learnpath.class.php 513 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739
  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. $categoryId = (int) $categoryId;
  711. // Session id.
  712. $session_id = api_get_session_id();
  713. $userId = empty($userId) ? api_get_user_id() : $userId;
  714. if (empty($publicated_on)) {
  715. $publicated_on = null;
  716. } else {
  717. $publicated_on = Database::escape_string(api_get_utc_datetime($publicated_on));
  718. }
  719. if (empty($expired_on)) {
  720. $expired_on = null;
  721. } else {
  722. $expired_on = Database::escape_string(api_get_utc_datetime($expired_on));
  723. }
  724. $check_name = "SELECT * FROM $tbl_lp
  725. WHERE c_id = $course_id AND name = '".Database::escape_string($name)."'";
  726. $res_name = Database::query($check_name);
  727. while (Database::num_rows($res_name)) {
  728. // There is already one such name, update the current one a bit.
  729. $i++;
  730. $name = $name.' - '.$i;
  731. $check_name = "SELECT * FROM $tbl_lp
  732. WHERE c_id = $course_id AND name = '".Database::escape_string($name)."' ";
  733. $res_name = Database::query($check_name);
  734. }
  735. // New name does not exist yet; keep it.
  736. // Escape description.
  737. // Kevin: added htmlentities().
  738. $description = Database::escape_string(api_htmlentities($description, ENT_QUOTES, $charset));
  739. $type = 1;
  740. switch ($learnpath) {
  741. case 'guess':
  742. break;
  743. case 'dokeos':
  744. case 'chamilo':
  745. $type = 1;
  746. break;
  747. case 'aicc':
  748. break;
  749. }
  750. switch ($origin) {
  751. case 'zip':
  752. // Check zip name string. If empty, we are currently creating a new Chamilo learnpath.
  753. break;
  754. case 'manual':
  755. default:
  756. $get_max = "SELECT MAX(display_order)
  757. FROM $tbl_lp WHERE c_id = $course_id";
  758. $res_max = Database::query($get_max);
  759. if (Database::num_rows($res_max) < 1) {
  760. $dsp = 1;
  761. } else {
  762. $row = Database::fetch_array($res_max);
  763. $dsp = $row[0] + 1;
  764. }
  765. $params = [
  766. 'c_id' => $course_id,
  767. 'lp_type' => $type,
  768. 'name' => $name,
  769. 'description' => $description,
  770. 'path' => '',
  771. 'default_view_mod' => 'embedded',
  772. 'default_encoding' => 'UTF-8',
  773. 'display_order' => $dsp,
  774. 'content_maker' => 'Chamilo',
  775. 'content_local' => 'local',
  776. 'js_lib' => '',
  777. 'session_id' => $session_id,
  778. 'created_on' => api_get_utc_datetime(),
  779. 'modified_on' => api_get_utc_datetime(),
  780. 'publicated_on' => $publicated_on,
  781. 'expired_on' => $expired_on,
  782. 'category_id' => $categoryId,
  783. 'force_commit' => 0,
  784. 'content_license' => '',
  785. 'debug' => 0,
  786. 'theme' => '',
  787. 'preview_image' => '',
  788. 'author' => '',
  789. 'prerequisite' => 0,
  790. 'hide_toc_frame' => 0,
  791. 'seriousgame_mode' => 0,
  792. 'autolaunch' => 0,
  793. 'max_attempts' => 0,
  794. 'subscribe_users' => 0,
  795. 'accumulate_scorm_time' => 1,
  796. ];
  797. $id = Database::insert($tbl_lp, $params);
  798. if ($id > 0) {
  799. $sql = "UPDATE $tbl_lp SET id = iid WHERE iid = $id";
  800. Database::query($sql);
  801. // Insert into item_property.
  802. api_item_property_update(
  803. $courseInfo,
  804. TOOL_LEARNPATH,
  805. $id,
  806. 'LearnpathAdded',
  807. $userId
  808. );
  809. api_set_default_visibility(
  810. $id,
  811. TOOL_LEARNPATH,
  812. 0,
  813. $courseInfo,
  814. $session_id,
  815. $userId
  816. );
  817. return $id;
  818. }
  819. break;
  820. }
  821. }
  822. /**
  823. * Auto completes the parents of an item in case it's been completed or passed.
  824. *
  825. * @param int $item Optional ID of the item from which to look for parents
  826. */
  827. public function autocomplete_parents($item)
  828. {
  829. $debug = $this->debug;
  830. if (empty($item)) {
  831. $item = $this->current;
  832. }
  833. $currentItem = $this->getItem($item);
  834. if ($currentItem) {
  835. $parent_id = $currentItem->get_parent();
  836. $parent = $this->getItem($parent_id);
  837. if ($parent) {
  838. // if $item points to an object and there is a parent.
  839. if ($debug) {
  840. error_log(
  841. 'Autocompleting parent of item '.$item.' '.
  842. $currentItem->get_title().'" (item '.$parent_id.' "'.$parent->get_title().'") ',
  843. 0
  844. );
  845. }
  846. // New experiment including failed and browsed in completed status.
  847. //$current_status = $currentItem->get_status();
  848. //if ($currentItem->is_done() || $current_status == 'browsed' || $current_status == 'failed') {
  849. // Fixes chapter auto complete
  850. if (true) {
  851. // If the current item is completed or passes or succeeded.
  852. $updateParentStatus = true;
  853. if ($debug) {
  854. error_log('Status of current item is alright');
  855. }
  856. foreach ($parent->get_children() as $childItemId) {
  857. $childItem = $this->getItem($childItemId);
  858. // If children was not set try to get the info
  859. if (empty($childItem->db_item_view_id)) {
  860. $childItem->set_lp_view($this->lp_view_id, $this->course_int_id);
  861. }
  862. // Check all his brothers (parent's children) for completion status.
  863. if ($childItemId != $item) {
  864. if ($debug) {
  865. error_log(
  866. 'Looking at brother #'.$childItemId.' "'.$childItem->get_title().'", status is '.$childItem->get_status(),
  867. 0
  868. );
  869. }
  870. // Trying completing parents of failed and browsed items as well.
  871. if ($childItem->status_is(
  872. [
  873. 'completed',
  874. 'passed',
  875. 'succeeded',
  876. 'browsed',
  877. 'failed',
  878. ]
  879. )
  880. ) {
  881. // Keep completion status to true.
  882. continue;
  883. } else {
  884. if ($debug > 2) {
  885. error_log(
  886. '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,
  887. 0
  888. );
  889. }
  890. $updateParentStatus = false;
  891. break;
  892. }
  893. }
  894. }
  895. if ($updateParentStatus) {
  896. // If all the children were completed:
  897. $parent->set_status('completed');
  898. $parent->save(false, $this->prerequisites_match($parent->get_id()));
  899. // Force the status to "completed"
  900. //$this->update_queue[$parent->get_id()] = $parent->get_status();
  901. $this->update_queue[$parent->get_id()] = 'completed';
  902. if ($debug) {
  903. error_log(
  904. 'Added parent #'.$parent->get_id().' "'.$parent->get_title().'" to update queue status: completed '.
  905. print_r($this->update_queue, 1),
  906. 0
  907. );
  908. }
  909. // Recursive call.
  910. $this->autocomplete_parents($parent->get_id());
  911. }
  912. }
  913. } else {
  914. if ($debug) {
  915. error_log("Parent #$parent_id does not exists");
  916. }
  917. }
  918. } else {
  919. if ($debug) {
  920. error_log("#$item is an item that doesn't have parents");
  921. }
  922. }
  923. }
  924. /**
  925. * Closes the current resource.
  926. *
  927. * Stops the timer
  928. * Saves into the database if required
  929. * Clears the current resource data from this object
  930. *
  931. * @return bool True on success, false on failure
  932. */
  933. public function close()
  934. {
  935. if (empty($this->lp_id)) {
  936. $this->error = 'Trying to close this learnpath but no ID is set';
  937. return false;
  938. }
  939. $this->current_time_stop = time();
  940. $this->ordered_items = [];
  941. $this->index = 0;
  942. unset($this->lp_id);
  943. //unset other stuff
  944. return true;
  945. }
  946. /**
  947. * Static admin function allowing removal of a learnpath.
  948. *
  949. * @param array $courseInfo
  950. * @param int $id Learnpath ID
  951. * @param string $delete Whether to delete data or keep it (default: 'keep', others: 'remove')
  952. *
  953. * @return bool True on success, false on failure (might change that to return number of elements deleted)
  954. */
  955. public function delete($courseInfo = null, $id = null, $delete = 'keep')
  956. {
  957. $course_id = api_get_course_int_id();
  958. if (!empty($courseInfo)) {
  959. $course_id = isset($courseInfo['real_id']) ? $courseInfo['real_id'] : $course_id;
  960. }
  961. // TODO: Implement a way of getting this to work when the current object is not set.
  962. // In clear: implement this in the item class as well (abstract class) and use the given ID in queries.
  963. // If an ID is specifically given and the current LP is not the same, prevent delete.
  964. if (!empty($id) && ($id != $this->lp_id)) {
  965. return false;
  966. }
  967. $lp = Database::get_course_table(TABLE_LP_MAIN);
  968. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  969. $lp_view = Database::get_course_table(TABLE_LP_VIEW);
  970. $lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  971. // Delete lp item id.
  972. foreach ($this->items as $lpItemId => $dummy) {
  973. $sql = "DELETE FROM $lp_item_view
  974. WHERE c_id = $course_id AND lp_item_id = '".$lpItemId."'";
  975. Database::query($sql);
  976. }
  977. // Proposed by Christophe (nickname: clefevre)
  978. $sql = "DELETE FROM $lp_item
  979. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  980. Database::query($sql);
  981. $sql = "DELETE FROM $lp_view
  982. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  983. Database::query($sql);
  984. self::toggle_publish($this->lp_id, 'i');
  985. if ($this->type == 2 || $this->type == 3) {
  986. // This is a scorm learning path, delete the files as well.
  987. $sql = "SELECT path FROM $lp
  988. WHERE iid = ".$this->lp_id;
  989. $res = Database::query($sql);
  990. if (Database::num_rows($res) > 0) {
  991. $row = Database::fetch_array($res);
  992. $path = $row['path'];
  993. $sql = "SELECT id FROM $lp
  994. WHERE
  995. c_id = $course_id AND
  996. path = '$path' AND
  997. iid != ".$this->lp_id;
  998. $res = Database::query($sql);
  999. if (Database::num_rows($res) > 0) {
  1000. // Another learning path uses this directory, so don't delete it.
  1001. if ($this->debug > 2) {
  1002. error_log('In learnpath::delete(), found other LP using path '.$path.', keeping directory', 0);
  1003. }
  1004. } else {
  1005. // No other LP uses that directory, delete it.
  1006. $course_rel_dir = api_get_course_path().'/scorm/'; // scorm dir web path starting from /courses
  1007. // The absolute system path for this course.
  1008. $course_scorm_dir = api_get_path(SYS_COURSE_PATH).$course_rel_dir;
  1009. if ($delete == 'remove' && is_dir($course_scorm_dir.$path) && !empty($course_scorm_dir)) {
  1010. if ($this->debug > 2) {
  1011. error_log('In learnpath::delete(), found SCORM, deleting directory: '.$course_scorm_dir.$path, 0);
  1012. }
  1013. // Proposed by Christophe (clefevre).
  1014. if (strcmp(substr($path, -2), "/.") == 0) {
  1015. $path = substr($path, 0, -1); // Remove "." at the end.
  1016. }
  1017. //exec('rm -rf ' . $course_scorm_dir . $path); // See Bug #5208, this is not OS-portable way.
  1018. rmdirr($course_scorm_dir.$path);
  1019. }
  1020. }
  1021. }
  1022. }
  1023. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  1024. $link = 'lp/lp_controller.php?action=view&lp_id='.$this->lp_id;
  1025. // Delete tools
  1026. $sql = "DELETE FROM $tbl_tool
  1027. WHERE c_id = $course_id AND (link LIKE '$link%' AND image='scormbuilder.gif')";
  1028. Database::query($sql);
  1029. $sql = "DELETE FROM $lp
  1030. WHERE iid = ".$this->lp_id;
  1031. Database::query($sql);
  1032. // Updates the display order of all lps.
  1033. $this->update_display_order();
  1034. api_item_property_update(
  1035. api_get_course_info(),
  1036. TOOL_LEARNPATH,
  1037. $this->lp_id,
  1038. 'delete',
  1039. api_get_user_id()
  1040. );
  1041. $link_info = GradebookUtils::isResourceInCourseGradebook(
  1042. api_get_course_id(),
  1043. 4,
  1044. $id,
  1045. api_get_session_id()
  1046. );
  1047. if ($link_info !== false) {
  1048. GradebookUtils::remove_resource_from_course_gradebook($link_info['id']);
  1049. }
  1050. if (api_get_setting('search_enabled') == 'true') {
  1051. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  1052. delete_all_values_for_item($this->cc, TOOL_LEARNPATH, $this->lp_id);
  1053. }
  1054. }
  1055. /**
  1056. * Removes all the children of one item - dangerous!
  1057. *
  1058. * @param int $id Element ID of which children have to be removed
  1059. *
  1060. * @return int Total number of children removed
  1061. */
  1062. public function delete_children_items($id)
  1063. {
  1064. $course_id = $this->course_info['real_id'];
  1065. $num = 0;
  1066. $id = (int) $id;
  1067. if (empty($id) || empty($course_id)) {
  1068. return false;
  1069. }
  1070. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1071. $sql = "SELECT * FROM $lp_item
  1072. WHERE c_id = $course_id AND parent_item_id = $id";
  1073. $res = Database::query($sql);
  1074. while ($row = Database::fetch_array($res)) {
  1075. $num += $this->delete_children_items($row['iid']);
  1076. $sql = "DELETE FROM $lp_item
  1077. WHERE c_id = $course_id AND iid = ".$row['iid'];
  1078. Database::query($sql);
  1079. $num++;
  1080. }
  1081. return $num;
  1082. }
  1083. /**
  1084. * Removes an item from the current learnpath.
  1085. *
  1086. * @param int $id Elem ID (0 if first)
  1087. *
  1088. * @return int Number of elements moved
  1089. *
  1090. * @todo implement resource removal
  1091. */
  1092. public function delete_item($id)
  1093. {
  1094. $course_id = api_get_course_int_id();
  1095. $id = (int) $id;
  1096. // TODO: Implement the resource removal.
  1097. if (empty($id) || empty($course_id)) {
  1098. return false;
  1099. }
  1100. // First select item to get previous, next, and display order.
  1101. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1102. $sql_sel = "SELECT * FROM $lp_item WHERE iid = $id";
  1103. $res_sel = Database::query($sql_sel);
  1104. if (Database::num_rows($res_sel) < 1) {
  1105. return false;
  1106. }
  1107. $row = Database::fetch_array($res_sel);
  1108. $previous = $row['previous_item_id'];
  1109. $next = $row['next_item_id'];
  1110. $display = $row['display_order'];
  1111. $parent = $row['parent_item_id'];
  1112. $lp = $row['lp_id'];
  1113. // Delete children items.
  1114. $this->delete_children_items($id);
  1115. // Now delete the item.
  1116. $sql_del = "DELETE FROM $lp_item WHERE iid = $id";
  1117. Database::query($sql_del);
  1118. // Now update surrounding items.
  1119. $sql_upd = "UPDATE $lp_item SET next_item_id = $next
  1120. WHERE iid = $previous";
  1121. Database::query($sql_upd);
  1122. $sql_upd = "UPDATE $lp_item SET previous_item_id = $previous
  1123. WHERE iid = $next AND item_type != '".TOOL_LP_FINAL_ITEM."'";
  1124. Database::query($sql_upd);
  1125. // Now update all following items with new display order.
  1126. $sql_all = "UPDATE $lp_item SET display_order = display_order-1
  1127. WHERE
  1128. c_id = $course_id AND
  1129. lp_id = $lp AND
  1130. parent_item_id = $parent AND
  1131. display_order > $display";
  1132. Database::query($sql_all);
  1133. //Removing prerequisites since the item will not longer exist
  1134. $sql_all = "UPDATE $lp_item SET prerequisite = ''
  1135. WHERE c_id = $course_id AND prerequisite = $id";
  1136. Database::query($sql_all);
  1137. $sql = "UPDATE $lp_item
  1138. SET previous_item_id = ".$this->getLastInFirstLevel()."
  1139. WHERE c_id = $course_id AND lp_id = {$this->lp_id} AND item_type = '".TOOL_LP_FINAL_ITEM."'";
  1140. Database::query($sql);
  1141. // Remove from search engine if enabled.
  1142. if (api_get_setting('search_enabled') === 'true') {
  1143. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  1144. $sql = 'SELECT * FROM %s
  1145. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
  1146. LIMIT 1';
  1147. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp, $id);
  1148. $res = Database::query($sql);
  1149. if (Database::num_rows($res) > 0) {
  1150. $row2 = Database::fetch_array($res);
  1151. $di = new ChamiloIndexer();
  1152. $di->remove_document($row2['search_did']);
  1153. }
  1154. $sql = 'DELETE FROM %s
  1155. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
  1156. LIMIT 1';
  1157. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp, $id);
  1158. Database::query($sql);
  1159. }
  1160. }
  1161. /**
  1162. * Updates an item's content in place.
  1163. *
  1164. * @param int $id Element ID
  1165. * @param int $parent Parent item ID
  1166. * @param int $previous Previous item ID
  1167. * @param string $title Item title
  1168. * @param string $description Item description
  1169. * @param string $prerequisites Prerequisites (optional)
  1170. * @param array $audio The array resulting of the $_FILES[mp3] element
  1171. * @param int $max_time_allowed
  1172. * @param string $url
  1173. *
  1174. * @return bool True on success, false on error
  1175. */
  1176. public function edit_item(
  1177. $id,
  1178. $parent,
  1179. $previous,
  1180. $title,
  1181. $description,
  1182. $prerequisites = '0',
  1183. $audio = [],
  1184. $max_time_allowed = 0,
  1185. $url = ''
  1186. ) {
  1187. $course_id = api_get_course_int_id();
  1188. $_course = api_get_course_info();
  1189. $id = (int) $id;
  1190. if (empty($max_time_allowed)) {
  1191. $max_time_allowed = 0;
  1192. }
  1193. if (empty($id) || empty($_course)) {
  1194. return false;
  1195. }
  1196. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1197. $sql = "SELECT * FROM $tbl_lp_item
  1198. WHERE iid = $id";
  1199. $res_select = Database::query($sql);
  1200. $row_select = Database::fetch_array($res_select);
  1201. $audio_update_sql = '';
  1202. if (is_array($audio) && !empty($audio['tmp_name']) && $audio['error'] === 0) {
  1203. // Create the audio folder if it does not exist yet.
  1204. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  1205. if (!is_dir($filepath.'audio')) {
  1206. mkdir($filepath.'audio', api_get_permissions_for_new_directories());
  1207. $audio_id = add_document(
  1208. $_course,
  1209. '/audio',
  1210. 'folder',
  1211. 0,
  1212. 'audio'
  1213. );
  1214. api_item_property_update(
  1215. $_course,
  1216. TOOL_DOCUMENT,
  1217. $audio_id,
  1218. 'FolderCreated',
  1219. api_get_user_id(),
  1220. null,
  1221. null,
  1222. null,
  1223. null,
  1224. api_get_session_id()
  1225. );
  1226. api_item_property_update(
  1227. $_course,
  1228. TOOL_DOCUMENT,
  1229. $audio_id,
  1230. 'invisible',
  1231. api_get_user_id(),
  1232. null,
  1233. null,
  1234. null,
  1235. null,
  1236. api_get_session_id()
  1237. );
  1238. }
  1239. // Upload file in documents.
  1240. $pi = pathinfo($audio['name']);
  1241. if ($pi['extension'] === 'mp3') {
  1242. $c_det = api_get_course_info($this->cc);
  1243. $bp = api_get_path(SYS_COURSE_PATH).$c_det['path'].'/document';
  1244. $path = handle_uploaded_document(
  1245. $c_det,
  1246. $audio,
  1247. $bp,
  1248. '/audio',
  1249. api_get_user_id(),
  1250. 0,
  1251. null,
  1252. 0,
  1253. 'rename',
  1254. false,
  1255. 0
  1256. );
  1257. $path = substr($path, 7);
  1258. // Update reference in lp_item - audio path is the path from inside de document/audio/ dir.
  1259. $audio_update_sql = ", audio = '".Database::escape_string($path)."' ";
  1260. }
  1261. }
  1262. $same_parent = $row_select['parent_item_id'] == $parent ? true : false;
  1263. $same_previous = $row_select['previous_item_id'] == $previous ? true : false;
  1264. // TODO: htmlspecialchars to be checked for encoding related problems.
  1265. if ($same_parent && $same_previous) {
  1266. // Only update title and description.
  1267. $sql = "UPDATE $tbl_lp_item
  1268. SET title = '".Database::escape_string($title)."',
  1269. prerequisite = '".$prerequisites."',
  1270. description = '".Database::escape_string($description)."'
  1271. ".$audio_update_sql.",
  1272. max_time_allowed = '".Database::escape_string($max_time_allowed)."'
  1273. WHERE iid = $id";
  1274. Database::query($sql);
  1275. } else {
  1276. $old_parent = $row_select['parent_item_id'];
  1277. $old_previous = $row_select['previous_item_id'];
  1278. $old_next = $row_select['next_item_id'];
  1279. $old_order = $row_select['display_order'];
  1280. $old_prerequisite = $row_select['prerequisite'];
  1281. $old_max_time_allowed = $row_select['max_time_allowed'];
  1282. /* BEGIN -- virtually remove the current item id */
  1283. /* for the next and previous item it is like the current item doesn't exist anymore */
  1284. if ($old_previous != 0) {
  1285. // Next
  1286. $sql = "UPDATE $tbl_lp_item
  1287. SET next_item_id = $old_next
  1288. WHERE iid = $old_previous";
  1289. Database::query($sql);
  1290. }
  1291. if (!empty($old_next)) {
  1292. // Previous
  1293. $sql = "UPDATE $tbl_lp_item
  1294. SET previous_item_id = $old_previous
  1295. WHERE iid = $old_next";
  1296. Database::query($sql);
  1297. }
  1298. // display_order - 1 for every item with a display_order
  1299. // bigger then the display_order of the current item.
  1300. $sql = "UPDATE $tbl_lp_item
  1301. SET display_order = display_order - 1
  1302. WHERE
  1303. c_id = $course_id AND
  1304. display_order > $old_order AND
  1305. lp_id = ".$this->lp_id." AND
  1306. parent_item_id = $old_parent";
  1307. Database::query($sql);
  1308. /* END -- virtually remove the current item id */
  1309. /* BEGIN -- update the current item id to his new location */
  1310. if ($previous == 0) {
  1311. // Select the data of the item that should come after the current item.
  1312. $sql = "SELECT id, display_order
  1313. FROM $tbl_lp_item
  1314. WHERE
  1315. c_id = $course_id AND
  1316. lp_id = ".$this->lp_id." AND
  1317. parent_item_id = $parent AND
  1318. previous_item_id = $previous";
  1319. $res_select_old = Database::query($sql);
  1320. $row_select_old = Database::fetch_array($res_select_old);
  1321. // If the new parent didn't have children before.
  1322. if (Database::num_rows($res_select_old) == 0) {
  1323. $new_next = 0;
  1324. $new_order = 1;
  1325. } else {
  1326. $new_next = $row_select_old['id'];
  1327. $new_order = $row_select_old['display_order'];
  1328. }
  1329. } else {
  1330. // Select the data of the item that should come before the current item.
  1331. $sql = "SELECT next_item_id, display_order
  1332. FROM $tbl_lp_item
  1333. WHERE iid = $previous";
  1334. $res_select_old = Database::query($sql);
  1335. $row_select_old = Database::fetch_array($res_select_old);
  1336. $new_next = $row_select_old['next_item_id'];
  1337. $new_order = $row_select_old['display_order'] + 1;
  1338. }
  1339. // TODO: htmlspecialchars to be checked for encoding related problems.
  1340. // Update the current item with the new data.
  1341. $sql = "UPDATE $tbl_lp_item
  1342. SET
  1343. title = '".Database::escape_string($title)."',
  1344. description = '".Database::escape_string($description)."',
  1345. parent_item_id = $parent,
  1346. previous_item_id = $previous,
  1347. next_item_id = $new_next,
  1348. display_order = $new_order
  1349. $audio_update_sql
  1350. WHERE iid = $id";
  1351. Database::query($sql);
  1352. if ($previous != 0) {
  1353. // Update the previous item's next_item_id.
  1354. $sql = "UPDATE $tbl_lp_item
  1355. SET next_item_id = $id
  1356. WHERE iid = $previous";
  1357. Database::query($sql);
  1358. }
  1359. if (!empty($new_next)) {
  1360. // Update the next item's previous_item_id.
  1361. $sql = "UPDATE $tbl_lp_item
  1362. SET previous_item_id = $id
  1363. WHERE iid = $new_next";
  1364. Database::query($sql);
  1365. }
  1366. if ($old_prerequisite != $prerequisites) {
  1367. $sql = "UPDATE $tbl_lp_item
  1368. SET prerequisite = '$prerequisites'
  1369. WHERE iid = $id";
  1370. Database::query($sql);
  1371. }
  1372. if ($old_max_time_allowed != $max_time_allowed) {
  1373. // update max time allowed
  1374. $sql = "UPDATE $tbl_lp_item
  1375. SET max_time_allowed = $max_time_allowed
  1376. WHERE iid = $id";
  1377. Database::query($sql);
  1378. }
  1379. // Update all the items with the same or a bigger display_order than the current item.
  1380. $sql = "UPDATE $tbl_lp_item
  1381. SET display_order = display_order + 1
  1382. WHERE
  1383. c_id = $course_id AND
  1384. lp_id = ".$this->get_id()." AND
  1385. iid <> $id AND
  1386. parent_item_id = $parent AND
  1387. display_order >= $new_order";
  1388. Database::query($sql);
  1389. }
  1390. if ($row_select['item_type'] == 'link') {
  1391. $link = new Link();
  1392. $linkId = $row_select['path'];
  1393. $link->updateLink($linkId, $url);
  1394. }
  1395. }
  1396. /**
  1397. * Updates an item's prereq in place.
  1398. *
  1399. * @param int $id Element ID
  1400. * @param string $prerequisite_id Prerequisite Element ID
  1401. * @param int $minScore Prerequisite min score
  1402. * @param int $maxScore Prerequisite max score
  1403. *
  1404. * @return bool True on success, false on error
  1405. */
  1406. public function edit_item_prereq(
  1407. $id,
  1408. $prerequisite_id,
  1409. $minScore = 0,
  1410. $maxScore = 100
  1411. ) {
  1412. $id = (int) $id;
  1413. $prerequisite_id = (int) $prerequisite_id;
  1414. if (empty($id)) {
  1415. return false;
  1416. }
  1417. if (empty($minScore) || $minScore < 0) {
  1418. $minScore = 0;
  1419. }
  1420. if (empty($maxScore) || $maxScore < 0) {
  1421. $maxScore = 100;
  1422. }
  1423. $minScore = floatval($minScore);
  1424. $maxScore = floatval($maxScore);
  1425. if (empty($prerequisite_id)) {
  1426. $prerequisite_id = 'NULL';
  1427. $minScore = 0;
  1428. $maxScore = 100;
  1429. }
  1430. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1431. $sql = " UPDATE $tbl_lp_item
  1432. SET
  1433. prerequisite = $prerequisite_id ,
  1434. prerequisite_min_score = $minScore ,
  1435. prerequisite_max_score = $maxScore
  1436. WHERE iid = $id";
  1437. Database::query($sql);
  1438. return true;
  1439. }
  1440. /**
  1441. * Gets all the chapters belonging to the same parent as the item/chapter given
  1442. * Can also be called as abstract method.
  1443. *
  1444. * @deprecated not used
  1445. *
  1446. * @param int $id Item ID
  1447. *
  1448. * @return array A list of all the "brother items" (or an empty array on failure)
  1449. */
  1450. public function getSiblingDirectories($id)
  1451. {
  1452. $course_id = api_get_course_int_id();
  1453. if (empty($id) || $id != strval(intval($id))) {
  1454. return [];
  1455. }
  1456. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1457. $sql_parent = "SELECT * FROM $lp_item
  1458. WHERE iid = $id AND item_type='dir'";
  1459. $res_parent = Database::query($sql_parent);
  1460. if (Database::num_rows($res_parent) > 0) {
  1461. $row_parent = Database::fetch_array($res_parent);
  1462. $parent = $row_parent['parent_item_id'];
  1463. $sql = "SELECT * FROM $lp_item
  1464. WHERE
  1465. parent_item_id = $parent AND
  1466. iid = $id AND
  1467. item_type='dir'
  1468. ORDER BY display_order";
  1469. $res_bros = Database::query($sql);
  1470. $list = [];
  1471. while ($row_bro = Database::fetch_array($res_bros)) {
  1472. $list[] = $row_bro;
  1473. }
  1474. return $list;
  1475. }
  1476. return [];
  1477. }
  1478. /**
  1479. * Gets all the items belonging to the same parent as the item given
  1480. * Can also be called as abstract method.
  1481. *
  1482. * @deprecated not used
  1483. *
  1484. * @param int $id Item ID
  1485. *
  1486. * @return array A list of all the "brother items" (or an empty array on failure)
  1487. */
  1488. public function get_brother_items($id)
  1489. {
  1490. $course_id = api_get_course_int_id();
  1491. if (empty($id) || $id != strval(intval($id))) {
  1492. return [];
  1493. }
  1494. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1495. $sql_parent = "SELECT * FROM $lp_item
  1496. WHERE iid = $id";
  1497. $res_parent = Database::query($sql_parent);
  1498. if (Database::num_rows($res_parent) > 0) {
  1499. $row_parent = Database::fetch_array($res_parent);
  1500. $parent = $row_parent['parent_item_id'];
  1501. $sql = "SELECT * FROM $lp_item
  1502. WHERE c_id = $course_id AND parent_item_id = $parent
  1503. ORDER BY display_order";
  1504. $res_bros = Database::query($sql);
  1505. $list = [];
  1506. while ($row_bro = Database::fetch_array($res_bros)) {
  1507. $list[] = $row_bro;
  1508. }
  1509. return $list;
  1510. }
  1511. return [];
  1512. }
  1513. /**
  1514. * Get the specific prefix index terms of this learning path.
  1515. *
  1516. * @param string $prefix
  1517. *
  1518. * @return array Array of terms
  1519. */
  1520. public function get_common_index_terms_by_prefix($prefix)
  1521. {
  1522. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  1523. $terms = get_specific_field_values_list_by_prefix(
  1524. $prefix,
  1525. $this->cc,
  1526. TOOL_LEARNPATH,
  1527. $this->lp_id
  1528. );
  1529. $prefix_terms = [];
  1530. if (!empty($terms)) {
  1531. foreach ($terms as $term) {
  1532. $prefix_terms[] = $term['value'];
  1533. }
  1534. }
  1535. return $prefix_terms;
  1536. }
  1537. /**
  1538. * Gets the number of items currently completed.
  1539. *
  1540. * @param bool $failedStatusException flag to determine the failed status is not considered progressed
  1541. *
  1542. * @return int The number of items currently completed
  1543. */
  1544. public function get_complete_items_count($failedStatusException = false)
  1545. {
  1546. $i = 0;
  1547. $completedStatusList = [
  1548. 'completed',
  1549. 'passed',
  1550. 'succeeded',
  1551. 'browsed',
  1552. ];
  1553. if (!$failedStatusException) {
  1554. $completedStatusList[] = 'failed';
  1555. }
  1556. foreach ($this->items as $id => $dummy) {
  1557. // Trying failed and browsed considered "progressed" as well.
  1558. if ($this->items[$id]->status_is($completedStatusList) &&
  1559. $this->items[$id]->get_type() != 'dir'
  1560. ) {
  1561. $i++;
  1562. }
  1563. }
  1564. return $i;
  1565. }
  1566. /**
  1567. * Gets the current item ID.
  1568. *
  1569. * @return int The current learnpath item id
  1570. */
  1571. public function get_current_item_id()
  1572. {
  1573. $current = 0;
  1574. if (!empty($this->current)) {
  1575. $current = (int) $this->current;
  1576. }
  1577. return $current;
  1578. }
  1579. /**
  1580. * Force to get the first learnpath item id.
  1581. *
  1582. * @return int The current learnpath item id
  1583. */
  1584. public function get_first_item_id()
  1585. {
  1586. $current = 0;
  1587. if (is_array($this->ordered_items)) {
  1588. $current = $this->ordered_items[0];
  1589. }
  1590. return $current;
  1591. }
  1592. /**
  1593. * Gets the total number of items available for viewing in this SCORM.
  1594. *
  1595. * @return int The total number of items
  1596. */
  1597. public function get_total_items_count()
  1598. {
  1599. return count($this->items);
  1600. }
  1601. /**
  1602. * Gets the total number of items available for viewing in this SCORM but without chapters.
  1603. *
  1604. * @return int The total no-chapters number of items
  1605. */
  1606. public function getTotalItemsCountWithoutDirs()
  1607. {
  1608. $total = 0;
  1609. $typeListNotToCount = self::getChapterTypes();
  1610. foreach ($this->items as $temp2) {
  1611. if (!in_array($temp2->get_type(), $typeListNotToCount)) {
  1612. $total++;
  1613. }
  1614. }
  1615. return $total;
  1616. }
  1617. /**
  1618. * Sets the first element URL.
  1619. */
  1620. public function first()
  1621. {
  1622. if ($this->debug > 0) {
  1623. error_log('In learnpath::first()', 0);
  1624. error_log('$this->last_item_seen '.$this->last_item_seen);
  1625. }
  1626. // Test if the last_item_seen exists and is not a dir.
  1627. if (count($this->ordered_items) == 0) {
  1628. $this->index = 0;
  1629. }
  1630. if (!empty($this->last_item_seen) &&
  1631. !empty($this->items[$this->last_item_seen]) &&
  1632. $this->items[$this->last_item_seen]->get_type() != 'dir'
  1633. //with this change (below) the LP will NOT go to the next item, it will take lp item we left
  1634. //&& !$this->items[$this->last_item_seen]->is_done()
  1635. ) {
  1636. if ($this->debug > 2) {
  1637. error_log(
  1638. 'In learnpath::first() - Last item seen is '.$this->last_item_seen.' of type '.
  1639. $this->items[$this->last_item_seen]->get_type()
  1640. );
  1641. }
  1642. $index = -1;
  1643. foreach ($this->ordered_items as $myindex => $item_id) {
  1644. if ($item_id == $this->last_item_seen) {
  1645. $index = $myindex;
  1646. break;
  1647. }
  1648. }
  1649. if ($index == -1) {
  1650. // Index hasn't changed, so item not found - panic (this shouldn't happen).
  1651. if ($this->debug > 2) {
  1652. error_log('Last item ('.$this->last_item_seen.') was found in items but not in ordered_items, panic!', 0);
  1653. }
  1654. return false;
  1655. } else {
  1656. $this->last = $this->last_item_seen;
  1657. $this->current = $this->last_item_seen;
  1658. $this->index = $index;
  1659. }
  1660. } else {
  1661. if ($this->debug > 2) {
  1662. error_log('In learnpath::first() - No last item seen', 0);
  1663. }
  1664. $index = 0;
  1665. // Loop through all ordered items and stop at the first item that is
  1666. // not a directory *and* that has not been completed yet.
  1667. while (!empty($this->ordered_items[$index]) &&
  1668. is_a($this->items[$this->ordered_items[$index]], 'learnpathItem') &&
  1669. (
  1670. $this->items[$this->ordered_items[$index]]->get_type() == 'dir' ||
  1671. $this->items[$this->ordered_items[$index]]->is_done() === true
  1672. ) && $index < $this->max_ordered_items) {
  1673. $index++;
  1674. }
  1675. $this->last = $this->current;
  1676. // current is
  1677. $this->current = isset($this->ordered_items[$index]) ? $this->ordered_items[$index] : null;
  1678. $this->index = $index;
  1679. if ($this->debug > 2) {
  1680. error_log('$index '.$index);
  1681. error_log('In learnpath::first() - No last item seen');
  1682. error_log('New last = '.$this->last.'('.$this->ordered_items[$index].')');
  1683. }
  1684. }
  1685. if ($this->debug > 2) {
  1686. error_log('In learnpath::first() - First item is '.$this->get_current_item_id());
  1687. }
  1688. }
  1689. /**
  1690. * Gets the js library from the database.
  1691. *
  1692. * @return string The name of the javascript library to be used
  1693. */
  1694. public function get_js_lib()
  1695. {
  1696. $lib = '';
  1697. if (!empty($this->js_lib)) {
  1698. $lib = $this->js_lib;
  1699. }
  1700. return $lib;
  1701. }
  1702. /**
  1703. * Gets the learnpath database ID.
  1704. *
  1705. * @return int Learnpath ID in the lp table
  1706. */
  1707. public function get_id()
  1708. {
  1709. if (!empty($this->lp_id)) {
  1710. return (int) $this->lp_id;
  1711. }
  1712. return 0;
  1713. }
  1714. /**
  1715. * Gets the last element URL.
  1716. *
  1717. * @return string URL to load into the viewer
  1718. */
  1719. public function get_last()
  1720. {
  1721. // This is just in case the lesson doesn't cointain a valid scheme, just to avoid "Notices"
  1722. if (count($this->ordered_items) > 0) {
  1723. $this->index = count($this->ordered_items) - 1;
  1724. return $this->ordered_items[$this->index];
  1725. }
  1726. return false;
  1727. }
  1728. /**
  1729. * Get the last element in the first level.
  1730. * Unlike learnpath::get_last this function doesn't consider the subsection' elements.
  1731. *
  1732. * @return mixed
  1733. */
  1734. public function getLastInFirstLevel()
  1735. {
  1736. try {
  1737. $lastId = Database::getManager()
  1738. ->createQuery('SELECT i.iid FROM ChamiloCourseBundle:CLpItem i
  1739. WHERE i.lpId = :lp AND i.parentItemId = 0 AND i.itemType != :type ORDER BY i.displayOrder DESC')
  1740. ->setMaxResults(1)
  1741. ->setParameters(['lp' => $this->lp_id, 'type' => TOOL_LP_FINAL_ITEM])
  1742. ->getSingleScalarResult();
  1743. return $lastId;
  1744. } catch (Exception $exception) {
  1745. return 0;
  1746. }
  1747. }
  1748. /**
  1749. * Gets the navigation bar for the learnpath display screen.
  1750. *
  1751. * @param string $barId
  1752. *
  1753. * @return string The HTML string to use as a navigation bar
  1754. */
  1755. public function get_navigation_bar($barId = '')
  1756. {
  1757. if (empty($barId)) {
  1758. $barId = 'control-top';
  1759. }
  1760. $lpId = $this->lp_id;
  1761. $mycurrentitemid = $this->get_current_item_id();
  1762. $reportingText = get_lang('Reporting');
  1763. $previousText = get_lang('ScormPrevious');
  1764. $nextText = get_lang('ScormNext');
  1765. $fullScreenText = get_lang('ScormExitFullScreen');
  1766. $settings = api_get_configuration_value('lp_view_settings');
  1767. $display = isset($settings['display']) ? $settings['display'] : false;
  1768. $reportingIcon = '
  1769. <a class="icon-toolbar"
  1770. id="stats_link"
  1771. href="lp_controller.php?action=stats&'.api_get_cidreq(true).'&lp_id='.$lpId.'"
  1772. onclick="window.parent.API.save_asset(); return true;"
  1773. target="content_name" title="'.$reportingText.'">
  1774. <span class="fa fa-info"></span><span class="sr-only">'.$reportingText.'</span>
  1775. </a>';
  1776. if (!empty($display)) {
  1777. $showReporting = isset($display['show_reporting_icon']) ? $display['show_reporting_icon'] : true;
  1778. if ($showReporting === false) {
  1779. $reportingIcon = '';
  1780. }
  1781. }
  1782. $hideArrows = false;
  1783. if (isset($settings['display']) && isset($settings['display']['hide_lp_arrow_navigation'])) {
  1784. $hideArrows = $settings['display']['hide_lp_arrow_navigation'];
  1785. }
  1786. $previousIcon = '';
  1787. $nextIcon = '';
  1788. if ($hideArrows === false) {
  1789. $previousIcon = '
  1790. <a class="icon-toolbar" id="scorm-previous" href="#"
  1791. onclick="switch_item('.$mycurrentitemid.',\'previous\');return false;" title="'.$previousText.'">
  1792. <span class="fa fa-chevron-left"></span><span class="sr-only">'.$previousText.'</span>
  1793. </a>';
  1794. $nextIcon = '
  1795. <a class="icon-toolbar" id="scorm-next" href="#"
  1796. onclick="switch_item('.$mycurrentitemid.',\'next\');return false;" title="'.$nextText.'">
  1797. <span class="fa fa-chevron-right"></span><span class="sr-only">'.$nextText.'</span>
  1798. </a>';
  1799. }
  1800. if ($this->mode === 'fullscreen') {
  1801. $navbar = '
  1802. <span id="'.$barId.'" class="buttons">
  1803. '.$reportingIcon.'
  1804. '.$previousIcon.'
  1805. '.$nextIcon.'
  1806. <a class="icon-toolbar" id="view-embedded"
  1807. href="lp_controller.php?action=mode&mode=embedded" target="_top" title="'.$fullScreenText.'">
  1808. <span class="fa fa-columns"></span><span class="sr-only">'.$fullScreenText.'</span>
  1809. </a>
  1810. </span>';
  1811. } else {
  1812. $navbar = '
  1813. <span id="'.$barId.'" class="buttons text-right">
  1814. '.$reportingIcon.'
  1815. '.$previousIcon.'
  1816. '.$nextIcon.'
  1817. </span>';
  1818. }
  1819. return $navbar;
  1820. }
  1821. /**
  1822. * Gets the next resource in queue (url).
  1823. *
  1824. * @return string URL to load into the viewer
  1825. */
  1826. public function get_next_index()
  1827. {
  1828. // TODO
  1829. $index = $this->index;
  1830. $index++;
  1831. while (
  1832. !empty($this->ordered_items[$index]) && ($this->items[$this->ordered_items[$index]]->get_type() == 'dir') &&
  1833. $index < $this->max_ordered_items
  1834. ) {
  1835. $index++;
  1836. if ($index == $this->max_ordered_items) {
  1837. if ($this->items[$this->ordered_items[$index]]->get_type() == 'dir') {
  1838. return $this->index;
  1839. }
  1840. return $index;
  1841. }
  1842. }
  1843. if (empty($this->ordered_items[$index])) {
  1844. return $this->index;
  1845. }
  1846. return $index;
  1847. }
  1848. /**
  1849. * Gets item_id for the next element.
  1850. *
  1851. * @return int Next item (DB) ID
  1852. */
  1853. public function get_next_item_id()
  1854. {
  1855. $new_index = $this->get_next_index();
  1856. if (!empty($new_index)) {
  1857. if (isset($this->ordered_items[$new_index])) {
  1858. return $this->ordered_items[$new_index];
  1859. }
  1860. }
  1861. return 0;
  1862. }
  1863. /**
  1864. * Returns the package type ('scorm','aicc','scorm2004','dokeos','ppt'...).
  1865. *
  1866. * Generally, the package provided is in the form of a zip file, so the function
  1867. * has been written to test a zip file. If not a zip, the function will return the
  1868. * default return value: ''
  1869. *
  1870. * @param string $file_path the path to the file
  1871. * @param string $file_name the original name of the file
  1872. *
  1873. * @return string 'scorm','aicc','scorm2004','dokeos' or '' if the package cannot be recognized
  1874. */
  1875. public static function get_package_type($file_path, $file_name)
  1876. {
  1877. // Get name of the zip file without the extension.
  1878. $file_info = pathinfo($file_name);
  1879. $extension = $file_info['extension']; // Extension only.
  1880. if (!empty($_POST['ppt2lp']) && !in_array(strtolower($extension), [
  1881. 'dll',
  1882. 'exe',
  1883. ])) {
  1884. return 'oogie';
  1885. }
  1886. if (!empty($_POST['woogie']) && !in_array(strtolower($extension), [
  1887. 'dll',
  1888. 'exe',
  1889. ])) {
  1890. return 'woogie';
  1891. }
  1892. $zipFile = new PclZip($file_path);
  1893. // Check the zip content (real size and file extension).
  1894. $zipContentArray = $zipFile->listContent();
  1895. $package_type = '';
  1896. $manifest = '';
  1897. $aicc_match_crs = 0;
  1898. $aicc_match_au = 0;
  1899. $aicc_match_des = 0;
  1900. $aicc_match_cst = 0;
  1901. // The following loop should be stopped as soon as we found the right imsmanifest.xml (how to recognize it?).
  1902. if (is_array($zipContentArray) && count($zipContentArray) > 0) {
  1903. foreach ($zipContentArray as $thisContent) {
  1904. if (preg_match('~.(php.*|phtml)$~i', $thisContent['filename'])) {
  1905. // New behaviour: Don't do anything. These files will be removed in scorm::import_package.
  1906. } elseif (stristr($thisContent['filename'], 'imsmanifest.xml') !== false) {
  1907. $manifest = $thisContent['filename']; // Just the relative directory inside scorm/
  1908. $package_type = 'scorm';
  1909. break; // Exit the foreach loop.
  1910. } elseif (
  1911. preg_match('/aicc\//i', $thisContent['filename']) ||
  1912. in_array(
  1913. strtolower(pathinfo($thisContent['filename'], PATHINFO_EXTENSION)),
  1914. ['crs', 'au', 'des', 'cst']
  1915. )
  1916. ) {
  1917. $ext = strtolower(pathinfo($thisContent['filename'], PATHINFO_EXTENSION));
  1918. switch ($ext) {
  1919. case 'crs':
  1920. $aicc_match_crs = 1;
  1921. break;
  1922. case 'au':
  1923. $aicc_match_au = 1;
  1924. break;
  1925. case 'des':
  1926. $aicc_match_des = 1;
  1927. break;
  1928. case 'cst':
  1929. $aicc_match_cst = 1;
  1930. break;
  1931. default:
  1932. break;
  1933. }
  1934. //break; // Don't exit the loop, because if we find an imsmanifest afterwards, we want it, not the AICC.
  1935. } else {
  1936. $package_type = '';
  1937. }
  1938. }
  1939. }
  1940. if (empty($package_type) && 4 == ($aicc_match_crs + $aicc_match_au + $aicc_match_des + $aicc_match_cst)) {
  1941. // If found an aicc directory... (!= false means it cannot be false (error) or 0 (no match)).
  1942. $package_type = 'aicc';
  1943. }
  1944. // Try with chamilo course builder
  1945. if (empty($package_type)) {
  1946. $package_type = 'chamilo';
  1947. }
  1948. return $package_type;
  1949. }
  1950. /**
  1951. * Gets the previous resource in queue (url). Also initialises time values for this viewing.
  1952. *
  1953. * @return string URL to load into the viewer
  1954. */
  1955. public function get_previous_index()
  1956. {
  1957. $index = $this->index;
  1958. if (isset($this->ordered_items[$index - 1])) {
  1959. $index--;
  1960. while (isset($this->ordered_items[$index]) &&
  1961. ($this->items[$this->ordered_items[$index]]->get_type() == 'dir')
  1962. ) {
  1963. $index--;
  1964. if ($index < 0) {
  1965. return $this->index;
  1966. }
  1967. }
  1968. }
  1969. return $index;
  1970. }
  1971. /**
  1972. * Gets item_id for the next element.
  1973. *
  1974. * @return int Previous item (DB) ID
  1975. */
  1976. public function get_previous_item_id()
  1977. {
  1978. $index = $this->get_previous_index();
  1979. return $this->ordered_items[$index];
  1980. }
  1981. /**
  1982. * Returns the HTML necessary to print a mediaplayer block inside a page.
  1983. *
  1984. * @param int $lpItemId
  1985. * @param string $autostart
  1986. *
  1987. * @return string The mediaplayer HTML
  1988. */
  1989. public function get_mediaplayer($lpItemId, $autostart = 'true')
  1990. {
  1991. $course_id = api_get_course_int_id();
  1992. $_course = api_get_course_info();
  1993. if (empty($_course)) {
  1994. return '';
  1995. }
  1996. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1997. $tbl_lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  1998. $lpItemId = (int) $lpItemId;
  1999. /** @var learnpathItem $item */
  2000. $item = isset($this->items[$lpItemId]) ? $this->items[$lpItemId] : null;
  2001. $itemViewId = 0;
  2002. if ($item) {
  2003. $itemViewId = (int) $item->db_item_view_id;
  2004. }
  2005. // Getting all the information about the item.
  2006. $sql = "SELECT lpi.audio, lpi.item_type, lp_view.status
  2007. FROM $tbl_lp_item as lpi
  2008. INNER JOIN $tbl_lp_item_view as lp_view
  2009. ON (lpi.iid = lp_view.lp_item_id)
  2010. WHERE
  2011. lp_view.iid = $itemViewId AND
  2012. lpi.iid = $lpItemId AND
  2013. lp_view.c_id = $course_id";
  2014. $result = Database::query($sql);
  2015. $row = Database::fetch_assoc($result);
  2016. $output = '';
  2017. if (!empty($row['audio'])) {
  2018. $list = $_SESSION['oLP']->get_toc();
  2019. switch ($row['item_type']) {
  2020. case 'quiz':
  2021. $type_quiz = false;
  2022. foreach ($list as $toc) {
  2023. if ($toc['id'] == $_SESSION['oLP']->current) {
  2024. $type_quiz = true;
  2025. }
  2026. }
  2027. if ($type_quiz) {
  2028. if ($_SESSION['oLP']->prevent_reinit == 1) {
  2029. $autostart_audio = $row['status'] === 'completed' ? 'false' : 'true';
  2030. } else {
  2031. $autostart_audio = $autostart;
  2032. }
  2033. }
  2034. break;
  2035. case TOOL_READOUT_TEXT:;
  2036. $autostart_audio = 'false';
  2037. break;
  2038. default:
  2039. $autostart_audio = 'true';
  2040. }
  2041. $courseInfo = api_get_course_info();
  2042. $audio = $row['audio'];
  2043. $file = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/audio/'.$audio;
  2044. $url = api_get_path(WEB_COURSE_PATH).$courseInfo['path'].'/document/audio/'.$audio.'?'.api_get_cidreq();
  2045. if (!file_exists($file)) {
  2046. $lpPathInfo = $_SESSION['oLP']->generate_lp_folder(api_get_course_info());
  2047. $file = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.$lpPathInfo['dir'].$audio;
  2048. $url = api_get_path(WEB_COURSE_PATH).$_course['path'].'/document'.$lpPathInfo['dir'].$audio.'?'.api_get_cidreq();
  2049. }
  2050. $player = Display::getMediaPlayer(
  2051. $file,
  2052. [
  2053. 'id' => 'lp_audio_media_player',
  2054. 'url' => $url,
  2055. 'autoplay' => $autostart_audio,
  2056. 'width' => '100%',
  2057. ]
  2058. );
  2059. // The mp3 player.
  2060. $output = '<div id="container">';
  2061. $output .= $player;
  2062. $output .= '</div>';
  2063. }
  2064. return $output;
  2065. }
  2066. /**
  2067. * @param int $studentId
  2068. * @param int $prerequisite
  2069. * @param array $courseInfo
  2070. * @param int $sessionId
  2071. *
  2072. * @return bool
  2073. */
  2074. public static function isBlockedByPrerequisite(
  2075. $studentId,
  2076. $prerequisite,
  2077. $courseInfo,
  2078. $sessionId
  2079. ) {
  2080. if (empty($courseInfo)) {
  2081. return false;
  2082. }
  2083. $courseId = $courseInfo['real_id'];
  2084. $allow = api_get_configuration_value('allow_teachers_to_access_blocked_lp_by_prerequisite');
  2085. if ($allow) {
  2086. if (api_is_allowed_to_edit() ||
  2087. api_is_platform_admin(true) ||
  2088. api_is_drh() ||
  2089. api_is_coach($sessionId, $courseId, false)
  2090. ) {
  2091. return false;
  2092. }
  2093. }
  2094. $isBlocked = false;
  2095. if (!empty($prerequisite)) {
  2096. $progress = self::getProgress(
  2097. $prerequisite,
  2098. $studentId,
  2099. $courseId,
  2100. $sessionId
  2101. );
  2102. if ($progress < 100) {
  2103. $isBlocked = true;
  2104. }
  2105. if (Tracking::minimumTimeAvailable($sessionId, $courseId)) {
  2106. // Block if it does not exceed minimum time
  2107. // Minimum time (in minutes) to pass the learning path
  2108. $accumulateWorkTime = self::getAccumulateWorkTimePrerequisite($prerequisite, $courseId);
  2109. if ($accumulateWorkTime > 0) {
  2110. // Total time in course (sum of times in learning paths from course)
  2111. $accumulateWorkTimeTotal = self::getAccumulateWorkTimeTotal($courseId);
  2112. // Connect with the plugin_licences_course_session table
  2113. // which indicates what percentage of the time applies
  2114. // Minimum connection percentage
  2115. $perc = 100;
  2116. // Time from the course
  2117. $tc = $accumulateWorkTimeTotal;
  2118. // Percentage of the learning paths
  2119. $pl = $accumulateWorkTime / $accumulateWorkTimeTotal;
  2120. // Minimum time for each learning path
  2121. $accumulateWorkTime = ($pl * $tc * $perc / 100);
  2122. // Spent time (in seconds) so far in the learning path
  2123. $lpTimeList = Tracking::getCalculateTime($studentId, $courseId, $sessionId);
  2124. $lpTime = isset($lpTimeList[TOOL_LEARNPATH][$prerequisite]) ? $lpTimeList[TOOL_LEARNPATH][$prerequisite] : 0;
  2125. if ($lpTime < ($accumulateWorkTime * 60)) {
  2126. $isBlocked = true;
  2127. }
  2128. }
  2129. }
  2130. }
  2131. return $isBlocked;
  2132. }
  2133. /**
  2134. * Checks if the learning path is visible for student after the progress
  2135. * of its prerequisite is completed, considering the time availability and
  2136. * the LP visibility.
  2137. *
  2138. * @param int $lp_id
  2139. * @param int $student_id
  2140. * @param array $courseInfo
  2141. * @param int $sessionId
  2142. *
  2143. * @return bool
  2144. */
  2145. public static function is_lp_visible_for_student(
  2146. $lp_id,
  2147. $student_id,
  2148. $courseInfo = [],
  2149. $sessionId = 0
  2150. ) {
  2151. $courseInfo = empty($courseInfo) ? api_get_course_info() : $courseInfo;
  2152. $lp_id = (int) $lp_id;
  2153. $sessionId = (int) $sessionId;
  2154. if (empty($courseInfo)) {
  2155. return false;
  2156. }
  2157. if (empty($sessionId)) {
  2158. $sessionId = api_get_session_id();
  2159. }
  2160. $courseId = $courseInfo['real_id'];
  2161. $itemInfo = api_get_item_property_info(
  2162. $courseId,
  2163. TOOL_LEARNPATH,
  2164. $lp_id,
  2165. $sessionId
  2166. );
  2167. // If the item was deleted.
  2168. if (isset($itemInfo['visibility']) && $itemInfo['visibility'] == 2) {
  2169. return false;
  2170. }
  2171. // @todo remove this query and load the row info as a parameter
  2172. $table = Database::get_course_table(TABLE_LP_MAIN);
  2173. // Get current prerequisite
  2174. $sql = "SELECT id, prerequisite, subscribe_users, publicated_on, expired_on
  2175. FROM $table
  2176. WHERE iid = $lp_id";
  2177. $rs = Database::query($sql);
  2178. $now = time();
  2179. if (Database::num_rows($rs) > 0) {
  2180. $row = Database::fetch_array($rs, 'ASSOC');
  2181. $prerequisite = $row['prerequisite'];
  2182. $is_visible = true;
  2183. $isBlocked = self::isBlockedByPrerequisite(
  2184. $student_id,
  2185. $prerequisite,
  2186. $courseInfo,
  2187. $sessionId
  2188. );
  2189. if ($isBlocked) {
  2190. $is_visible = false;
  2191. }
  2192. // Also check the time availability of the LP
  2193. if ($is_visible) {
  2194. // Adding visibility restrictions
  2195. if (!empty($row['publicated_on'])) {
  2196. if ($now < api_strtotime($row['publicated_on'], 'UTC')) {
  2197. $is_visible = false;
  2198. }
  2199. }
  2200. // Blocking empty start times see BT#2800
  2201. global $_custom;
  2202. if (isset($_custom['lps_hidden_when_no_start_date']) &&
  2203. $_custom['lps_hidden_when_no_start_date']
  2204. ) {
  2205. if (empty($row['publicated_on'])) {
  2206. $is_visible = false;
  2207. }
  2208. }
  2209. if (!empty($row['expired_on'])) {
  2210. if ($now > api_strtotime($row['expired_on'], 'UTC')) {
  2211. $is_visible = false;
  2212. }
  2213. }
  2214. }
  2215. if ($is_visible) {
  2216. $subscriptionSettings = self::getSubscriptionSettings();
  2217. // Check if the subscription users/group to a LP is ON
  2218. if (isset($row['subscribe_users']) && $row['subscribe_users'] == 1 &&
  2219. $subscriptionSettings['allow_add_users_to_lp'] === true
  2220. ) {
  2221. // Try group
  2222. $is_visible = false;
  2223. // Checking only the user visibility
  2224. $userVisibility = api_get_item_visibility(
  2225. $courseInfo,
  2226. 'learnpath',
  2227. $row['id'],
  2228. $sessionId,
  2229. $student_id,
  2230. 'LearnpathSubscription'
  2231. );
  2232. if ($userVisibility == 1) {
  2233. $is_visible = true;
  2234. } else {
  2235. $userGroups = GroupManager::getAllGroupPerUserSubscription($student_id, $courseId);
  2236. if (!empty($userGroups)) {
  2237. foreach ($userGroups as $groupInfo) {
  2238. $groupId = $groupInfo['iid'];
  2239. $userVisibility = api_get_item_visibility(
  2240. $courseInfo,
  2241. 'learnpath',
  2242. $row['id'],
  2243. $sessionId,
  2244. null,
  2245. 'LearnpathSubscription',
  2246. $groupId
  2247. );
  2248. if ($userVisibility == 1) {
  2249. $is_visible = true;
  2250. break;
  2251. }
  2252. }
  2253. }
  2254. }
  2255. }
  2256. }
  2257. return $is_visible;
  2258. }
  2259. return false;
  2260. }
  2261. /**
  2262. * @param int $lpId
  2263. * @param int $userId
  2264. * @param int $courseId
  2265. * @param int $sessionId
  2266. *
  2267. * @return int
  2268. */
  2269. public static function getProgress($lpId, $userId, $courseId, $sessionId = 0)
  2270. {
  2271. $lpId = (int) $lpId;
  2272. $userId = (int) $userId;
  2273. $courseId = (int) $courseId;
  2274. $sessionId = (int) $sessionId;
  2275. $sessionCondition = api_get_session_condition($sessionId);
  2276. $table = Database::get_course_table(TABLE_LP_VIEW);
  2277. $sql = "SELECT progress FROM $table
  2278. WHERE
  2279. c_id = $courseId AND
  2280. lp_id = $lpId AND
  2281. user_id = $userId $sessionCondition ";
  2282. $res = Database::query($sql);
  2283. $progress = 0;
  2284. if (Database::num_rows($res) > 0) {
  2285. $row = Database::fetch_array($res);
  2286. $progress = (int) $row['progress'];
  2287. }
  2288. return $progress;
  2289. }
  2290. /**
  2291. * @param array $lpList
  2292. * @param int $userId
  2293. * @param int $courseId
  2294. * @param int $sessionId
  2295. *
  2296. * @return array
  2297. */
  2298. public static function getProgressFromLpList($lpList, $userId, $courseId, $sessionId = 0)
  2299. {
  2300. $lpList = array_map('intval', $lpList);
  2301. if (empty($lpList)) {
  2302. return [];
  2303. }
  2304. $lpList = implode("','", $lpList);
  2305. $userId = (int) $userId;
  2306. $courseId = (int) $courseId;
  2307. $sessionId = (int) $sessionId;
  2308. $sessionCondition = api_get_session_condition($sessionId);
  2309. $table = Database::get_course_table(TABLE_LP_VIEW);
  2310. $sql = "SELECT lp_id, progress FROM $table
  2311. WHERE
  2312. c_id = $courseId AND
  2313. lp_id IN ('".$lpList."') AND
  2314. user_id = $userId $sessionCondition ";
  2315. $res = Database::query($sql);
  2316. if (Database::num_rows($res) > 0) {
  2317. $list = [];
  2318. while ($row = Database::fetch_array($res)) {
  2319. $list[$row['lp_id']] = $row['progress'];
  2320. }
  2321. return $list;
  2322. }
  2323. return [];
  2324. }
  2325. /**
  2326. * Displays a progress bar
  2327. * completed so far.
  2328. *
  2329. * @param int $percentage Progress value to display
  2330. * @param string $text_add Text to display near the progress value
  2331. *
  2332. * @return string HTML string containing the progress bar
  2333. */
  2334. public static function get_progress_bar($percentage = -1, $text_add = '')
  2335. {
  2336. $text = $percentage.$text_add;
  2337. $output = '<div class="progress">
  2338. <div id="progress_bar_value"
  2339. class="progress-bar progress-bar-success" role="progressbar"
  2340. aria-valuenow="'.$percentage.'" aria-valuemin="0" aria-valuemax="100" style="width: '.$text.';">
  2341. '.$text.'
  2342. </div>
  2343. </div>';
  2344. return $output;
  2345. }
  2346. /**
  2347. * @param string $mode can be '%' or 'abs'
  2348. * otherwise this value will be used $this->progress_bar_mode
  2349. *
  2350. * @return string
  2351. */
  2352. public function getProgressBar($mode = null)
  2353. {
  2354. list($percentage, $text_add) = $this->get_progress_bar_text($mode);
  2355. return self::get_progress_bar($percentage, $text_add);
  2356. }
  2357. /**
  2358. * Gets the progress bar info to display inside the progress bar.
  2359. * Also used by scorm_api.php.
  2360. *
  2361. * @param string $mode Mode of display (can be '%' or 'abs').abs means
  2362. * we display a number of completed elements per total elements
  2363. * @param int $add Additional steps to fake as completed
  2364. *
  2365. * @return array Percentage or number and symbol (% or /xx)
  2366. */
  2367. public function get_progress_bar_text($mode = '', $add = 0)
  2368. {
  2369. if (empty($mode)) {
  2370. $mode = $this->progress_bar_mode;
  2371. }
  2372. $total_items = $this->getTotalItemsCountWithoutDirs();
  2373. $completeItems = $this->get_complete_items_count();
  2374. if ($add != 0) {
  2375. $completeItems += $add;
  2376. }
  2377. $text = '';
  2378. if ($completeItems > $total_items) {
  2379. $completeItems = $total_items;
  2380. }
  2381. $percentage = 0;
  2382. if ($mode == '%') {
  2383. if ($total_items > 0) {
  2384. $percentage = ((float) $completeItems / (float) $total_items) * 100;
  2385. }
  2386. $percentage = number_format($percentage, 0);
  2387. $text = '%';
  2388. } elseif ($mode === 'abs') {
  2389. $percentage = $completeItems;
  2390. $text = '/'.$total_items;
  2391. }
  2392. return [
  2393. $percentage,
  2394. $text,
  2395. ];
  2396. }
  2397. /**
  2398. * Gets the progress bar mode.
  2399. *
  2400. * @return string The progress bar mode attribute
  2401. */
  2402. public function get_progress_bar_mode()
  2403. {
  2404. if (!empty($this->progress_bar_mode)) {
  2405. return $this->progress_bar_mode;
  2406. }
  2407. return '%';
  2408. }
  2409. /**
  2410. * Gets the learnpath theme (remote or local).
  2411. *
  2412. * @return string Learnpath theme
  2413. */
  2414. public function get_theme()
  2415. {
  2416. if (!empty($this->theme)) {
  2417. return $this->theme;
  2418. }
  2419. return '';
  2420. }
  2421. /**
  2422. * Gets the learnpath session id.
  2423. *
  2424. * @return int
  2425. */
  2426. public function get_lp_session_id()
  2427. {
  2428. if (!empty($this->lp_session_id)) {
  2429. return (int) $this->lp_session_id;
  2430. }
  2431. return 0;
  2432. }
  2433. /**
  2434. * Gets the learnpath image.
  2435. *
  2436. * @return string Web URL of the LP image
  2437. */
  2438. public function get_preview_image()
  2439. {
  2440. if (!empty($this->preview_image)) {
  2441. return $this->preview_image;
  2442. }
  2443. return '';
  2444. }
  2445. /**
  2446. * @param string $size
  2447. * @param string $path_type
  2448. *
  2449. * @return bool|string
  2450. */
  2451. public function get_preview_image_path($size = null, $path_type = 'web')
  2452. {
  2453. $preview_image = $this->get_preview_image();
  2454. if (isset($preview_image) && !empty($preview_image)) {
  2455. $image_sys_path = api_get_path(SYS_COURSE_PATH).$this->course_info['path'].'/upload/learning_path/images/';
  2456. $image_path = api_get_path(WEB_COURSE_PATH).$this->course_info['path'].'/upload/learning_path/images/';
  2457. if (isset($size)) {
  2458. $info = pathinfo($preview_image);
  2459. $image_custom_size = $info['filename'].'.'.$size.'.'.$info['extension'];
  2460. if (file_exists($image_sys_path.$image_custom_size)) {
  2461. if ($path_type == 'web') {
  2462. return $image_path.$image_custom_size;
  2463. } else {
  2464. return $image_sys_path.$image_custom_size;
  2465. }
  2466. }
  2467. } else {
  2468. if ($path_type == 'web') {
  2469. return $image_path.$preview_image;
  2470. } else {
  2471. return $image_sys_path.$preview_image;
  2472. }
  2473. }
  2474. }
  2475. return false;
  2476. }
  2477. /**
  2478. * Gets the learnpath author.
  2479. *
  2480. * @return string LP's author
  2481. */
  2482. public function get_author()
  2483. {
  2484. if (!empty($this->author)) {
  2485. return $this->author;
  2486. }
  2487. return '';
  2488. }
  2489. /**
  2490. * Gets hide table of contents.
  2491. *
  2492. * @return int
  2493. */
  2494. public function getHideTableOfContents()
  2495. {
  2496. return (int) $this->hide_toc_frame;
  2497. }
  2498. /**
  2499. * Generate a new prerequisites string for a given item. If this item was a sco and
  2500. * its prerequisites were strings (instead of IDs), then transform those strings into
  2501. * IDs, knowing that SCORM IDs are kept in the "ref" field of the lp_item table.
  2502. * Prefix all item IDs that end-up in the prerequisites string by "ITEM_" to use the
  2503. * same rule as the scormExport() method.
  2504. *
  2505. * @param int $item_id Item ID
  2506. *
  2507. * @return string Prerequisites string ready for the export as SCORM
  2508. */
  2509. public function get_scorm_prereq_string($item_id)
  2510. {
  2511. if ($this->debug > 0) {
  2512. error_log('In learnpath::get_scorm_prereq_string()');
  2513. }
  2514. if (!is_object($this->items[$item_id])) {
  2515. return false;
  2516. }
  2517. /** @var learnpathItem $oItem */
  2518. $oItem = $this->items[$item_id];
  2519. $prereq = $oItem->get_prereq_string();
  2520. if (empty($prereq)) {
  2521. return '';
  2522. }
  2523. if (preg_match('/^\d+$/', $prereq) &&
  2524. isset($this->items[$prereq]) &&
  2525. is_object($this->items[$prereq])
  2526. ) {
  2527. // If the prerequisite is a simple integer ID and this ID exists as an item ID,
  2528. // then simply return it (with the ITEM_ prefix).
  2529. //return 'ITEM_' . $prereq;
  2530. return $this->items[$prereq]->ref;
  2531. } else {
  2532. if (isset($this->refs_list[$prereq])) {
  2533. // It's a simple string item from which the ID can be found in the refs list,
  2534. // so we can transform it directly to an ID for export.
  2535. return $this->items[$this->refs_list[$prereq]]->ref;
  2536. } elseif (isset($this->refs_list['ITEM_'.$prereq])) {
  2537. return $this->items[$this->refs_list['ITEM_'.$prereq]]->ref;
  2538. } else {
  2539. // The last case, if it's a complex form, then find all the IDs (SCORM strings)
  2540. // and replace them, one by one, by the internal IDs (chamilo db)
  2541. // TODO: Modify the '*' replacement to replace the multiplier in front of it
  2542. // by a space as well.
  2543. $find = [
  2544. '&',
  2545. '|',
  2546. '~',
  2547. '=',
  2548. '<>',
  2549. '{',
  2550. '}',
  2551. '*',
  2552. '(',
  2553. ')',
  2554. ];
  2555. $replace = [
  2556. ' ',
  2557. ' ',
  2558. ' ',
  2559. ' ',
  2560. ' ',
  2561. ' ',
  2562. ' ',
  2563. ' ',
  2564. ' ',
  2565. ' ',
  2566. ];
  2567. $prereq_mod = str_replace($find, $replace, $prereq);
  2568. $ids = explode(' ', $prereq_mod);
  2569. foreach ($ids as $id) {
  2570. $id = trim($id);
  2571. if (isset($this->refs_list[$id])) {
  2572. $prereq = preg_replace(
  2573. '/[^a-zA-Z_0-9]('.$id.')[^a-zA-Z_0-9]/',
  2574. 'ITEM_'.$this->refs_list[$id],
  2575. $prereq
  2576. );
  2577. }
  2578. }
  2579. return $prereq;
  2580. }
  2581. }
  2582. }
  2583. /**
  2584. * Returns the XML DOM document's node.
  2585. *
  2586. * @param resource $children Reference to a list of objects to search for the given ITEM_*
  2587. * @param string $id The identifier to look for
  2588. *
  2589. * @return mixed The reference to the element found with that identifier. False if not found
  2590. */
  2591. public function get_scorm_xml_node(&$children, $id)
  2592. {
  2593. for ($i = 0; $i < $children->length; $i++) {
  2594. $item_temp = $children->item($i);
  2595. if ($item_temp->nodeName == 'item') {
  2596. if ($item_temp->getAttribute('identifier') == $id) {
  2597. return $item_temp;
  2598. }
  2599. }
  2600. $subchildren = $item_temp->childNodes;
  2601. if ($subchildren && $subchildren->length > 0) {
  2602. $val = $this->get_scorm_xml_node($subchildren, $id);
  2603. if (is_object($val)) {
  2604. return $val;
  2605. }
  2606. }
  2607. }
  2608. return false;
  2609. }
  2610. /**
  2611. * Gets the status list for all LP's items.
  2612. *
  2613. * @return array Array of [index] => [item ID => current status]
  2614. */
  2615. public function get_items_status_list()
  2616. {
  2617. $list = [];
  2618. foreach ($this->ordered_items as $item_id) {
  2619. $list[] = [
  2620. $item_id => $this->items[$item_id]->get_status(),
  2621. ];
  2622. }
  2623. return $list;
  2624. }
  2625. /**
  2626. * Return the number of interactions for the given learnpath Item View ID.
  2627. * This method can be used as static.
  2628. *
  2629. * @param int $lp_iv_id Item View ID
  2630. * @param int $course_id course id
  2631. *
  2632. * @return int
  2633. */
  2634. public static function get_interactions_count_from_db($lp_iv_id, $course_id)
  2635. {
  2636. $table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
  2637. $lp_iv_id = (int) $lp_iv_id;
  2638. $course_id = (int) $course_id;
  2639. $sql = "SELECT count(*) FROM $table
  2640. WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id";
  2641. $res = Database::query($sql);
  2642. $num = 0;
  2643. if (Database::num_rows($res)) {
  2644. $row = Database::fetch_array($res);
  2645. $num = $row[0];
  2646. }
  2647. return $num;
  2648. }
  2649. /**
  2650. * Return the interactions as an array for the given lp_iv_id.
  2651. * This method can be used as static.
  2652. *
  2653. * @param int $lp_iv_id Learnpath Item View ID
  2654. *
  2655. * @return array
  2656. *
  2657. * @todo Transcode labels instead of switching to HTML (which requires to know the encoding of the LP)
  2658. */
  2659. public static function get_iv_interactions_array($lp_iv_id, $course_id = 0)
  2660. {
  2661. $course_id = empty($course_id) ? api_get_course_int_id() : (int) $course_id;
  2662. $list = [];
  2663. $table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
  2664. $lp_iv_id = (int) $lp_iv_id;
  2665. if (empty($lp_iv_id) || empty($course_id)) {
  2666. return [];
  2667. }
  2668. $sql = "SELECT * FROM $table
  2669. WHERE c_id = ".$course_id." AND lp_iv_id = $lp_iv_id
  2670. ORDER BY order_id ASC";
  2671. $res = Database::query($sql);
  2672. $num = Database::num_rows($res);
  2673. if ($num > 0) {
  2674. $list[] = [
  2675. 'order_id' => api_htmlentities(get_lang('Order'), ENT_QUOTES),
  2676. 'id' => api_htmlentities(get_lang('InteractionID'), ENT_QUOTES),
  2677. 'type' => api_htmlentities(get_lang('Type'), ENT_QUOTES),
  2678. 'time' => api_htmlentities(get_lang('TimeFinished'), ENT_QUOTES),
  2679. 'correct_responses' => api_htmlentities(get_lang('CorrectAnswers'), ENT_QUOTES),
  2680. 'student_response' => api_htmlentities(get_lang('StudentResponse'), ENT_QUOTES),
  2681. 'result' => api_htmlentities(get_lang('Result'), ENT_QUOTES),
  2682. 'latency' => api_htmlentities(get_lang('LatencyTimeSpent'), ENT_QUOTES),
  2683. 'student_response_formatted' => '',
  2684. ];
  2685. while ($row = Database::fetch_array($res)) {
  2686. $studentResponseFormatted = urldecode($row['student_response']);
  2687. $content_student_response = explode('__|', $studentResponseFormatted);
  2688. if (count($content_student_response) > 0) {
  2689. if (count($content_student_response) >= 3) {
  2690. // Pop the element off the end of array.
  2691. array_pop($content_student_response);
  2692. }
  2693. $studentResponseFormatted = implode(',', $content_student_response);
  2694. }
  2695. $list[] = [
  2696. 'order_id' => $row['order_id'] + 1,
  2697. 'id' => urldecode($row['interaction_id']), //urldecode because they often have %2F or stuff like that
  2698. 'type' => $row['interaction_type'],
  2699. 'time' => $row['completion_time'],
  2700. 'correct_responses' => '', // Hide correct responses from students.
  2701. 'student_response' => $row['student_response'],
  2702. 'result' => $row['result'],
  2703. 'latency' => $row['latency'],
  2704. 'student_response_formatted' => $studentResponseFormatted,
  2705. ];
  2706. }
  2707. }
  2708. return $list;
  2709. }
  2710. /**
  2711. * Return the number of objectives for the given learnpath Item View ID.
  2712. * This method can be used as static.
  2713. *
  2714. * @param int $lp_iv_id Item View ID
  2715. * @param int $course_id Course ID
  2716. *
  2717. * @return int Number of objectives
  2718. */
  2719. public static function get_objectives_count_from_db($lp_iv_id, $course_id)
  2720. {
  2721. $table = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
  2722. $course_id = (int) $course_id;
  2723. $lp_iv_id = (int) $lp_iv_id;
  2724. $sql = "SELECT count(*) FROM $table
  2725. WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id";
  2726. //@todo seems that this always returns 0
  2727. $res = Database::query($sql);
  2728. $num = 0;
  2729. if (Database::num_rows($res)) {
  2730. $row = Database::fetch_array($res);
  2731. $num = $row[0];
  2732. }
  2733. return $num;
  2734. }
  2735. /**
  2736. * Return the objectives as an array for the given lp_iv_id.
  2737. * This method can be used as static.
  2738. *
  2739. * @param int $lpItemViewId Learnpath Item View ID
  2740. * @param int $course_id
  2741. *
  2742. * @return array
  2743. *
  2744. * @todo Translate labels
  2745. */
  2746. public static function get_iv_objectives_array($lpItemViewId = 0, $course_id = 0)
  2747. {
  2748. $course_id = empty($course_id) ? api_get_course_int_id() : (int) $course_id;
  2749. $lpItemViewId = (int) $lpItemViewId;
  2750. if (empty($course_id) || empty($lpItemViewId)) {
  2751. return [];
  2752. }
  2753. $table = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
  2754. $sql = "SELECT * FROM $table
  2755. WHERE c_id = $course_id AND lp_iv_id = $lpItemViewId
  2756. ORDER BY order_id ASC";
  2757. $res = Database::query($sql);
  2758. $num = Database::num_rows($res);
  2759. $list = [];
  2760. if ($num > 0) {
  2761. $list[] = [
  2762. 'order_id' => api_htmlentities(get_lang('Order'), ENT_QUOTES),
  2763. 'objective_id' => api_htmlentities(get_lang('ObjectiveID'), ENT_QUOTES),
  2764. 'score_raw' => api_htmlentities(get_lang('ObjectiveRawScore'), ENT_QUOTES),
  2765. 'score_max' => api_htmlentities(get_lang('ObjectiveMaxScore'), ENT_QUOTES),
  2766. 'score_min' => api_htmlentities(get_lang('ObjectiveMinScore'), ENT_QUOTES),
  2767. 'status' => api_htmlentities(get_lang('ObjectiveStatus'), ENT_QUOTES),
  2768. ];
  2769. while ($row = Database::fetch_array($res)) {
  2770. $list[] = [
  2771. 'order_id' => $row['order_id'] + 1,
  2772. 'objective_id' => urldecode($row['objective_id']), // urldecode() because they often have %2F
  2773. 'score_raw' => $row['score_raw'],
  2774. 'score_max' => $row['score_max'],
  2775. 'score_min' => $row['score_min'],
  2776. 'status' => $row['status'],
  2777. ];
  2778. }
  2779. }
  2780. return $list;
  2781. }
  2782. /**
  2783. * Generate and return the table of contents for this learnpath. The (flat) table returned can be
  2784. * used by get_html_toc() to be ready to display.
  2785. *
  2786. * @return array TOC as a table with 4 elements per row: title, link, status and level
  2787. */
  2788. public function get_toc()
  2789. {
  2790. $toc = [];
  2791. foreach ($this->ordered_items as $item_id) {
  2792. // TODO: Change this link generation and use new function instead.
  2793. $toc[] = [
  2794. 'id' => $item_id,
  2795. 'title' => $this->items[$item_id]->get_title(),
  2796. 'status' => $this->items[$item_id]->get_status(),
  2797. 'level' => $this->items[$item_id]->get_level(),
  2798. 'type' => $this->items[$item_id]->get_type(),
  2799. 'description' => $this->items[$item_id]->get_description(),
  2800. 'path' => $this->items[$item_id]->get_path(),
  2801. 'parent' => $this->items[$item_id]->get_parent(),
  2802. ];
  2803. }
  2804. return $toc;
  2805. }
  2806. /**
  2807. * Generate and return the table of contents for this learnpath. The JS
  2808. * table returned is used inside of scorm_api.php.
  2809. *
  2810. * @param string $varname
  2811. *
  2812. * @return string A JS array variable construction
  2813. */
  2814. public function get_items_details_as_js($varname = 'olms.lms_item_types')
  2815. {
  2816. $toc = $varname.' = new Array();';
  2817. foreach ($this->ordered_items as $item_id) {
  2818. $toc .= $varname."['i$item_id'] = '".$this->items[$item_id]->get_type()."';";
  2819. }
  2820. return $toc;
  2821. }
  2822. /**
  2823. * Gets the learning path type.
  2824. *
  2825. * @param bool $get_name Return the name? If false, return the ID. Default is false.
  2826. *
  2827. * @return mixed Type ID or name, depending on the parameter
  2828. */
  2829. public function get_type($get_name = false)
  2830. {
  2831. $res = false;
  2832. if (!empty($this->type) && (!$get_name)) {
  2833. $res = $this->type;
  2834. }
  2835. return $res;
  2836. }
  2837. /**
  2838. * Gets the learning path type as static method.
  2839. *
  2840. * @param int $lp_id
  2841. *
  2842. * @return mixed Type ID or name, depending on the parameter
  2843. */
  2844. public static function get_type_static($lp_id = 0)
  2845. {
  2846. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  2847. $lp_id = (int) $lp_id;
  2848. $sql = "SELECT lp_type FROM $tbl_lp
  2849. WHERE iid = $lp_id";
  2850. $res = Database::query($sql);
  2851. if ($res === false) {
  2852. return null;
  2853. }
  2854. if (Database::num_rows($res) <= 0) {
  2855. return null;
  2856. }
  2857. $row = Database::fetch_array($res);
  2858. return $row['lp_type'];
  2859. }
  2860. /**
  2861. * Gets a flat list of item IDs ordered for display (level by level ordered by order_display)
  2862. * This method can be used as abstract and is recursive.
  2863. *
  2864. * @param int $lp Learnpath ID
  2865. * @param int $parent Parent ID of the items to look for
  2866. * @param int $course_id
  2867. *
  2868. * @return array Ordered list of item IDs (empty array on error)
  2869. */
  2870. public static function get_flat_ordered_items_list($lp = 1, $parent = 0, $course_id = 0)
  2871. {
  2872. if (empty($course_id)) {
  2873. $course_id = api_get_course_int_id();
  2874. } else {
  2875. $course_id = (int) $course_id;
  2876. }
  2877. $list = [];
  2878. if (empty($lp)) {
  2879. return $list;
  2880. }
  2881. $lp = (int) $lp;
  2882. $parent = (int) $parent;
  2883. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  2884. $sql = "SELECT iid FROM $tbl_lp_item
  2885. WHERE c_id = $course_id AND lp_id = $lp AND parent_item_id = $parent
  2886. ORDER BY display_order";
  2887. $res = Database::query($sql);
  2888. while ($row = Database::fetch_array($res)) {
  2889. $sublist = self::get_flat_ordered_items_list(
  2890. $lp,
  2891. $row['iid'],
  2892. $course_id
  2893. );
  2894. $list[] = $row['iid'];
  2895. foreach ($sublist as $item) {
  2896. $list[] = $item;
  2897. }
  2898. }
  2899. return $list;
  2900. }
  2901. /**
  2902. * @return array
  2903. */
  2904. public static function getChapterTypes()
  2905. {
  2906. return [
  2907. 'dir',
  2908. ];
  2909. }
  2910. /**
  2911. * Uses the table generated by get_toc() and returns an HTML-formattedstring ready to display.
  2912. *
  2913. * @param $tree
  2914. *
  2915. * @return array HTML TOC ready to display
  2916. */
  2917. public function getParentToc($tree)
  2918. {
  2919. if (empty($tree)) {
  2920. $tree = $this->get_toc();
  2921. }
  2922. $dirTypes = self::getChapterTypes();
  2923. $myCurrentId = $this->get_current_item_id();
  2924. $listParent = [];
  2925. $listChildren = [];
  2926. $listNotParent = [];
  2927. $list = [];
  2928. foreach ($tree as $subtree) {
  2929. if (in_array($subtree['type'], $dirTypes)) {
  2930. $listChildren = $this->getChildrenToc($tree, $subtree['id']);
  2931. $subtree['children'] = $listChildren;
  2932. if (!empty($subtree['children'])) {
  2933. foreach ($subtree['children'] as $subItem) {
  2934. if ($subItem['id'] == $this->current) {
  2935. $subtree['parent_current'] = 'in';
  2936. $subtree['current'] = 'on';
  2937. }
  2938. }
  2939. }
  2940. $listParent[] = $subtree;
  2941. }
  2942. if (!in_array($subtree['type'], $dirTypes) && $subtree['parent'] == null) {
  2943. $classStatus = [
  2944. 'not attempted' => 'scorm_not_attempted',
  2945. 'incomplete' => 'scorm_not_attempted',
  2946. 'failed' => 'scorm_failed',
  2947. 'completed' => 'scorm_completed',
  2948. 'passed' => 'scorm_completed',
  2949. 'succeeded' => 'scorm_completed',
  2950. 'browsed' => 'scorm_completed',
  2951. ];
  2952. if (isset($classStatus[$subtree['status']])) {
  2953. $cssStatus = $classStatus[$subtree['status']];
  2954. }
  2955. $title = Security::remove_XSS($subtree['title']);
  2956. unset($subtree['title']);
  2957. if (empty($title)) {
  2958. $title = self::rl_get_resource_name(api_get_course_id(), $this->get_id(), $subtree['id']);
  2959. }
  2960. $classStyle = null;
  2961. if ($subtree['id'] == $this->current) {
  2962. $classStyle = 'scorm_item_normal '.$classStyle.'scorm_highlight';
  2963. } elseif (!in_array($subtree['type'], $dirTypes)) {
  2964. $classStyle = 'scorm_item_normal '.$classStyle.' ';
  2965. }
  2966. $subtree['title'] = $title;
  2967. $subtree['class'] = $classStyle.' '.$cssStatus;
  2968. $subtree['url'] = $this->get_link('http', $subtree['id'], $tree);
  2969. $subtree['current_id'] = $myCurrentId;
  2970. $listNotParent[] = $subtree;
  2971. }
  2972. }
  2973. $list['are_parents'] = $listParent;
  2974. $list['not_parents'] = $listNotParent;
  2975. return $list;
  2976. }
  2977. /**
  2978. * Uses the table generated by get_toc() and returns an HTML-formattedstring ready to display.
  2979. *
  2980. * @param array $tree
  2981. * @param int $id
  2982. * @param bool $parent
  2983. *
  2984. * @return array HTML TOC ready to display
  2985. */
  2986. public function getChildrenToc($tree, $id, $parent = true)
  2987. {
  2988. if (empty($tree)) {
  2989. $tree = $this->get_toc();
  2990. }
  2991. $dirTypes = self::getChapterTypes();
  2992. $currentItemId = $this->get_current_item_id();
  2993. $list = [];
  2994. $classStatus = [
  2995. 'not attempted' => 'scorm_not_attempted',
  2996. 'incomplete' => 'scorm_not_attempted',
  2997. 'failed' => 'scorm_failed',
  2998. 'completed' => 'scorm_completed',
  2999. 'passed' => 'scorm_completed',
  3000. 'succeeded' => 'scorm_completed',
  3001. 'browsed' => 'scorm_completed',
  3002. ];
  3003. foreach ($tree as $subtree) {
  3004. $subtree['tree'] = null;
  3005. if (!in_array($subtree['type'], $dirTypes) && $subtree['parent'] == $id) {
  3006. if ($subtree['id'] == $this->current) {
  3007. $subtree['current'] = 'active';
  3008. } else {
  3009. $subtree['current'] = null;
  3010. }
  3011. if (isset($classStatus[$subtree['status']])) {
  3012. $cssStatus = $classStatus[$subtree['status']];
  3013. }
  3014. $title = Security::remove_XSS($subtree['title']);
  3015. unset($subtree['title']);
  3016. if (empty($title)) {
  3017. $title = self::rl_get_resource_name(api_get_course_id(), $this->get_id(), $subtree['id']);
  3018. }
  3019. $classStyle = null;
  3020. if ($subtree['id'] == $this->current) {
  3021. $classStyle = 'scorm_item_normal '.$classStyle.'scorm_highlight';
  3022. } elseif (!in_array($subtree['type'], $dirTypes)) {
  3023. $classStyle = 'scorm_item_normal '.$classStyle.' ';
  3024. }
  3025. if (in_array($subtree['type'], $dirTypes)) {
  3026. $subtree['title'] = stripslashes($title);
  3027. } else {
  3028. $subtree['title'] = $title;
  3029. $subtree['class'] = $classStyle.' '.$cssStatus;
  3030. $subtree['url'] = $this->get_link('http', $subtree['id'], $tree);
  3031. $subtree['current_id'] = $currentItemId;
  3032. }
  3033. $list[] = $subtree;
  3034. }
  3035. }
  3036. return $list;
  3037. }
  3038. /**
  3039. * Uses the table generated by get_toc() and returns an HTML-formatted string ready to display.
  3040. *
  3041. * @param array $toc_list
  3042. *
  3043. * @return array HTML TOC ready to display
  3044. */
  3045. public function getListArrayToc($toc_list = [])
  3046. {
  3047. if (empty($toc_list)) {
  3048. $toc_list = $this->get_toc();
  3049. }
  3050. // Temporary variables.
  3051. $currentItemId = $this->get_current_item_id();
  3052. $list = [];
  3053. $arrayList = [];
  3054. $classStatus = [
  3055. 'not attempted' => 'scorm_not_attempted',
  3056. 'incomplete' => 'scorm_not_attempted',
  3057. 'failed' => 'scorm_failed',
  3058. 'completed' => 'scorm_completed',
  3059. 'passed' => 'scorm_completed',
  3060. 'succeeded' => 'scorm_completed',
  3061. 'browsed' => 'scorm_completed',
  3062. ];
  3063. foreach ($toc_list as $item) {
  3064. $list['id'] = $item['id'];
  3065. $list['status'] = $item['status'];
  3066. $cssStatus = null;
  3067. if (isset($classStatus[$item['status']])) {
  3068. $cssStatus = $classStatus[$item['status']];
  3069. }
  3070. $classStyle = ' ';
  3071. $dirTypes = self::getChapterTypes();
  3072. if (in_array($item['type'], $dirTypes)) {
  3073. $classStyle = 'scorm_item_section ';
  3074. }
  3075. if ($item['id'] == $this->current) {
  3076. $classStyle = 'scorm_item_normal '.$classStyle.'scorm_highlight';
  3077. } elseif (!in_array($item['type'], $dirTypes)) {
  3078. $classStyle = 'scorm_item_normal '.$classStyle.' ';
  3079. }
  3080. $title = $item['title'];
  3081. if (empty($title)) {
  3082. $title = self::rl_get_resource_name(
  3083. api_get_course_id(),
  3084. $this->get_id(),
  3085. $item['id']
  3086. );
  3087. }
  3088. $title = Security::remove_XSS($item['title']);
  3089. if (empty($item['description'])) {
  3090. $list['description'] = $title;
  3091. } else {
  3092. $list['description'] = $item['description'];
  3093. }
  3094. $list['class'] = $classStyle.' '.$cssStatus;
  3095. $list['level'] = $item['level'];
  3096. $list['type'] = $item['type'];
  3097. if (in_array($item['type'], $dirTypes)) {
  3098. $list['css_level'] = 'level_'.$item['level'];
  3099. } else {
  3100. $list['css_level'] = 'level_'.$item['level'].' scorm_type_'.self::format_scorm_type_item($item['type']);
  3101. }
  3102. if (in_array($item['type'], $dirTypes)) {
  3103. $list['title'] = stripslashes($title);
  3104. } else {
  3105. $list['title'] = stripslashes($title);
  3106. $list['url'] = $this->get_link('http', $item['id'], $toc_list);
  3107. $list['current_id'] = $currentItemId;
  3108. }
  3109. $arrayList[] = $list;
  3110. }
  3111. return $arrayList;
  3112. }
  3113. /**
  3114. * Returns an HTML-formatted string ready to display with teacher buttons
  3115. * in LP view menu.
  3116. *
  3117. * @return string HTML TOC ready to display
  3118. */
  3119. public function get_teacher_toc_buttons()
  3120. {
  3121. $isAllow = api_is_allowed_to_edit(null, true, false, false);
  3122. $hideIcons = api_get_configuration_value('hide_teacher_icons_lp');
  3123. $html = '';
  3124. if ($isAllow && $hideIcons == false) {
  3125. if ($this->get_lp_session_id() == api_get_session_id()) {
  3126. $html .= '<div id="actions_lp" class="actions_lp"><hr>';
  3127. $html .= '<div class="btn-group">';
  3128. $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'>".
  3129. Display::returnFontAwesomeIcon('street-view').get_lang('Overview')."</a>";
  3130. $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'>".
  3131. Display::returnFontAwesomeIcon('pencil').get_lang('Edit')."</a>";
  3132. $html .= '<a class="btn btn-sm btn-default" href="lp_controller.php?'.api_get_cidreq()."&action=edit&lp_id=".$this->lp_id.'&isStudentView=false">'.
  3133. Display::returnFontAwesomeIcon('cog').get_lang('Settings').'</a>';
  3134. $html .= '</div>';
  3135. $html .= '</div>';
  3136. }
  3137. }
  3138. return $html;
  3139. }
  3140. /**
  3141. * Gets the learnpath maker name - generally the editor's name.
  3142. *
  3143. * @return string Learnpath maker name
  3144. */
  3145. public function get_maker()
  3146. {
  3147. if (!empty($this->maker)) {
  3148. return $this->maker;
  3149. }
  3150. return '';
  3151. }
  3152. /**
  3153. * Gets the learnpath name/title.
  3154. *
  3155. * @return string Learnpath name/title
  3156. */
  3157. public function get_name()
  3158. {
  3159. if (!empty($this->name)) {
  3160. return $this->name;
  3161. }
  3162. return 'N/A';
  3163. }
  3164. /**
  3165. * @return string
  3166. */
  3167. public function getNameNoTags()
  3168. {
  3169. return strip_tags($this->get_name());
  3170. }
  3171. /**
  3172. * Gets a link to the resource from the present location, depending on item ID.
  3173. *
  3174. * @param string $type Type of link expected
  3175. * @param int $item_id Learnpath item ID
  3176. * @param bool $provided_toc
  3177. *
  3178. * @return string $provided_toc Link to the lp_item resource
  3179. */
  3180. public function get_link($type = 'http', $item_id = 0, $provided_toc = false)
  3181. {
  3182. $course_id = $this->get_course_int_id();
  3183. $item_id = (int) $item_id;
  3184. if (empty($item_id)) {
  3185. $item_id = $this->get_current_item_id();
  3186. if (empty($item_id)) {
  3187. //still empty, this means there was no item_id given and we are not in an object context or
  3188. //the object property is empty, return empty link
  3189. $this->first();
  3190. return '';
  3191. }
  3192. }
  3193. $file = '';
  3194. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3195. $lp_item_table = Database::get_course_table(TABLE_LP_ITEM);
  3196. $lp_item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  3197. $sql = "SELECT
  3198. l.lp_type as ltype,
  3199. l.path as lpath,
  3200. li.item_type as litype,
  3201. li.path as lipath,
  3202. li.parameters as liparams
  3203. FROM $lp_table l
  3204. INNER JOIN $lp_item_table li
  3205. ON (li.lp_id = l.iid)
  3206. WHERE
  3207. li.iid = $item_id
  3208. ";
  3209. $res = Database::query($sql);
  3210. if (Database::num_rows($res) > 0) {
  3211. $row = Database::fetch_array($res);
  3212. $lp_type = $row['ltype'];
  3213. $lp_path = $row['lpath'];
  3214. $lp_item_type = $row['litype'];
  3215. $lp_item_path = $row['lipath'];
  3216. $lp_item_params = $row['liparams'];
  3217. if (empty($lp_item_params) && strpos($lp_item_path, '?') !== false) {
  3218. list($lp_item_path, $lp_item_params) = explode('?', $lp_item_path);
  3219. }
  3220. $sys_course_path = api_get_path(SYS_COURSE_PATH).api_get_course_path();
  3221. if ($type === 'http') {
  3222. //web path
  3223. $course_path = api_get_path(WEB_COURSE_PATH).api_get_course_path();
  3224. } else {
  3225. $course_path = $sys_course_path; //system path
  3226. }
  3227. // Fixed issue BT#1272 - If the item type is a Chamilo Item (quiz, link, etc),
  3228. // then change the lp type to thread it as a normal Chamilo LP not a SCO.
  3229. if (in_array(
  3230. $lp_item_type,
  3231. ['quiz', 'document', 'final_item', 'link', 'forum', 'thread', 'student_publication']
  3232. )
  3233. ) {
  3234. $lp_type = 1;
  3235. }
  3236. // Now go through the specific cases to get the end of the path
  3237. // @todo Use constants instead of int values.
  3238. switch ($lp_type) {
  3239. case 1:
  3240. $file = self::rl_get_resource_link_for_learnpath(
  3241. $course_id,
  3242. $this->get_id(),
  3243. $item_id,
  3244. $this->get_view_id()
  3245. );
  3246. switch ($lp_item_type) {
  3247. case 'document':
  3248. // Shows a button to download the file instead of just downloading the file directly.
  3249. $documentPathInfo = pathinfo($file);
  3250. if (isset($documentPathInfo['extension'])) {
  3251. $parsed = parse_url($documentPathInfo['extension']);
  3252. if (isset($parsed['path'])) {
  3253. $extension = $parsed['path'];
  3254. $extensionsToDownload = [
  3255. 'zip',
  3256. 'ppt',
  3257. 'pptx',
  3258. 'ods',
  3259. 'xlsx',
  3260. 'xls',
  3261. 'csv',
  3262. 'doc',
  3263. 'docx',
  3264. 'dot',
  3265. ];
  3266. if (in_array($extension, $extensionsToDownload)) {
  3267. $file = api_get_path(WEB_CODE_PATH).
  3268. 'lp/embed.php?type=download&source=file&lp_item_id='.$item_id.'&'.api_get_cidreq();
  3269. }
  3270. }
  3271. }
  3272. break;
  3273. case 'dir':
  3274. $file = 'lp_content.php?type=dir';
  3275. break;
  3276. case 'link':
  3277. if (Link::is_youtube_link($file)) {
  3278. $src = Link::get_youtube_video_id($file);
  3279. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=youtube&source='.$src;
  3280. } elseif (Link::isVimeoLink($file)) {
  3281. $src = Link::getVimeoLinkId($file);
  3282. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=vimeo&source='.$src;
  3283. } else {
  3284. // If the current site is HTTPS and the link is
  3285. // HTTP, browsers will refuse opening the link
  3286. $urlId = api_get_current_access_url_id();
  3287. $url = api_get_access_url($urlId, false);
  3288. $protocol = substr($url['url'], 0, 5);
  3289. if ($protocol === 'https') {
  3290. $linkProtocol = substr($file, 0, 5);
  3291. if ($linkProtocol === 'http:') {
  3292. //this is the special intervention case
  3293. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=nonhttps&source='.urlencode($file);
  3294. }
  3295. }
  3296. }
  3297. break;
  3298. case 'quiz':
  3299. // Check how much attempts of a exercise exits in lp
  3300. $lp_item_id = $this->get_current_item_id();
  3301. $lp_view_id = $this->get_view_id();
  3302. $prevent_reinit = null;
  3303. if (isset($this->items[$this->current])) {
  3304. $prevent_reinit = $this->items[$this->current]->get_prevent_reinit();
  3305. }
  3306. if (empty($provided_toc)) {
  3307. if ($this->debug > 0) {
  3308. error_log('In learnpath::get_link() Loading get_toc ', 0);
  3309. }
  3310. $list = $this->get_toc();
  3311. } else {
  3312. if ($this->debug > 0) {
  3313. error_log('In learnpath::get_link() Loading get_toc from "cache" ', 0);
  3314. }
  3315. $list = $provided_toc;
  3316. }
  3317. $type_quiz = false;
  3318. foreach ($list as $toc) {
  3319. if ($toc['id'] == $lp_item_id && $toc['type'] == 'quiz') {
  3320. $type_quiz = true;
  3321. }
  3322. }
  3323. if ($type_quiz) {
  3324. $lp_item_id = (int) $lp_item_id;
  3325. $lp_view_id = (int) $lp_view_id;
  3326. $sql = "SELECT count(*) FROM $lp_item_view_table
  3327. WHERE
  3328. c_id = $course_id AND
  3329. lp_item_id='".$lp_item_id."' AND
  3330. lp_view_id ='".$lp_view_id."' AND
  3331. status='completed'";
  3332. $result = Database::query($sql);
  3333. $row_count = Database:: fetch_row($result);
  3334. $count_item_view = (int) $row_count[0];
  3335. $not_multiple_attempt = 0;
  3336. if ($prevent_reinit === 1 && $count_item_view > 0) {
  3337. $not_multiple_attempt = 1;
  3338. }
  3339. $file .= '&not_multiple_attempt='.$not_multiple_attempt;
  3340. }
  3341. break;
  3342. }
  3343. $tmp_array = explode('/', $file);
  3344. $document_name = $tmp_array[count($tmp_array) - 1];
  3345. if (strpos($document_name, '_DELETED_')) {
  3346. $file = 'blank.php?error=document_deleted';
  3347. }
  3348. break;
  3349. case 2:
  3350. if ($this->debug > 2) {
  3351. error_log('In learnpath::get_link() '.__LINE__.' - Item type: '.$lp_item_type, 0);
  3352. }
  3353. if ($lp_item_type != 'dir') {
  3354. // Quite complex here:
  3355. // We want to make sure 'http://' (and similar) links can
  3356. // be loaded as is (withouth the Chamilo path in front) but
  3357. // some contents use this form: resource.htm?resource=http://blablabla
  3358. // which means we have to find a protocol at the path's start, otherwise
  3359. // it should not be considered as an external URL.
  3360. // if ($this->prerequisites_match($item_id)) {
  3361. if (preg_match('#^[a-zA-Z]{2,5}://#', $lp_item_path) != 0) {
  3362. if ($this->debug > 2) {
  3363. error_log('In learnpath::get_link() '.__LINE__.' - Found match for protocol in '.$lp_item_path, 0);
  3364. }
  3365. // Distant url, return as is.
  3366. $file = $lp_item_path;
  3367. } else {
  3368. if ($this->debug > 2) {
  3369. error_log('In learnpath::get_link() '.__LINE__.' - No starting protocol in '.$lp_item_path, 0);
  3370. }
  3371. // Prevent getting untranslatable urls.
  3372. $lp_item_path = preg_replace('/%2F/', '/', $lp_item_path);
  3373. $lp_item_path = preg_replace('/%3A/', ':', $lp_item_path);
  3374. // Prepare the path.
  3375. $file = $course_path.'/scorm/'.$lp_path.'/'.$lp_item_path;
  3376. // TODO: Fix this for urls with protocol header.
  3377. $file = str_replace('//', '/', $file);
  3378. $file = str_replace(':/', '://', $file);
  3379. if (substr($lp_path, -1) == '/') {
  3380. $lp_path = substr($lp_path, 0, -1);
  3381. }
  3382. if (!is_file(realpath($sys_course_path.'/scorm/'.$lp_path.'/'.$lp_item_path))) {
  3383. // if file not found.
  3384. $decoded = html_entity_decode($lp_item_path);
  3385. list($decoded) = explode('?', $decoded);
  3386. if (!is_file(realpath($sys_course_path.'/scorm/'.$lp_path.'/'.$decoded))) {
  3387. $file = self::rl_get_resource_link_for_learnpath(
  3388. $course_id,
  3389. $this->get_id(),
  3390. $item_id,
  3391. $this->get_view_id()
  3392. );
  3393. if (empty($file)) {
  3394. $file = 'blank.php?error=document_not_found';
  3395. } else {
  3396. $tmp_array = explode('/', $file);
  3397. $document_name = $tmp_array[count($tmp_array) - 1];
  3398. if (strpos($document_name, '_DELETED_')) {
  3399. $file = 'blank.php?error=document_deleted';
  3400. } else {
  3401. $file = 'blank.php?error=document_not_found';
  3402. }
  3403. }
  3404. } else {
  3405. $file = $course_path.'/scorm/'.$lp_path.'/'.$decoded;
  3406. }
  3407. }
  3408. }
  3409. // We want to use parameters if they were defined in the imsmanifest
  3410. if (strpos($file, 'blank.php') === false) {
  3411. $lp_item_params = ltrim($lp_item_params, '?');
  3412. $file .= (strstr($file, '?') === false ? '?' : '').$lp_item_params;
  3413. }
  3414. } else {
  3415. $file = 'lp_content.php?type=dir';
  3416. }
  3417. break;
  3418. case 3:
  3419. if ($this->debug > 2) {
  3420. error_log('In learnpath::get_link() '.__LINE__.' - Item type: '.$lp_item_type, 0);
  3421. }
  3422. // Formatting AICC HACP append URL.
  3423. $aicc_append = '?aicc_sid='.urlencode(session_id()).'&aicc_url='.urlencode(api_get_path(WEB_CODE_PATH).'lp/aicc_hacp.php').'&';
  3424. if (!empty($lp_item_params)) {
  3425. $aicc_append .= $lp_item_params.'&';
  3426. }
  3427. if ($lp_item_type != 'dir') {
  3428. // Quite complex here:
  3429. // We want to make sure 'http://' (and similar) links can
  3430. // be loaded as is (withouth the Chamilo path in front) but
  3431. // some contents use this form: resource.htm?resource=http://blablabla
  3432. // which means we have to find a protocol at the path's start, otherwise
  3433. // it should not be considered as an external URL.
  3434. if (preg_match('#^[a-zA-Z]{2,5}://#', $lp_item_path) != 0) {
  3435. if ($this->debug > 2) {
  3436. error_log('In learnpath::get_link() '.__LINE__.' - Found match for protocol in '.$lp_item_path, 0);
  3437. }
  3438. // Distant url, return as is.
  3439. $file = $lp_item_path;
  3440. // Enabled and modified by Ivan Tcholakov, 16-OCT-2008.
  3441. /*
  3442. if (stristr($file,'<servername>') !== false) {
  3443. $file = str_replace('<servername>', $course_path.'/scorm/'.$lp_path.'/', $lp_item_path);
  3444. }
  3445. */
  3446. if (stripos($file, '<servername>') !== false) {
  3447. //$file = str_replace('<servername>',$course_path.'/scorm/'.$lp_path.'/',$lp_item_path);
  3448. $web_course_path = str_replace('https://', '', str_replace('http://', '', $course_path));
  3449. $file = str_replace('<servername>', $web_course_path.'/scorm/'.$lp_path, $lp_item_path);
  3450. }
  3451. $file .= $aicc_append;
  3452. } else {
  3453. if ($this->debug > 2) {
  3454. error_log('In learnpath::get_link() '.__LINE__.' - No starting protocol in '.$lp_item_path, 0);
  3455. }
  3456. // Prevent getting untranslatable urls.
  3457. $lp_item_path = preg_replace('/%2F/', '/', $lp_item_path);
  3458. $lp_item_path = preg_replace('/%3A/', ':', $lp_item_path);
  3459. // Prepare the path - lp_path might be unusable because it includes the "aicc" subdir name.
  3460. $file = $course_path.'/scorm/'.$lp_path.'/'.$lp_item_path;
  3461. // TODO: Fix this for urls with protocol header.
  3462. $file = str_replace('//', '/', $file);
  3463. $file = str_replace(':/', '://', $file);
  3464. $file .= $aicc_append;
  3465. }
  3466. } else {
  3467. $file = 'lp_content.php?type=dir';
  3468. }
  3469. break;
  3470. case 4:
  3471. break;
  3472. default:
  3473. break;
  3474. }
  3475. // Replace &amp; by & because &amp; will break URL with params
  3476. $file = !empty($file) ? str_replace('&amp;', '&', $file) : '';
  3477. }
  3478. if ($this->debug > 2) {
  3479. error_log('In learnpath::get_link() - returning "'.$file.'" from get_link', 0);
  3480. }
  3481. return $file;
  3482. }
  3483. /**
  3484. * Gets the latest usable view or generate a new one.
  3485. *
  3486. * @param int $attempt_num Optional attempt number. If none given, takes the highest from the lp_view table
  3487. *
  3488. * @return int DB lp_view id
  3489. */
  3490. public function get_view($attempt_num = 0)
  3491. {
  3492. $search = '';
  3493. // Use $attempt_num to enable multi-views management (disabled so far).
  3494. if ($attempt_num != 0 && intval(strval($attempt_num)) == $attempt_num) {
  3495. $search = 'AND view_count = '.$attempt_num;
  3496. }
  3497. // When missing $attempt_num, search for a unique lp_view record for this lp and user.
  3498. $lp_view_table = Database::get_course_table(TABLE_LP_VIEW);
  3499. $course_id = api_get_course_int_id();
  3500. $sessionId = api_get_session_id();
  3501. $sql = "SELECT iid, view_count FROM $lp_view_table
  3502. WHERE
  3503. c_id = $course_id AND
  3504. lp_id = ".$this->get_id()." AND
  3505. user_id = ".$this->get_user_id()." AND
  3506. session_id = $sessionId
  3507. $search
  3508. ORDER BY view_count DESC";
  3509. $res = Database::query($sql);
  3510. if (Database::num_rows($res) > 0) {
  3511. $row = Database::fetch_array($res);
  3512. $this->lp_view_id = $row['iid'];
  3513. } elseif (!api_is_invitee()) {
  3514. // There is no database record, create one.
  3515. $sql = "INSERT INTO $lp_view_table (c_id, lp_id, user_id, view_count, session_id) VALUES
  3516. ($course_id, ".$this->get_id().",".$this->get_user_id().", 1, $sessionId)";
  3517. Database::query($sql);
  3518. $id = Database::insert_id();
  3519. $this->lp_view_id = $id;
  3520. $sql = "UPDATE $lp_view_table SET id = iid WHERE iid = $id";
  3521. Database::query($sql);
  3522. }
  3523. return $this->lp_view_id;
  3524. }
  3525. /**
  3526. * Gets the current view id.
  3527. *
  3528. * @return int View ID (from lp_view)
  3529. */
  3530. public function get_view_id()
  3531. {
  3532. if (!empty($this->lp_view_id)) {
  3533. return (int) $this->lp_view_id;
  3534. }
  3535. return 0;
  3536. }
  3537. /**
  3538. * Gets the update queue.
  3539. *
  3540. * @return array Array containing IDs of items to be updated by JavaScript
  3541. */
  3542. public function get_update_queue()
  3543. {
  3544. return $this->update_queue;
  3545. }
  3546. /**
  3547. * Gets the user ID.
  3548. *
  3549. * @return int User ID
  3550. */
  3551. public function get_user_id()
  3552. {
  3553. if (!empty($this->user_id)) {
  3554. return (int) $this->user_id;
  3555. }
  3556. return false;
  3557. }
  3558. /**
  3559. * Checks if any of the items has an audio element attached.
  3560. *
  3561. * @return bool True or false
  3562. */
  3563. public function has_audio()
  3564. {
  3565. $has = false;
  3566. foreach ($this->items as $i => $item) {
  3567. if (!empty($this->items[$i]->audio)) {
  3568. $has = true;
  3569. break;
  3570. }
  3571. }
  3572. return $has;
  3573. }
  3574. /**
  3575. * Moves an item up and down at its level.
  3576. *
  3577. * @param int $id Item to move up and down
  3578. * @param string $direction Direction 'up' or 'down'
  3579. *
  3580. * @return bool|int
  3581. */
  3582. public function move_item($id, $direction)
  3583. {
  3584. $course_id = api_get_course_int_id();
  3585. if (empty($id) || empty($direction)) {
  3586. return false;
  3587. }
  3588. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  3589. $sql_sel = "SELECT *
  3590. FROM $tbl_lp_item
  3591. WHERE
  3592. iid = $id
  3593. ";
  3594. $res_sel = Database::query($sql_sel);
  3595. // Check if elem exists.
  3596. if (Database::num_rows($res_sel) < 1) {
  3597. return false;
  3598. }
  3599. // Gather data.
  3600. $row = Database::fetch_array($res_sel);
  3601. $previous = $row['previous_item_id'];
  3602. $next = $row['next_item_id'];
  3603. $display = $row['display_order'];
  3604. $parent = $row['parent_item_id'];
  3605. $lp = $row['lp_id'];
  3606. // Update the item (switch with previous/next one).
  3607. switch ($direction) {
  3608. case 'up':
  3609. if ($display > 1) {
  3610. $sql_sel2 = "SELECT * FROM $tbl_lp_item
  3611. WHERE iid = $previous";
  3612. $res_sel2 = Database::query($sql_sel2);
  3613. if (Database::num_rows($res_sel2) < 1) {
  3614. $previous_previous = 0;
  3615. }
  3616. // Gather data.
  3617. $row2 = Database::fetch_array($res_sel2);
  3618. $previous_previous = $row2['previous_item_id'];
  3619. // Update previous_previous item (switch "next" with current).
  3620. if ($previous_previous != 0) {
  3621. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3622. next_item_id = $id
  3623. WHERE iid = $previous_previous";
  3624. Database::query($sql_upd2);
  3625. }
  3626. // Update previous item (switch with current).
  3627. if ($previous != 0) {
  3628. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3629. next_item_id = $next,
  3630. previous_item_id = $id,
  3631. display_order = display_order +1
  3632. WHERE iid = $previous";
  3633. Database::query($sql_upd2);
  3634. }
  3635. // Update current item (switch with previous).
  3636. if ($id != 0) {
  3637. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3638. next_item_id = $previous,
  3639. previous_item_id = $previous_previous,
  3640. display_order = display_order-1
  3641. WHERE c_id = ".$course_id." AND id = $id";
  3642. Database::query($sql_upd2);
  3643. }
  3644. // Update next item (new previous item).
  3645. if (!empty($next)) {
  3646. $sql_upd2 = "UPDATE $tbl_lp_item SET previous_item_id = $previous
  3647. WHERE iid = $next";
  3648. Database::query($sql_upd2);
  3649. }
  3650. $display = $display - 1;
  3651. }
  3652. break;
  3653. case 'down':
  3654. if ($next != 0) {
  3655. $sql_sel2 = "SELECT * FROM $tbl_lp_item
  3656. WHERE iid = $next";
  3657. $res_sel2 = Database::query($sql_sel2);
  3658. if (Database::num_rows($res_sel2) < 1) {
  3659. $next_next = 0;
  3660. }
  3661. // Gather data.
  3662. $row2 = Database::fetch_array($res_sel2);
  3663. $next_next = $row2['next_item_id'];
  3664. // Update previous item (switch with current).
  3665. if ($previous != 0) {
  3666. $sql_upd2 = "UPDATE $tbl_lp_item
  3667. SET next_item_id = $next
  3668. WHERE iid = $previous";
  3669. Database::query($sql_upd2);
  3670. }
  3671. // Update current item (switch with previous).
  3672. if ($id != 0) {
  3673. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3674. previous_item_id = $next,
  3675. next_item_id = $next_next,
  3676. display_order = display_order + 1
  3677. WHERE iid = $id";
  3678. Database::query($sql_upd2);
  3679. }
  3680. // Update next item (new previous item).
  3681. if ($next != 0) {
  3682. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3683. previous_item_id = $previous,
  3684. next_item_id = $id,
  3685. display_order = display_order-1
  3686. WHERE iid = $next";
  3687. Database::query($sql_upd2);
  3688. }
  3689. // Update next_next item (switch "previous" with current).
  3690. if ($next_next != 0) {
  3691. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3692. previous_item_id = $id
  3693. WHERE iid = $next_next";
  3694. Database::query($sql_upd2);
  3695. }
  3696. $display = $display + 1;
  3697. }
  3698. break;
  3699. default:
  3700. return false;
  3701. }
  3702. return $display;
  3703. }
  3704. /**
  3705. * Move a LP up (display_order).
  3706. *
  3707. * @param int $lp_id Learnpath ID
  3708. * @param int $categoryId Category ID
  3709. *
  3710. * @return bool
  3711. */
  3712. public static function move_up($lp_id, $categoryId = 0)
  3713. {
  3714. $courseId = api_get_course_int_id();
  3715. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3716. $categoryCondition = '';
  3717. if (!empty($categoryId)) {
  3718. $categoryId = (int) $categoryId;
  3719. $categoryCondition = " AND category_id = $categoryId";
  3720. }
  3721. $sql = "SELECT * FROM $lp_table
  3722. WHERE c_id = $courseId
  3723. $categoryCondition
  3724. ORDER BY display_order";
  3725. $res = Database::query($sql);
  3726. if ($res === false) {
  3727. return false;
  3728. }
  3729. $lps = [];
  3730. $lp_order = [];
  3731. $num = Database::num_rows($res);
  3732. // First check the order is correct, globally (might be wrong because
  3733. // of versions < 1.8.4)
  3734. if ($num > 0) {
  3735. $i = 1;
  3736. while ($row = Database::fetch_array($res)) {
  3737. if ($row['display_order'] != $i) { // If we find a gap in the order, we need to fix it.
  3738. $sql = "UPDATE $lp_table SET display_order = $i
  3739. WHERE iid = ".$row['iid'];
  3740. Database::query($sql);
  3741. }
  3742. $row['display_order'] = $i;
  3743. $lps[$row['iid']] = $row;
  3744. $lp_order[$i] = $row['iid'];
  3745. $i++;
  3746. }
  3747. }
  3748. if ($num > 1) { // If there's only one element, no need to sort.
  3749. $order = $lps[$lp_id]['display_order'];
  3750. if ($order > 1) { // If it's the first element, no need to move up.
  3751. $sql = "UPDATE $lp_table SET display_order = $order
  3752. WHERE iid = ".$lp_order[$order - 1];
  3753. Database::query($sql);
  3754. $sql = "UPDATE $lp_table SET display_order = ".($order - 1)."
  3755. WHERE iid = $lp_id";
  3756. Database::query($sql);
  3757. }
  3758. }
  3759. return true;
  3760. }
  3761. /**
  3762. * Move a learnpath down (display_order).
  3763. *
  3764. * @param int $lp_id Learnpath ID
  3765. * @param int $categoryId Category ID
  3766. *
  3767. * @return bool
  3768. */
  3769. public static function move_down($lp_id, $categoryId = 0)
  3770. {
  3771. $courseId = api_get_course_int_id();
  3772. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3773. $categoryCondition = '';
  3774. if (!empty($categoryId)) {
  3775. $categoryId = (int) $categoryId;
  3776. $categoryCondition = " AND category_id = $categoryId";
  3777. }
  3778. $sql = "SELECT * FROM $lp_table
  3779. WHERE c_id = $courseId
  3780. $categoryCondition
  3781. ORDER BY display_order";
  3782. $res = Database::query($sql);
  3783. if ($res === false) {
  3784. return false;
  3785. }
  3786. $lps = [];
  3787. $lp_order = [];
  3788. $num = Database::num_rows($res);
  3789. $max = 0;
  3790. // First check the order is correct, globally (might be wrong because
  3791. // of versions < 1.8.4).
  3792. if ($num > 0) {
  3793. $i = 1;
  3794. while ($row = Database::fetch_array($res)) {
  3795. $max = $i;
  3796. if ($row['display_order'] != $i) {
  3797. // If we find a gap in the order, we need to fix it.
  3798. $sql = "UPDATE $lp_table SET display_order = $i
  3799. WHERE iid = ".$row['iid'];
  3800. Database::query($sql);
  3801. }
  3802. $row['display_order'] = $i;
  3803. $lps[$row['iid']] = $row;
  3804. $lp_order[$i] = $row['iid'];
  3805. $i++;
  3806. }
  3807. }
  3808. if ($num > 1) { // If there's only one element, no need to sort.
  3809. $order = $lps[$lp_id]['display_order'];
  3810. if ($order < $max) { // If it's the first element, no need to move up.
  3811. $sql = "UPDATE $lp_table SET display_order = $order
  3812. WHERE iid = ".$lp_order[$order + 1];
  3813. Database::query($sql);
  3814. $sql = "UPDATE $lp_table SET display_order = ".($order + 1)."
  3815. WHERE iid = $lp_id";
  3816. Database::query($sql);
  3817. }
  3818. }
  3819. return true;
  3820. }
  3821. /**
  3822. * Updates learnpath attributes to point to the next element
  3823. * The last part is similar to set_current_item but processing the other way around.
  3824. */
  3825. public function next()
  3826. {
  3827. if ($this->debug > 0) {
  3828. error_log('In learnpath::next()', 0);
  3829. }
  3830. $this->last = $this->get_current_item_id();
  3831. $this->items[$this->last]->save(
  3832. false,
  3833. $this->prerequisites_match($this->last)
  3834. );
  3835. $this->autocomplete_parents($this->last);
  3836. $new_index = $this->get_next_index();
  3837. if ($this->debug > 2) {
  3838. error_log('New index: '.$new_index, 0);
  3839. }
  3840. $this->index = $new_index;
  3841. if ($this->debug > 2) {
  3842. error_log('Now having orderedlist['.$new_index.'] = '.$this->ordered_items[$new_index], 0);
  3843. }
  3844. $this->current = $this->ordered_items[$new_index];
  3845. if ($this->debug > 2) {
  3846. error_log('new item id is '.$this->current.'-'.$this->get_current_item_id(), 0);
  3847. }
  3848. }
  3849. /**
  3850. * Open a resource = initialise all local variables relative to this resource. Depending on the child
  3851. * class, this might be redefined to allow several behaviours depending on the document type.
  3852. *
  3853. * @param int $id Resource ID
  3854. */
  3855. public function open($id)
  3856. {
  3857. // TODO:
  3858. // set the current resource attribute to this resource
  3859. // switch on element type (redefine in child class?)
  3860. // set status for this item to "opened"
  3861. // start timer
  3862. // initialise score
  3863. $this->index = 0; //or = the last item seen (see $this->last)
  3864. }
  3865. /**
  3866. * Check that all prerequisites are fulfilled. Returns true and an
  3867. * empty string on success, returns false
  3868. * and the prerequisite string on error.
  3869. * This function is based on the rules for aicc_script language as
  3870. * described in the SCORM 1.2 CAM documentation page 108.
  3871. *
  3872. * @param int $itemId Optional item ID. If none given, uses the current open item.
  3873. *
  3874. * @return bool true if prerequisites are matched, false otherwise - Empty string if true returned, prerequisites
  3875. * string otherwise
  3876. */
  3877. public function prerequisites_match($itemId = null)
  3878. {
  3879. $allow = api_get_configuration_value('allow_teachers_to_access_blocked_lp_by_prerequisite');
  3880. if ($allow) {
  3881. if (api_is_allowed_to_edit() ||
  3882. api_is_platform_admin(true) ||
  3883. api_is_drh() ||
  3884. api_is_coach(api_get_session_id(), api_get_course_int_id())
  3885. ) {
  3886. return true;
  3887. }
  3888. }
  3889. $debug = $this->debug;
  3890. if ($debug > 0) {
  3891. error_log('In learnpath::prerequisites_match()');
  3892. }
  3893. if (empty($itemId)) {
  3894. $itemId = $this->current;
  3895. }
  3896. $currentItem = $this->getItem($itemId);
  3897. if ($currentItem) {
  3898. if ($this->type == 2) {
  3899. // Getting prereq from scorm
  3900. $prereq_string = $this->get_scorm_prereq_string($itemId);
  3901. } else {
  3902. $prereq_string = $currentItem->get_prereq_string();
  3903. }
  3904. if (empty($prereq_string)) {
  3905. if ($debug > 0) {
  3906. error_log('Found prereq_string is empty return true');
  3907. }
  3908. return true;
  3909. }
  3910. // Clean spaces.
  3911. $prereq_string = str_replace(' ', '', $prereq_string);
  3912. if ($debug > 0) {
  3913. error_log('Found prereq_string: '.$prereq_string, 0);
  3914. }
  3915. // Now send to the parse_prereq() function that will check this component's prerequisites.
  3916. $result = $currentItem->parse_prereq(
  3917. $prereq_string,
  3918. $this->items,
  3919. $this->refs_list,
  3920. $this->get_user_id()
  3921. );
  3922. if ($result === false) {
  3923. $this->set_error_msg($currentItem->prereq_alert);
  3924. }
  3925. } else {
  3926. $result = true;
  3927. if ($debug > 1) {
  3928. error_log('$this->items['.$itemId.'] was not an object', 0);
  3929. }
  3930. }
  3931. if ($debug > 1) {
  3932. error_log('End of prerequisites_match(). Error message is now '.$this->error, 0);
  3933. }
  3934. return $result;
  3935. }
  3936. /**
  3937. * Updates learnpath attributes to point to the previous element
  3938. * The last part is similar to set_current_item but processing the other way around.
  3939. */
  3940. public function previous()
  3941. {
  3942. $this->last = $this->get_current_item_id();
  3943. $this->items[$this->last]->save(
  3944. false,
  3945. $this->prerequisites_match($this->last)
  3946. );
  3947. $this->autocomplete_parents($this->last);
  3948. $new_index = $this->get_previous_index();
  3949. $this->index = $new_index;
  3950. $this->current = $this->ordered_items[$new_index];
  3951. }
  3952. /**
  3953. * Publishes a learnpath. This basically means show or hide the learnpath
  3954. * to normal users.
  3955. * Can be used as abstract.
  3956. *
  3957. * @param int $lp_id Learnpath ID
  3958. * @param int $set_visibility New visibility
  3959. *
  3960. * @return bool
  3961. */
  3962. public static function toggle_visibility($lp_id, $set_visibility = 1)
  3963. {
  3964. $action = 'visible';
  3965. if ($set_visibility != 1) {
  3966. $action = 'invisible';
  3967. self::toggle_publish($lp_id, 'i');
  3968. }
  3969. return api_item_property_update(
  3970. api_get_course_info(),
  3971. TOOL_LEARNPATH,
  3972. $lp_id,
  3973. $action,
  3974. api_get_user_id()
  3975. );
  3976. }
  3977. /**
  3978. * Publishes a learnpath category.
  3979. * This basically means show or hide the learnpath category to normal users.
  3980. *
  3981. * @param int $id
  3982. * @param int $visibility
  3983. *
  3984. * @throws \Doctrine\ORM\NonUniqueResultException
  3985. * @throws \Doctrine\ORM\ORMException
  3986. * @throws \Doctrine\ORM\OptimisticLockException
  3987. * @throws \Doctrine\ORM\TransactionRequiredException
  3988. *
  3989. * @return bool
  3990. */
  3991. public static function toggleCategoryVisibility($id, $visibility = 1)
  3992. {
  3993. $action = 'visible';
  3994. if ($visibility != 1) {
  3995. $action = 'invisible';
  3996. $list = new LearnpathList(
  3997. api_get_user_id(),
  3998. null,
  3999. null,
  4000. null,
  4001. false,
  4002. $id
  4003. );
  4004. $lpList = $list->get_flat_list();
  4005. foreach ($lpList as $lp) {
  4006. self::toggle_visibility($lp['iid'], 0);
  4007. }
  4008. self::toggleCategoryPublish($id, 0);
  4009. }
  4010. return api_item_property_update(
  4011. api_get_course_info(),
  4012. TOOL_LEARNPATH_CATEGORY,
  4013. $id,
  4014. $action,
  4015. api_get_user_id()
  4016. );
  4017. }
  4018. /**
  4019. * Publishes a learnpath. This basically means show or hide the learnpath
  4020. * on the course homepage
  4021. * Can be used as abstract.
  4022. *
  4023. * @param int $lp_id Learnpath id
  4024. * @param string $set_visibility New visibility (v/i - visible/invisible)
  4025. *
  4026. * @return bool
  4027. */
  4028. public static function toggle_publish($lp_id, $set_visibility = 'v')
  4029. {
  4030. $course_id = api_get_course_int_id();
  4031. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4032. $lp_id = (int) $lp_id;
  4033. $sql = "SELECT * FROM $tbl_lp
  4034. WHERE iid = $lp_id";
  4035. $result = Database::query($sql);
  4036. if (Database::num_rows($result)) {
  4037. $row = Database::fetch_array($result);
  4038. $name = Database::escape_string($row['name']);
  4039. if ($set_visibility == 'i') {
  4040. $v = 0;
  4041. }
  4042. if ($set_visibility == 'v') {
  4043. $v = 1;
  4044. }
  4045. $session_id = api_get_session_id();
  4046. $session_condition = api_get_session_condition($session_id);
  4047. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  4048. $link = 'lp/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  4049. $oldLink = 'newscorm/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  4050. $sql = "SELECT * FROM $tbl_tool
  4051. WHERE
  4052. c_id = $course_id AND
  4053. (link = '$link' OR link = '$oldLink') AND
  4054. image = 'scormbuilder.gif' AND
  4055. (
  4056. link LIKE '$link%' OR
  4057. link LIKE '$oldLink%'
  4058. )
  4059. $session_condition
  4060. ";
  4061. $result = Database::query($sql);
  4062. $num = Database::num_rows($result);
  4063. if ($set_visibility == 'i' && $num > 0) {
  4064. $sql = "DELETE FROM $tbl_tool
  4065. WHERE
  4066. c_id = $course_id AND
  4067. (link = '$link' OR link = '$oldLink') AND
  4068. image='scormbuilder.gif'
  4069. $session_condition";
  4070. Database::query($sql);
  4071. } elseif ($set_visibility == 'v' && $num == 0) {
  4072. $sql = "INSERT INTO $tbl_tool (category, c_id, name, link, image, visibility, admin, address, added_tool, session_id) VALUES
  4073. ('authoring', $course_id, '$name', '$link', 'scormbuilder.gif', '$v', '0','pastillegris.gif', 0, $session_id)";
  4074. Database::query($sql);
  4075. $insertId = Database::insert_id();
  4076. if ($insertId) {
  4077. $sql = "UPDATE $tbl_tool SET id = iid WHERE iid = $insertId";
  4078. Database::query($sql);
  4079. }
  4080. } elseif ($set_visibility == 'v' && $num > 0) {
  4081. $sql = "UPDATE $tbl_tool SET
  4082. c_id = $course_id,
  4083. name = '$name',
  4084. link = '$link',
  4085. image = 'scormbuilder.gif',
  4086. visibility = '$v',
  4087. admin = '0',
  4088. address = 'pastillegris.gif',
  4089. added_tool = 0,
  4090. session_id = $session_id
  4091. WHERE
  4092. c_id = ".$course_id." AND
  4093. (link = '$link' OR link = '$oldLink') AND
  4094. image='scormbuilder.gif'
  4095. $session_condition
  4096. ";
  4097. Database::query($sql);
  4098. } else {
  4099. // Parameter and database incompatible, do nothing, exit.
  4100. return false;
  4101. }
  4102. } else {
  4103. return false;
  4104. }
  4105. }
  4106. /**
  4107. * Publishes a learnpath.
  4108. * Show or hide the learnpath category on the course homepage.
  4109. *
  4110. * @param int $id
  4111. * @param int $setVisibility
  4112. *
  4113. * @throws \Doctrine\ORM\NonUniqueResultException
  4114. * @throws \Doctrine\ORM\ORMException
  4115. * @throws \Doctrine\ORM\OptimisticLockException
  4116. * @throws \Doctrine\ORM\TransactionRequiredException
  4117. *
  4118. * @return bool
  4119. */
  4120. public static function toggleCategoryPublish($id, $setVisibility = 1)
  4121. {
  4122. $courseId = api_get_course_int_id();
  4123. $sessionId = api_get_session_id();
  4124. $sessionCondition = api_get_session_condition(
  4125. $sessionId,
  4126. true,
  4127. false,
  4128. 't.sessionId'
  4129. );
  4130. $em = Database::getManager();
  4131. /** @var CLpCategory $category */
  4132. $category = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  4133. if (!$category) {
  4134. return false;
  4135. }
  4136. if (empty($courseId)) {
  4137. return false;
  4138. }
  4139. $link = self::getCategoryLinkForTool($id);
  4140. /** @var CTool $tool */
  4141. $tool = $em->createQuery("
  4142. SELECT t FROM ChamiloCourseBundle:CTool t
  4143. WHERE
  4144. t.cId = :course AND
  4145. t.link = :link1 AND
  4146. t.image = 'lp_category.gif' AND
  4147. t.link LIKE :link2
  4148. $sessionCondition
  4149. ")
  4150. ->setParameters([
  4151. 'course' => (int) $courseId,
  4152. 'link1' => $link,
  4153. 'link2' => "$link%",
  4154. ])
  4155. ->getOneOrNullResult();
  4156. if ($setVisibility == 0 && $tool) {
  4157. $em->remove($tool);
  4158. $em->flush();
  4159. return true;
  4160. }
  4161. if ($setVisibility == 1 && !$tool) {
  4162. $tool = new CTool();
  4163. $tool
  4164. ->setCategory('authoring')
  4165. ->setCId($courseId)
  4166. ->setName(strip_tags($category->getName()))
  4167. ->setLink($link)
  4168. ->setImage('lp_category.gif')
  4169. ->setVisibility(1)
  4170. ->setAdmin(0)
  4171. ->setAddress('pastillegris.gif')
  4172. ->setAddedTool(0)
  4173. ->setSessionId($sessionId)
  4174. ->setTarget('_self');
  4175. $em->persist($tool);
  4176. $em->flush();
  4177. $tool->setId($tool->getIid());
  4178. $em->persist($tool);
  4179. $em->flush();
  4180. return true;
  4181. }
  4182. if ($setVisibility == 1 && $tool) {
  4183. $tool
  4184. ->setName(strip_tags($category->getName()))
  4185. ->setVisibility(1);
  4186. $em->persist($tool);
  4187. $em->flush();
  4188. return true;
  4189. }
  4190. return false;
  4191. }
  4192. /**
  4193. * Check if the learnpath category is visible for a user.
  4194. *
  4195. * @param CLpCategory $category
  4196. * @param User $user
  4197. * @param int
  4198. * @param int
  4199. *
  4200. * @return bool
  4201. */
  4202. public static function categoryIsVisibleForStudent(
  4203. CLpCategory $category,
  4204. User $user,
  4205. $courseId = 0,
  4206. $sessionId = 0
  4207. ) {
  4208. $subscriptionSettings = self::getSubscriptionSettings();
  4209. if ($subscriptionSettings['allow_add_users_to_lp_category'] == false) {
  4210. return true;
  4211. }
  4212. $isAllowedToEdit = api_is_allowed_to_edit(null, true);
  4213. if ($isAllowedToEdit) {
  4214. return true;
  4215. }
  4216. if (empty($category)) {
  4217. return false;
  4218. }
  4219. $users = $category->getUsers();
  4220. if (empty($users) || !$users->count()) {
  4221. return true;
  4222. }
  4223. $courseId = empty($courseId) ? api_get_course_int_id() : (int) $courseId;
  4224. $sessionId = empty($sessionId) ? api_get_session_id() : (int) $sessionId;
  4225. if ($category->hasUserAdded($user)) {
  4226. return true;
  4227. }
  4228. $groups = GroupManager::getAllGroupPerUserSubscription($user->getId());
  4229. if (!empty($groups)) {
  4230. $em = Database::getManager();
  4231. /** @var ItemPropertyRepository $itemRepo */
  4232. $itemRepo = $em->getRepository('ChamiloCourseBundle:CItemProperty');
  4233. /** @var CourseRepository $courseRepo */
  4234. $courseRepo = $em->getRepository('ChamiloCoreBundle:Course');
  4235. $session = null;
  4236. if (!empty($sessionId)) {
  4237. $session = $em->getRepository('ChamiloCoreBundle:Session')->find($sessionId);
  4238. }
  4239. $course = $courseRepo->find($courseId);
  4240. // Subscribed groups to a LP
  4241. $subscribedGroupsInLp = $itemRepo->getGroupsSubscribedToItem(
  4242. TOOL_LEARNPATH_CATEGORY,
  4243. $category->getId(),
  4244. $course,
  4245. $session
  4246. );
  4247. if (!empty($subscribedGroupsInLp)) {
  4248. $groups = array_column($groups, 'iid');
  4249. /** @var CItemProperty $item */
  4250. foreach ($subscribedGroupsInLp as $item) {
  4251. if ($item->getGroup() &&
  4252. in_array($item->getGroup()->getId(), $groups)
  4253. ) {
  4254. return true;
  4255. }
  4256. }
  4257. }
  4258. }
  4259. return false;
  4260. }
  4261. /**
  4262. * Check if a learnpath category is published as course tool.
  4263. *
  4264. * @param CLpCategory $category
  4265. * @param int $courseId
  4266. *
  4267. * @return bool
  4268. */
  4269. public static function categoryIsPublished(
  4270. CLpCategory $category,
  4271. $courseId
  4272. ) {
  4273. $link = self::getCategoryLinkForTool($category->getId());
  4274. $em = Database::getManager();
  4275. $tools = $em
  4276. ->createQuery("
  4277. SELECT t FROM ChamiloCourseBundle:CTool t
  4278. WHERE t.cId = :course AND
  4279. t.name = :name AND
  4280. t.image = 'lp_category.gif' AND
  4281. t.link LIKE :link
  4282. ")
  4283. ->setParameters([
  4284. 'course' => $courseId,
  4285. 'name' => strip_tags($category->getName()),
  4286. 'link' => "$link%",
  4287. ])
  4288. ->getResult();
  4289. /** @var CTool $tool */
  4290. $tool = current($tools);
  4291. return $tool ? $tool->getVisibility() : false;
  4292. }
  4293. /**
  4294. * Restart the whole learnpath. Return the URL of the first element.
  4295. * Make sure the results are saved with anoter method. This method should probably be redefined in children classes.
  4296. * To use a similar method statically, use the create_new_attempt() method.
  4297. *
  4298. * @return bool
  4299. */
  4300. public function restart()
  4301. {
  4302. if ($this->debug > 0) {
  4303. error_log('In learnpath::restart()', 0);
  4304. }
  4305. // TODO
  4306. // Call autosave method to save the current progress.
  4307. //$this->index = 0;
  4308. if (api_is_invitee()) {
  4309. return false;
  4310. }
  4311. $session_id = api_get_session_id();
  4312. $course_id = api_get_course_int_id();
  4313. $lp_view_table = Database::get_course_table(TABLE_LP_VIEW);
  4314. $sql = "INSERT INTO $lp_view_table (c_id, lp_id, user_id, view_count, session_id)
  4315. VALUES ($course_id, ".$this->lp_id.",".$this->get_user_id().",".($this->attempt + 1).", $session_id)";
  4316. if ($this->debug > 2) {
  4317. error_log('Inserting new lp_view for restart: '.$sql, 0);
  4318. }
  4319. Database::query($sql);
  4320. $view_id = Database::insert_id();
  4321. if ($view_id) {
  4322. $sql = "UPDATE $lp_view_table SET id = iid WHERE iid = $view_id";
  4323. Database::query($sql);
  4324. $this->lp_view_id = $view_id;
  4325. $this->attempt = $this->attempt + 1;
  4326. } else {
  4327. $this->error = 'Could not insert into item_view table...';
  4328. return false;
  4329. }
  4330. $this->autocomplete_parents($this->current);
  4331. foreach ($this->items as $index => $dummy) {
  4332. $this->items[$index]->restart();
  4333. $this->items[$index]->set_lp_view($this->lp_view_id);
  4334. }
  4335. $this->first();
  4336. return true;
  4337. }
  4338. /**
  4339. * Saves the current item.
  4340. *
  4341. * @return bool
  4342. */
  4343. public function save_current()
  4344. {
  4345. $debug = $this->debug;
  4346. // TODO: Do a better check on the index pointing to the right item (it is supposed to be working
  4347. // on $ordered_items[] but not sure it's always safe to use with $items[]).
  4348. if ($debug) {
  4349. error_log('save_current() saving item '.$this->current, 0);
  4350. error_log(''.print_r($this->items, true), 0);
  4351. }
  4352. if (isset($this->items[$this->current]) &&
  4353. is_object($this->items[$this->current])
  4354. ) {
  4355. if ($debug) {
  4356. error_log('Before save last_scorm_session_time: '.$this->items[$this->current]->getLastScormSessionTime());
  4357. }
  4358. $res = $this->items[$this->current]->save(
  4359. false,
  4360. $this->prerequisites_match($this->current)
  4361. );
  4362. $this->autocomplete_parents($this->current);
  4363. $status = $this->items[$this->current]->get_status();
  4364. $this->update_queue[$this->current] = $status;
  4365. if ($debug) {
  4366. error_log('After save last_scorm_session_time: '.$this->items[$this->current]->getLastScormSessionTime());
  4367. }
  4368. return $res;
  4369. }
  4370. return false;
  4371. }
  4372. /**
  4373. * Saves the given item.
  4374. *
  4375. * @param int $item_id Optional (will take from $_REQUEST if null)
  4376. * @param bool $from_outside Save from url params (true) or from current attributes (false). Default true
  4377. *
  4378. * @return bool
  4379. */
  4380. public function save_item($item_id = null, $from_outside = true)
  4381. {
  4382. $debug = $this->debug;
  4383. if ($debug) {
  4384. error_log('In learnpath::save_item('.$item_id.','.intval($from_outside).')', 0);
  4385. }
  4386. // TODO: Do a better check on the index pointing to the right item (it is supposed to be working
  4387. // on $ordered_items[] but not sure it's always safe to use with $items[]).
  4388. if (empty($item_id)) {
  4389. $item_id = (int) $_REQUEST['id'];
  4390. }
  4391. if (empty($item_id)) {
  4392. $item_id = $this->get_current_item_id();
  4393. }
  4394. if (isset($this->items[$item_id]) &&
  4395. is_object($this->items[$item_id])
  4396. ) {
  4397. if ($debug) {
  4398. error_log('Object exists');
  4399. }
  4400. // Saving the item.
  4401. $res = $this->items[$item_id]->save(
  4402. $from_outside,
  4403. $this->prerequisites_match($item_id)
  4404. );
  4405. if ($debug) {
  4406. error_log('update_queue before:');
  4407. error_log(print_r($this->update_queue, 1));
  4408. }
  4409. $this->autocomplete_parents($item_id);
  4410. $status = $this->items[$item_id]->get_status();
  4411. $this->update_queue[$item_id] = $status;
  4412. if ($debug) {
  4413. error_log('get_status(): '.$status);
  4414. error_log('update_queue after:');
  4415. error_log(print_r($this->update_queue, 1));
  4416. }
  4417. return $res;
  4418. }
  4419. return false;
  4420. }
  4421. /**
  4422. * Saves the last item seen's ID only in case.
  4423. */
  4424. public function save_last()
  4425. {
  4426. $course_id = api_get_course_int_id();
  4427. $debug = $this->debug;
  4428. if ($debug) {
  4429. error_log('In learnpath::save_last()', 0);
  4430. }
  4431. $session_condition = api_get_session_condition(
  4432. api_get_session_id(),
  4433. true,
  4434. false
  4435. );
  4436. $table = Database::get_course_table(TABLE_LP_VIEW);
  4437. if (isset($this->current) && !api_is_invitee()) {
  4438. if ($debug) {
  4439. error_log('Saving current item ('.$this->current.') for later review', 0);
  4440. }
  4441. $sql = "UPDATE $table SET
  4442. last_item = ".$this->get_current_item_id()."
  4443. WHERE
  4444. c_id = $course_id AND
  4445. lp_id = ".$this->get_id()." AND
  4446. user_id = ".$this->get_user_id()." ".$session_condition;
  4447. if ($debug) {
  4448. error_log('Saving last item seen : '.$sql, 0);
  4449. }
  4450. Database::query($sql);
  4451. }
  4452. if (!api_is_invitee()) {
  4453. // Save progress.
  4454. list($progress) = $this->get_progress_bar_text('%');
  4455. if ($progress >= 0 && $progress <= 100) {
  4456. $progress = (int) $progress;
  4457. $sql = "UPDATE $table SET
  4458. progress = $progress
  4459. WHERE
  4460. c_id = $course_id AND
  4461. lp_id = ".$this->get_id()." AND
  4462. user_id = ".$this->get_user_id()." ".$session_condition;
  4463. // Ignore errors as some tables might not have the progress field just yet.
  4464. Database::query($sql);
  4465. $this->progress_db = $progress;
  4466. }
  4467. }
  4468. }
  4469. /**
  4470. * Sets the current item ID (checks if valid and authorized first).
  4471. *
  4472. * @param int $item_id New item ID. If not given or not authorized, defaults to current
  4473. */
  4474. public function set_current_item($item_id = null)
  4475. {
  4476. $debug = $this->debug;
  4477. if ($debug) {
  4478. error_log('In learnpath::set_current_item('.$item_id.')', 0);
  4479. }
  4480. if (empty($item_id)) {
  4481. if ($debug) {
  4482. error_log('No new current item given, ignore...', 0);
  4483. }
  4484. // Do nothing.
  4485. } else {
  4486. if ($debug) {
  4487. error_log('New current item given is '.$item_id.'...', 0);
  4488. }
  4489. if (is_numeric($item_id)) {
  4490. $item_id = (int) $item_id;
  4491. // TODO: Check in database here.
  4492. $this->last = $this->current;
  4493. $this->current = $item_id;
  4494. // TODO: Update $this->index as well.
  4495. foreach ($this->ordered_items as $index => $item) {
  4496. if ($item == $this->current) {
  4497. $this->index = $index;
  4498. break;
  4499. }
  4500. }
  4501. if ($debug) {
  4502. error_log('set_current_item('.$item_id.') done. Index is now : '.$this->index);
  4503. }
  4504. } else {
  4505. if ($debug) {
  4506. error_log('set_current_item('.$item_id.') failed. Not a numeric value: ');
  4507. }
  4508. }
  4509. }
  4510. }
  4511. /**
  4512. * Sets the encoding.
  4513. *
  4514. * @param string $enc New encoding
  4515. *
  4516. * @return bool
  4517. *
  4518. * @todo (as of Chamilo 1.8.8): Check in the future whether this method is needed.
  4519. */
  4520. public function set_encoding($enc = 'UTF-8')
  4521. {
  4522. $enc = api_refine_encoding_id($enc);
  4523. if (empty($enc)) {
  4524. $enc = api_get_system_encoding();
  4525. }
  4526. if (api_is_encoding_supported($enc)) {
  4527. $lp = $this->get_id();
  4528. if ($lp != 0) {
  4529. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4530. $sql = "UPDATE $tbl_lp SET default_encoding = '$enc'
  4531. WHERE iid = ".$lp;
  4532. $res = Database::query($sql);
  4533. return $res;
  4534. }
  4535. }
  4536. return false;
  4537. }
  4538. /**
  4539. * Sets the JS lib setting in the database directly.
  4540. * This is the JavaScript library file this lp needs to load on startup.
  4541. *
  4542. * @param string $lib Proximity setting
  4543. *
  4544. * @return bool True on update success. False otherwise.
  4545. */
  4546. public function set_jslib($lib = '')
  4547. {
  4548. $lp = $this->get_id();
  4549. if ($lp != 0) {
  4550. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4551. $lib = Database::escape_string($lib);
  4552. $sql = "UPDATE $tbl_lp SET js_lib = '$lib'
  4553. WHERE iid = $lp";
  4554. $res = Database::query($sql);
  4555. return $res;
  4556. }
  4557. return false;
  4558. }
  4559. /**
  4560. * Sets the name of the LP maker (publisher) (and save).
  4561. *
  4562. * @param string $name Optional string giving the new content_maker of this learnpath
  4563. *
  4564. * @return bool True
  4565. */
  4566. public function set_maker($name = '')
  4567. {
  4568. if (empty($name)) {
  4569. return false;
  4570. }
  4571. $this->maker = $name;
  4572. $table = Database::get_course_table(TABLE_LP_MAIN);
  4573. $lp_id = $this->get_id();
  4574. $sql = "UPDATE $table SET
  4575. content_maker = '".Database::escape_string($this->maker)."'
  4576. WHERE iid = $lp_id";
  4577. Database::query($sql);
  4578. return true;
  4579. }
  4580. /**
  4581. * Sets the name of the current learnpath (and save).
  4582. *
  4583. * @param string $name Optional string giving the new name of this learnpath
  4584. *
  4585. * @return bool True/False
  4586. */
  4587. public function set_name($name = null)
  4588. {
  4589. if (empty($name)) {
  4590. return false;
  4591. }
  4592. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4593. $name = Database::escape_string($name);
  4594. $this->name = $name;
  4595. $lp_id = $this->get_id();
  4596. $course_id = $this->course_info['real_id'];
  4597. $sql = "UPDATE $lp_table SET
  4598. name = '$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 = '$name'
  4608. WHERE
  4609. c_id = $course_id AND
  4610. (link='$link' AND image='scormbuilder.gif' $session_condition)";
  4611. Database::query($sql);
  4612. return true;
  4613. }
  4614. return false;
  4615. }
  4616. /**
  4617. * Set index specified prefix terms for all items in this path.
  4618. *
  4619. * @param string $terms_string Comma-separated list of terms
  4620. * @param string $prefix Xapian term prefix
  4621. *
  4622. * @return bool False on error, true otherwise
  4623. */
  4624. public function set_terms_by_prefix($terms_string, $prefix)
  4625. {
  4626. $course_id = api_get_course_int_id();
  4627. if (api_get_setting('search_enabled') !== 'true') {
  4628. return false;
  4629. }
  4630. if (!extension_loaded('xapian')) {
  4631. return false;
  4632. }
  4633. $terms_string = trim($terms_string);
  4634. $terms = explode(',', $terms_string);
  4635. array_walk($terms, 'trim_value');
  4636. $stored_terms = $this->get_common_index_terms_by_prefix($prefix);
  4637. // Don't do anything if no change, verify only at DB, not the search engine.
  4638. if ((count(array_diff($terms, $stored_terms)) == 0) && (count(array_diff($stored_terms, $terms)) == 0)) {
  4639. return false;
  4640. }
  4641. require_once 'xapian.php'; // TODO: Try catch every xapian use or make wrappers on API.
  4642. require_once api_get_path(LIBRARY_PATH).'search/xapian/XapianQuery.php';
  4643. $items_table = Database::get_course_table(TABLE_LP_ITEM);
  4644. // TODO: Make query secure agains XSS : use member attr instead of post var.
  4645. $lp_id = (int) $_POST['lp_id'];
  4646. $sql = "SELECT * FROM $items_table WHERE c_id = $course_id AND lp_id = $lp_id";
  4647. $result = Database::query($sql);
  4648. $di = new ChamiloIndexer();
  4649. while ($lp_item = Database::fetch_array($result)) {
  4650. // Get search_did.
  4651. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  4652. $sql = 'SELECT * FROM %s
  4653. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
  4654. LIMIT 1';
  4655. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp_id, $lp_item['id']);
  4656. //echo $sql; echo '<br>';
  4657. $res = Database::query($sql);
  4658. if (Database::num_rows($res) > 0) {
  4659. $se_ref = Database::fetch_array($res);
  4660. // Compare terms.
  4661. $doc = $di->get_document($se_ref['search_did']);
  4662. $xapian_terms = xapian_get_doc_terms($doc, $prefix);
  4663. $xterms = [];
  4664. foreach ($xapian_terms as $xapian_term) {
  4665. $xterms[] = substr($xapian_term['name'], 1);
  4666. }
  4667. $dterms = $terms;
  4668. $missing_terms = array_diff($dterms, $xterms);
  4669. $deprecated_terms = array_diff($xterms, $dterms);
  4670. // Save it to search engine.
  4671. foreach ($missing_terms as $term) {
  4672. $doc->add_term($prefix.$term, 1);
  4673. }
  4674. foreach ($deprecated_terms as $term) {
  4675. $doc->remove_term($prefix.$term);
  4676. }
  4677. $di->getDb()->replace_document((int) $se_ref['search_did'], $doc);
  4678. $di->getDb()->flush();
  4679. }
  4680. }
  4681. return true;
  4682. }
  4683. /**
  4684. * Sets the theme of the LP (local/remote) (and save).
  4685. *
  4686. * @param string $name Optional string giving the new theme of this learnpath
  4687. *
  4688. * @return bool Returns true if theme name is not empty
  4689. */
  4690. public function set_theme($name = '')
  4691. {
  4692. $this->theme = $name;
  4693. $table = Database::get_course_table(TABLE_LP_MAIN);
  4694. $lp_id = $this->get_id();
  4695. $sql = "UPDATE $table
  4696. SET theme = '".Database::escape_string($this->theme)."'
  4697. WHERE iid = $lp_id";
  4698. Database::query($sql);
  4699. return true;
  4700. }
  4701. /**
  4702. * Sets the image of an LP (and save).
  4703. *
  4704. * @param string $name Optional string giving the new image of this learnpath
  4705. *
  4706. * @return bool Returns true if theme name is not empty
  4707. */
  4708. public function set_preview_image($name = '')
  4709. {
  4710. $this->preview_image = $name;
  4711. $table = Database::get_course_table(TABLE_LP_MAIN);
  4712. $lp_id = $this->get_id();
  4713. $sql = "UPDATE $table SET
  4714. preview_image = '".Database::escape_string($this->preview_image)."'
  4715. WHERE iid = $lp_id";
  4716. Database::query($sql);
  4717. return true;
  4718. }
  4719. /**
  4720. * Sets the author of a LP (and save).
  4721. *
  4722. * @param string $name Optional string giving the new author of this learnpath
  4723. *
  4724. * @return bool Returns true if author's name is not empty
  4725. */
  4726. public function set_author($name = '')
  4727. {
  4728. $this->author = $name;
  4729. $table = Database::get_course_table(TABLE_LP_MAIN);
  4730. $lp_id = $this->get_id();
  4731. $sql = "UPDATE $table SET author = '".Database::escape_string($name)."'
  4732. WHERE iid = $lp_id";
  4733. Database::query($sql);
  4734. return true;
  4735. }
  4736. /**
  4737. * Sets the hide_toc_frame parameter of a LP (and save).
  4738. *
  4739. * @param int $hide 1 if frame is hidden 0 then else
  4740. *
  4741. * @return bool Returns true if author's name is not empty
  4742. */
  4743. public function set_hide_toc_frame($hide)
  4744. {
  4745. if (intval($hide) == $hide) {
  4746. $this->hide_toc_frame = $hide;
  4747. $table = Database::get_course_table(TABLE_LP_MAIN);
  4748. $lp_id = $this->get_id();
  4749. $sql = "UPDATE $table SET
  4750. hide_toc_frame = '".(int) $this->hide_toc_frame."'
  4751. WHERE iid = $lp_id";
  4752. Database::query($sql);
  4753. return true;
  4754. }
  4755. return false;
  4756. }
  4757. /**
  4758. * Sets the prerequisite of a LP (and save).
  4759. *
  4760. * @param int $prerequisite integer giving the new prerequisite of this learnpath
  4761. *
  4762. * @return bool returns true if prerequisite is not empty
  4763. */
  4764. public function set_prerequisite($prerequisite)
  4765. {
  4766. $this->prerequisite = (int) $prerequisite;
  4767. $table = Database::get_course_table(TABLE_LP_MAIN);
  4768. $lp_id = $this->get_id();
  4769. $sql = "UPDATE $table SET prerequisite = '".$this->prerequisite."'
  4770. WHERE iid = $lp_id";
  4771. Database::query($sql);
  4772. return true;
  4773. }
  4774. /**
  4775. * Sets the location/proximity of the LP (local/remote) (and save).
  4776. *
  4777. * @param string $name Optional string giving the new location of this learnpath
  4778. *
  4779. * @return bool True on success / False on error
  4780. */
  4781. public function set_proximity($name = '')
  4782. {
  4783. if (empty($name)) {
  4784. return false;
  4785. }
  4786. $this->proximity = $name;
  4787. $table = Database::get_course_table(TABLE_LP_MAIN);
  4788. $lp_id = $this->get_id();
  4789. $sql = "UPDATE $table SET
  4790. content_local = '".Database::escape_string($name)."'
  4791. WHERE iid = $lp_id";
  4792. Database::query($sql);
  4793. return true;
  4794. }
  4795. /**
  4796. * Sets the previous item ID to a given ID. Generally, this should be set to the previous 'current' item.
  4797. *
  4798. * @param int $id DB ID of the item
  4799. */
  4800. public function set_previous_item($id)
  4801. {
  4802. if ($this->debug > 0) {
  4803. error_log('In learnpath::set_previous_item()', 0);
  4804. }
  4805. $this->last = $id;
  4806. }
  4807. /**
  4808. * Sets use_max_score.
  4809. *
  4810. * @param int $use_max_score Optional string giving the new location of this learnpath
  4811. *
  4812. * @return bool True on success / False on error
  4813. */
  4814. public function set_use_max_score($use_max_score = 1)
  4815. {
  4816. $use_max_score = (int) $use_max_score;
  4817. $this->use_max_score = $use_max_score;
  4818. $table = Database::get_course_table(TABLE_LP_MAIN);
  4819. $lp_id = $this->get_id();
  4820. $sql = "UPDATE $table SET
  4821. use_max_score = '".$this->use_max_score."'
  4822. WHERE iid = $lp_id";
  4823. Database::query($sql);
  4824. return true;
  4825. }
  4826. /**
  4827. * Sets and saves the expired_on date.
  4828. *
  4829. * @param string $expired_on Optional string giving the new author of this learnpath
  4830. *
  4831. * @throws \Doctrine\ORM\OptimisticLockException
  4832. *
  4833. * @return bool Returns true if author's name is not empty
  4834. */
  4835. public function set_expired_on($expired_on)
  4836. {
  4837. $em = Database::getManager();
  4838. /** @var CLp $lp */
  4839. $lp = $em
  4840. ->getRepository('ChamiloCourseBundle:CLp')
  4841. ->findOneBy(
  4842. [
  4843. 'iid' => $this->get_id(),
  4844. ]
  4845. );
  4846. if (!$lp) {
  4847. return false;
  4848. }
  4849. $this->expired_on = !empty($expired_on) ? api_get_utc_datetime($expired_on, false, true) : null;
  4850. $lp->setExpiredOn($this->expired_on);
  4851. $em->persist($lp);
  4852. $em->flush();
  4853. return true;
  4854. }
  4855. /**
  4856. * Sets and saves the publicated_on date.
  4857. *
  4858. * @param string $publicated_on Optional string giving the new author of this learnpath
  4859. *
  4860. * @throws \Doctrine\ORM\OptimisticLockException
  4861. *
  4862. * @return bool Returns true if author's name is not empty
  4863. */
  4864. public function set_publicated_on($publicated_on)
  4865. {
  4866. $em = Database::getManager();
  4867. /** @var CLp $lp */
  4868. $lp = $em
  4869. ->getRepository('ChamiloCourseBundle:CLp')
  4870. ->findOneBy(
  4871. [
  4872. 'iid' => $this->get_id(),
  4873. ]
  4874. );
  4875. if (!$lp) {
  4876. return false;
  4877. }
  4878. $this->publicated_on = !empty($publicated_on) ? api_get_utc_datetime($publicated_on, false, true) : null;
  4879. $lp->setPublicatedOn($this->publicated_on);
  4880. $em->persist($lp);
  4881. $em->flush();
  4882. return true;
  4883. }
  4884. /**
  4885. * Sets and saves the expired_on date.
  4886. *
  4887. * @return bool Returns true if author's name is not empty
  4888. */
  4889. public function set_modified_on()
  4890. {
  4891. $this->modified_on = api_get_utc_datetime();
  4892. $table = Database::get_course_table(TABLE_LP_MAIN);
  4893. $lp_id = $this->get_id();
  4894. $sql = "UPDATE $table SET modified_on = '".$this->modified_on."'
  4895. WHERE iid = $lp_id";
  4896. Database::query($sql);
  4897. return true;
  4898. }
  4899. /**
  4900. * Sets the object's error message.
  4901. *
  4902. * @param string $error Error message. If empty, reinits the error string
  4903. */
  4904. public function set_error_msg($error = '')
  4905. {
  4906. if ($this->debug > 0) {
  4907. error_log('In learnpath::set_error_msg()', 0);
  4908. }
  4909. if (empty($error)) {
  4910. $this->error = '';
  4911. } else {
  4912. $this->error .= $error;
  4913. }
  4914. }
  4915. /**
  4916. * Launches the current item if not 'sco'
  4917. * (starts timer and make sure there is a record ready in the DB).
  4918. *
  4919. * @param bool $allow_new_attempt Whether to allow a new attempt or not
  4920. *
  4921. * @return bool
  4922. */
  4923. public function start_current_item($allow_new_attempt = false)
  4924. {
  4925. $debug = $this->debug;
  4926. if ($debug) {
  4927. error_log('In learnpath::start_current_item()');
  4928. error_log('current: '.$this->current);
  4929. }
  4930. if ($this->current != 0 && isset($this->items[$this->current]) && is_object($this->items[$this->current])) {
  4931. $type = $this->get_type();
  4932. $item_type = $this->items[$this->current]->get_type();
  4933. if (($type == 2 && $item_type != 'sco') ||
  4934. ($type == 3 && $item_type != 'au') ||
  4935. ($type == 1 && $item_type != TOOL_QUIZ && $item_type != TOOL_HOTPOTATOES)
  4936. ) {
  4937. if ($debug) {
  4938. error_log('item type: '.$item_type);
  4939. error_log('lp type: '.$type);
  4940. }
  4941. $this->items[$this->current]->open($allow_new_attempt);
  4942. $this->autocomplete_parents($this->current);
  4943. $prereq_check = $this->prerequisites_match($this->current);
  4944. if ($debug) {
  4945. error_log('start_current_item will save item with prereq: '.$prereq_check);
  4946. }
  4947. $this->items[$this->current]->save(false, $prereq_check);
  4948. }
  4949. // If sco, then it is supposed to have been updated by some other call.
  4950. if ($item_type == 'sco') {
  4951. $this->items[$this->current]->restart();
  4952. }
  4953. }
  4954. if ($debug) {
  4955. error_log('lp_view_session_id');
  4956. error_log($this->lp_view_session_id);
  4957. error_log('api session id');
  4958. error_log(api_get_session_id());
  4959. error_log('End of learnpath::start_current_item()');
  4960. }
  4961. return true;
  4962. }
  4963. /**
  4964. * Stops the processing and counters for the old item (as held in $this->last).
  4965. *
  4966. * @return bool True/False
  4967. */
  4968. public function stop_previous_item()
  4969. {
  4970. $debug = $this->debug;
  4971. if ($debug) {
  4972. error_log('In learnpath::stop_previous_item()', 0);
  4973. }
  4974. if ($this->last != 0 && $this->last != $this->current &&
  4975. isset($this->items[$this->last]) && is_object($this->items[$this->last])
  4976. ) {
  4977. if ($debug) {
  4978. error_log('In learnpath::stop_previous_item() - '.$this->last.' is object');
  4979. }
  4980. switch ($this->get_type()) {
  4981. case '3':
  4982. if ($this->items[$this->last]->get_type() != 'au') {
  4983. if ($debug) {
  4984. error_log('In learnpath::stop_previous_item() - '.$this->last.' in lp_type 3 is <> au');
  4985. }
  4986. $this->items[$this->last]->close();
  4987. } else {
  4988. if ($debug) {
  4989. error_log('In learnpath::stop_previous_item() - Item is an AU, saving is managed by AICC signals');
  4990. }
  4991. }
  4992. break;
  4993. case '2':
  4994. if ($this->items[$this->last]->get_type() != 'sco') {
  4995. if ($debug) {
  4996. error_log('In learnpath::stop_previous_item() - '.$this->last.' in lp_type 2 is <> sco');
  4997. }
  4998. $this->items[$this->last]->close();
  4999. } else {
  5000. if ($debug) {
  5001. error_log('In learnpath::stop_previous_item() - Item is a SCO, saving is managed by SCO signals');
  5002. }
  5003. }
  5004. break;
  5005. case '1':
  5006. default:
  5007. if ($debug) {
  5008. error_log('In learnpath::stop_previous_item() - '.$this->last.' in lp_type 1 is asset');
  5009. }
  5010. $this->items[$this->last]->close();
  5011. break;
  5012. }
  5013. } else {
  5014. if ($debug) {
  5015. error_log('In learnpath::stop_previous_item() - No previous element found, ignoring...');
  5016. }
  5017. return false;
  5018. }
  5019. return true;
  5020. }
  5021. /**
  5022. * Updates the default view mode from fullscreen to embedded and inversely.
  5023. *
  5024. * @return string The current default view mode ('fullscreen' or 'embedded')
  5025. */
  5026. public function update_default_view_mode()
  5027. {
  5028. $table = Database::get_course_table(TABLE_LP_MAIN);
  5029. $sql = "SELECT * FROM $table
  5030. WHERE iid = ".$this->get_id();
  5031. $res = Database::query($sql);
  5032. if (Database::num_rows($res) > 0) {
  5033. $row = Database::fetch_array($res);
  5034. $default_view_mode = $row['default_view_mod'];
  5035. $view_mode = $default_view_mode;
  5036. switch ($default_view_mode) {
  5037. case 'fullscreen': // default with popup
  5038. $view_mode = 'embedded';
  5039. break;
  5040. case 'embedded': // default view with left menu
  5041. $view_mode = 'embedframe';
  5042. break;
  5043. case 'embedframe': //folded menu
  5044. $view_mode = 'impress';
  5045. break;
  5046. case 'impress':
  5047. $view_mode = 'fullscreen';
  5048. break;
  5049. }
  5050. $sql = "UPDATE $table SET default_view_mod = '$view_mode'
  5051. WHERE iid = ".$this->get_id();
  5052. Database::query($sql);
  5053. $this->mode = $view_mode;
  5054. return $view_mode;
  5055. }
  5056. return -1;
  5057. }
  5058. /**
  5059. * Updates the default behaviour about auto-commiting SCORM updates.
  5060. *
  5061. * @return bool True if auto-commit has been set to 'on', false otherwise
  5062. */
  5063. public function update_default_scorm_commit()
  5064. {
  5065. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5066. $sql = "SELECT * FROM $lp_table
  5067. WHERE iid = ".$this->get_id();
  5068. $res = Database::query($sql);
  5069. if (Database::num_rows($res) > 0) {
  5070. $row = Database::fetch_array($res);
  5071. $force = $row['force_commit'];
  5072. if ($force == 1) {
  5073. $force = 0;
  5074. $force_return = false;
  5075. } elseif ($force == 0) {
  5076. $force = 1;
  5077. $force_return = true;
  5078. }
  5079. $sql = "UPDATE $lp_table SET force_commit = $force
  5080. WHERE iid = ".$this->get_id();
  5081. Database::query($sql);
  5082. $this->force_commit = $force_return;
  5083. return $force_return;
  5084. }
  5085. return -1;
  5086. }
  5087. /**
  5088. * Updates the order of learning paths (goes through all of them by order and fills the gaps).
  5089. *
  5090. * @return bool True on success, false on failure
  5091. */
  5092. public function update_display_order()
  5093. {
  5094. $course_id = api_get_course_int_id();
  5095. $table = Database::get_course_table(TABLE_LP_MAIN);
  5096. $sql = "SELECT * FROM $table
  5097. WHERE c_id = $course_id
  5098. ORDER BY display_order";
  5099. $res = Database::query($sql);
  5100. if ($res === false) {
  5101. return false;
  5102. }
  5103. $num = Database::num_rows($res);
  5104. // First check the order is correct, globally (might be wrong because
  5105. // of versions < 1.8.4).
  5106. if ($num > 0) {
  5107. $i = 1;
  5108. while ($row = Database::fetch_array($res)) {
  5109. if ($row['display_order'] != $i) {
  5110. // If we find a gap in the order, we need to fix it.
  5111. $sql = "UPDATE $table SET display_order = $i
  5112. WHERE iid = ".$row['iid'];
  5113. Database::query($sql);
  5114. }
  5115. $i++;
  5116. }
  5117. }
  5118. return true;
  5119. }
  5120. /**
  5121. * Updates the "prevent_reinit" value that enables control on reinitialising items on second view.
  5122. *
  5123. * @return bool True if prevent_reinit has been set to 'on', false otherwise (or 1 or 0 in this case)
  5124. */
  5125. public function update_reinit()
  5126. {
  5127. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5128. $sql = "SELECT * FROM $lp_table
  5129. WHERE iid = ".$this->get_id();
  5130. $res = Database::query($sql);
  5131. if (Database::num_rows($res) > 0) {
  5132. $row = Database::fetch_array($res);
  5133. $force = $row['prevent_reinit'];
  5134. if ($force == 1) {
  5135. $force = 0;
  5136. } elseif ($force == 0) {
  5137. $force = 1;
  5138. }
  5139. $sql = "UPDATE $lp_table SET prevent_reinit = $force
  5140. WHERE iid = ".$this->get_id();
  5141. Database::query($sql);
  5142. $this->prevent_reinit = $force;
  5143. return $force;
  5144. }
  5145. return -1;
  5146. }
  5147. /**
  5148. * Determine the attempt_mode thanks to prevent_reinit and seriousgame_mode db flag.
  5149. *
  5150. * @return string 'single', 'multi' or 'seriousgame'
  5151. *
  5152. * @author ndiechburg <noel@cblue.be>
  5153. */
  5154. public function get_attempt_mode()
  5155. {
  5156. //Set default value for seriousgame_mode
  5157. if (!isset($this->seriousgame_mode)) {
  5158. $this->seriousgame_mode = 0;
  5159. }
  5160. // Set default value for prevent_reinit
  5161. if (!isset($this->prevent_reinit)) {
  5162. $this->prevent_reinit = 1;
  5163. }
  5164. if ($this->seriousgame_mode == 1 && $this->prevent_reinit == 1) {
  5165. return 'seriousgame';
  5166. }
  5167. if ($this->seriousgame_mode == 0 && $this->prevent_reinit == 1) {
  5168. return 'single';
  5169. }
  5170. if ($this->seriousgame_mode == 0 && $this->prevent_reinit == 0) {
  5171. return 'multiple';
  5172. }
  5173. return 'single';
  5174. }
  5175. /**
  5176. * Register the attempt mode into db thanks to flags prevent_reinit and seriousgame_mode flags.
  5177. *
  5178. * @param string 'seriousgame', 'single' or 'multiple'
  5179. *
  5180. * @return bool
  5181. *
  5182. * @author ndiechburg <noel@cblue.be>
  5183. */
  5184. public function set_attempt_mode($mode)
  5185. {
  5186. switch ($mode) {
  5187. case 'seriousgame':
  5188. $sg_mode = 1;
  5189. $prevent_reinit = 1;
  5190. break;
  5191. case 'single':
  5192. $sg_mode = 0;
  5193. $prevent_reinit = 1;
  5194. break;
  5195. case 'multiple':
  5196. $sg_mode = 0;
  5197. $prevent_reinit = 0;
  5198. break;
  5199. default:
  5200. $sg_mode = 0;
  5201. $prevent_reinit = 0;
  5202. break;
  5203. }
  5204. $this->prevent_reinit = $prevent_reinit;
  5205. $this->seriousgame_mode = $sg_mode;
  5206. $table = Database::get_course_table(TABLE_LP_MAIN);
  5207. $sql = "UPDATE $table SET
  5208. prevent_reinit = $prevent_reinit ,
  5209. seriousgame_mode = $sg_mode
  5210. WHERE iid = ".$this->get_id();
  5211. $res = Database::query($sql);
  5212. if ($res) {
  5213. return true;
  5214. } else {
  5215. return false;
  5216. }
  5217. }
  5218. /**
  5219. * Switch between multiple attempt, single attempt or serious_game mode (only for scorm).
  5220. *
  5221. * @author ndiechburg <noel@cblue.be>
  5222. */
  5223. public function switch_attempt_mode()
  5224. {
  5225. $mode = $this->get_attempt_mode();
  5226. switch ($mode) {
  5227. case 'single':
  5228. $next_mode = 'multiple';
  5229. break;
  5230. case 'multiple':
  5231. $next_mode = 'seriousgame';
  5232. break;
  5233. case 'seriousgame':
  5234. default:
  5235. $next_mode = 'single';
  5236. break;
  5237. }
  5238. $this->set_attempt_mode($next_mode);
  5239. }
  5240. /**
  5241. * Switch the lp in ktm mode. This is a special scorm mode with unique attempt
  5242. * but possibility to do again a completed item.
  5243. *
  5244. * @return bool true if seriousgame_mode has been set to 1, false otherwise
  5245. *
  5246. * @author ndiechburg <noel@cblue.be>
  5247. */
  5248. public function set_seriousgame_mode()
  5249. {
  5250. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5251. $sql = "SELECT * FROM $lp_table
  5252. WHERE iid = ".$this->get_id();
  5253. $res = Database::query($sql);
  5254. if (Database::num_rows($res) > 0) {
  5255. $row = Database::fetch_array($res);
  5256. $force = $row['seriousgame_mode'];
  5257. if ($force == 1) {
  5258. $force = 0;
  5259. } elseif ($force == 0) {
  5260. $force = 1;
  5261. }
  5262. $sql = "UPDATE $lp_table SET seriousgame_mode = $force
  5263. WHERE iid = ".$this->get_id();
  5264. Database::query($sql);
  5265. $this->seriousgame_mode = $force;
  5266. return $force;
  5267. }
  5268. return -1;
  5269. }
  5270. /**
  5271. * Updates the "scorm_debug" value that shows or hide the debug window.
  5272. *
  5273. * @return bool True if scorm_debug has been set to 'on', false otherwise (or 1 or 0 in this case)
  5274. */
  5275. public function update_scorm_debug()
  5276. {
  5277. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5278. $sql = "SELECT * FROM $lp_table
  5279. WHERE iid = ".$this->get_id();
  5280. $res = Database::query($sql);
  5281. if (Database::num_rows($res) > 0) {
  5282. $row = Database::fetch_array($res);
  5283. $force = $row['debug'];
  5284. if ($force == 1) {
  5285. $force = 0;
  5286. } elseif ($force == 0) {
  5287. $force = 1;
  5288. }
  5289. $sql = "UPDATE $lp_table SET debug = $force
  5290. WHERE iid = ".$this->get_id();
  5291. Database::query($sql);
  5292. $this->scorm_debug = $force;
  5293. return $force;
  5294. }
  5295. return -1;
  5296. }
  5297. /**
  5298. * Function that makes a call to the function sort_tree_array and create_tree_array.
  5299. *
  5300. * @author Kevin Van Den Haute
  5301. *
  5302. * @param array
  5303. */
  5304. public function tree_array($array)
  5305. {
  5306. $array = $this->sort_tree_array($array);
  5307. $this->create_tree_array($array);
  5308. }
  5309. /**
  5310. * Creates an array with the elements of the learning path tree in it.
  5311. *
  5312. * @author Kevin Van Den Haute
  5313. *
  5314. * @param array $array
  5315. * @param int $parent
  5316. * @param int $depth
  5317. * @param array $tmp
  5318. */
  5319. public function create_tree_array($array, $parent = 0, $depth = -1, $tmp = [])
  5320. {
  5321. if (is_array($array)) {
  5322. for ($i = 0; $i < count($array); $i++) {
  5323. if ($array[$i]['parent_item_id'] == $parent) {
  5324. if (!in_array($array[$i]['parent_item_id'], $tmp)) {
  5325. $tmp[] = $array[$i]['parent_item_id'];
  5326. $depth++;
  5327. }
  5328. $preq = (empty($array[$i]['prerequisite']) ? '' : $array[$i]['prerequisite']);
  5329. $audio = isset($array[$i]['audio']) ? $array[$i]['audio'] : null;
  5330. $path = isset($array[$i]['path']) ? $array[$i]['path'] : null;
  5331. $prerequisiteMinScore = isset($array[$i]['prerequisite_min_score']) ? $array[$i]['prerequisite_min_score'] : null;
  5332. $prerequisiteMaxScore = isset($array[$i]['prerequisite_max_score']) ? $array[$i]['prerequisite_max_score'] : null;
  5333. $ref = isset($array[$i]['ref']) ? $array[$i]['ref'] : '';
  5334. $this->arrMenu[] = [
  5335. 'id' => $array[$i]['id'],
  5336. 'ref' => $ref,
  5337. 'item_type' => $array[$i]['item_type'],
  5338. 'title' => $array[$i]['title'],
  5339. 'title_raw' => $array[$i]['title_raw'],
  5340. 'path' => $path,
  5341. 'description' => $array[$i]['description'],
  5342. 'parent_item_id' => $array[$i]['parent_item_id'],
  5343. 'previous_item_id' => $array[$i]['previous_item_id'],
  5344. 'next_item_id' => $array[$i]['next_item_id'],
  5345. 'min_score' => $array[$i]['min_score'],
  5346. 'max_score' => $array[$i]['max_score'],
  5347. 'mastery_score' => $array[$i]['mastery_score'],
  5348. 'display_order' => $array[$i]['display_order'],
  5349. 'prerequisite' => $preq,
  5350. 'depth' => $depth,
  5351. 'audio' => $audio,
  5352. 'prerequisite_min_score' => $prerequisiteMinScore,
  5353. 'prerequisite_max_score' => $prerequisiteMaxScore,
  5354. ];
  5355. $this->create_tree_array($array, $array[$i]['id'], $depth, $tmp);
  5356. }
  5357. }
  5358. }
  5359. }
  5360. /**
  5361. * Sorts a multi dimensional array by parent id and display order.
  5362. *
  5363. * @author Kevin Van Den Haute
  5364. *
  5365. * @param array $array (array with al the learning path items in it)
  5366. *
  5367. * @return array
  5368. */
  5369. public function sort_tree_array($array)
  5370. {
  5371. foreach ($array as $key => $row) {
  5372. $parent[$key] = $row['parent_item_id'];
  5373. $position[$key] = $row['display_order'];
  5374. }
  5375. if (count($array) > 0) {
  5376. array_multisort($parent, SORT_ASC, $position, SORT_ASC, $array);
  5377. }
  5378. return $array;
  5379. }
  5380. /**
  5381. * Function that creates a html list of learning path items so that we can add audio files to them.
  5382. *
  5383. * @author Kevin Van Den Haute
  5384. *
  5385. * @return string
  5386. */
  5387. public function overview()
  5388. {
  5389. $return = '';
  5390. $update_audio = isset($_GET['updateaudio']) ? $_GET['updateaudio'] : null;
  5391. // we need to start a form when we want to update all the mp3 files
  5392. if ($update_audio == 'true') {
  5393. $return .= '<form action="'.api_get_self().'?'.api_get_cidreq().'&updateaudio='.Security::remove_XSS($_GET['updateaudio']).'&action='.Security::remove_XSS($_GET['action']).'&lp_id='.$_SESSION['oLP']->lp_id.'" method="post" enctype="multipart/form-data" name="updatemp3" id="updatemp3">';
  5394. }
  5395. $return .= '<div id="message"></div>';
  5396. if (count($this->items) == 0) {
  5397. $return .= Display::return_message(get_lang('YouShouldAddItemsBeforeAttachAudio'), 'normal');
  5398. } else {
  5399. $return_audio = '<table class="data_table">';
  5400. $return_audio .= '<tr>';
  5401. $return_audio .= '<th width="40%">'.get_lang('Title').'</th>';
  5402. $return_audio .= '<th>'.get_lang('Audio').'</th>';
  5403. $return_audio .= '</tr>';
  5404. if ($update_audio != 'true') {
  5405. $return .= '<div class="col-md-12">';
  5406. $return .= self::return_new_tree($update_audio);
  5407. $return .= '</div>';
  5408. $return .= Display::div(
  5409. Display::url(get_lang('Save'), '#', ['id' => 'listSubmit', 'class' => 'btn btn-primary']),
  5410. ['style' => 'float:left; margin-top:15px;width:100%']
  5411. );
  5412. } else {
  5413. $return_audio .= self::return_new_tree($update_audio);
  5414. $return .= $return_audio.'</table>';
  5415. }
  5416. // We need to close the form when we are updating the mp3 files.
  5417. if ($update_audio == 'true') {
  5418. $return .= '<div class="footer-audio">';
  5419. $return .= Display::button(
  5420. 'save_audio',
  5421. '<em class="fa fa-file-audio-o"></em> '.get_lang('SaveAudioAndOrganization'),
  5422. ['class' => 'btn btn-primary', 'type' => 'submit']
  5423. );
  5424. $return .= '</div>';
  5425. }
  5426. }
  5427. // We need to close the form when we are updating the mp3 files.
  5428. if ($update_audio == 'true' && isset($this->arrMenu) && count($this->arrMenu) != 0) {
  5429. $return .= '</form>';
  5430. }
  5431. return $return;
  5432. }
  5433. /**
  5434. * @param string $update_audio
  5435. *
  5436. * @return array
  5437. */
  5438. public function processBuildMenuElements($update_audio = 'false')
  5439. {
  5440. $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
  5441. $arrLP = $this->getItemsForForm();
  5442. $this->tree_array($arrLP);
  5443. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  5444. unset($this->arrMenu);
  5445. $default_data = null;
  5446. $default_content = null;
  5447. $elements = [];
  5448. $return_audio = null;
  5449. $iconPath = api_get_path(SYS_CODE_PATH).'img/';
  5450. $mainUrl = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq();
  5451. $countItems = count($arrLP);
  5452. $upIcon = Display::return_icon(
  5453. 'up.png',
  5454. get_lang('Up'),
  5455. [],
  5456. ICON_SIZE_TINY
  5457. );
  5458. $disableUpIcon = Display::return_icon(
  5459. 'up_na.png',
  5460. get_lang('Up'),
  5461. [],
  5462. ICON_SIZE_TINY
  5463. );
  5464. $downIcon = Display::return_icon(
  5465. 'down.png',
  5466. get_lang('Down'),
  5467. [],
  5468. ICON_SIZE_TINY
  5469. );
  5470. $disableDownIcon = Display::return_icon(
  5471. 'down_na.png',
  5472. get_lang('Down'),
  5473. [],
  5474. ICON_SIZE_TINY
  5475. );
  5476. $show = api_get_configuration_value('show_full_lp_item_title_in_edition');
  5477. $pluginCalendar = api_get_plugin_setting('learning_calendar', 'enabled') === 'true';
  5478. $plugin = null;
  5479. if ($pluginCalendar) {
  5480. $plugin = LearningCalendarPlugin::create();
  5481. }
  5482. for ($i = 0; $i < $countItems; $i++) {
  5483. $parent_id = $arrLP[$i]['parent_item_id'];
  5484. $title = $arrLP[$i]['title'];
  5485. $title_cut = $arrLP[$i]['title_raw'];
  5486. if ($show === false) {
  5487. $title_cut = cut($arrLP[$i]['title'], self::MAX_LP_ITEM_TITLE_LENGTH);
  5488. }
  5489. // Link for the documents
  5490. if ($arrLP[$i]['item_type'] === 'document' || $arrLP[$i]['item_type'] == TOOL_READOUT_TEXT) {
  5491. $url = $mainUrl.'&action=view_item&mode=preview_document&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5492. $title_cut = Display::url(
  5493. $title_cut,
  5494. $url,
  5495. [
  5496. 'class' => 'ajax moved',
  5497. 'data-title' => $title,
  5498. 'title' => $title,
  5499. ]
  5500. );
  5501. }
  5502. // Detect if type is FINAL_ITEM to set path_id to SESSION
  5503. if ($arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM) {
  5504. Session::write('pathItem', $arrLP[$i]['path']);
  5505. }
  5506. $oddClass = 'row_even';
  5507. if (($i % 2) == 0) {
  5508. $oddClass = 'row_odd';
  5509. }
  5510. $return_audio .= '<tr id ="lp_item_'.$arrLP[$i]['id'].'" class="'.$oddClass.'">';
  5511. $icon_name = str_replace(' ', '', $arrLP[$i]['item_type']);
  5512. if (file_exists($iconPath.'lp_'.$icon_name.'.png')) {
  5513. $icon = Display::return_icon('lp_'.$icon_name.'.png');
  5514. } else {
  5515. if (file_exists($iconPath.'lp_'.$icon_name.'.gif')) {
  5516. $icon = Display::return_icon('lp_'.$icon_name.'.gif');
  5517. } else {
  5518. if ($arrLP[$i]['item_type'] === TOOL_LP_FINAL_ITEM) {
  5519. $icon = Display::return_icon('certificate.png');
  5520. } else {
  5521. $icon = Display::return_icon('folder_document.gif');
  5522. }
  5523. }
  5524. }
  5525. // The audio column.
  5526. $return_audio .= '<td align="left" style="padding-left:10px;">';
  5527. $audio = '';
  5528. if (!$update_audio || $update_audio != 'true') {
  5529. if (empty($arrLP[$i]['audio'])) {
  5530. $audio .= '';
  5531. }
  5532. } else {
  5533. $types = self::getChapterTypes();
  5534. if (!in_array($arrLP[$i]['item_type'], $types)) {
  5535. $audio .= '<input type="file" name="mp3file'.$arrLP[$i]['id'].'" id="mp3file" />';
  5536. if (!empty($arrLP[$i]['audio'])) {
  5537. $audio .= '<br />'.Security::remove_XSS($arrLP[$i]['audio']).'<br />
  5538. <input type="checkbox" name="removemp3'.$arrLP[$i]['id'].'" id="checkbox'.$arrLP[$i]['id'].'" />'.get_lang('RemoveAudio');
  5539. }
  5540. }
  5541. }
  5542. $return_audio .= Display::span($icon.' '.$title).
  5543. Display::tag(
  5544. 'td',
  5545. $audio,
  5546. ['style' => '']
  5547. );
  5548. $return_audio .= '</td>';
  5549. $move_icon = '';
  5550. $move_item_icon = '';
  5551. $edit_icon = '';
  5552. $delete_icon = '';
  5553. $audio_icon = '';
  5554. $prerequisities_icon = '';
  5555. $forumIcon = '';
  5556. $previewIcon = '';
  5557. $pluginCalendarIcon = '';
  5558. $orderIcons = '';
  5559. $pluginUrl = api_get_path(WEB_PLUGIN_PATH).'learning_calendar/start.php?';
  5560. if ($is_allowed_to_edit) {
  5561. if (!$update_audio || $update_audio != 'true') {
  5562. if ($arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM) {
  5563. $move_icon .= '<a class="moved" href="#">';
  5564. $move_icon .= Display::return_icon(
  5565. 'move_everywhere.png',
  5566. get_lang('Move'),
  5567. [],
  5568. ICON_SIZE_TINY
  5569. );
  5570. $move_icon .= '</a>';
  5571. }
  5572. }
  5573. // No edit for this item types
  5574. if (!in_array($arrLP[$i]['item_type'], ['sco', 'asset', 'final_item'])) {
  5575. if ($arrLP[$i]['item_type'] != 'dir') {
  5576. $edit_icon .= '<a href="'.$mainUrl.'&action=edit_item&view=build&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'&path_item='.$arrLP[$i]['path'].'" class="btn btn-default">';
  5577. $edit_icon .= Display::return_icon(
  5578. 'edit.png',
  5579. get_lang('LearnpathEditModule'),
  5580. [],
  5581. ICON_SIZE_TINY
  5582. );
  5583. $edit_icon .= '</a>';
  5584. if (!in_array($arrLP[$i]['item_type'], ['forum', 'thread'])) {
  5585. $forumThread = null;
  5586. if (isset($this->items[$arrLP[$i]['id']])) {
  5587. $forumThread = $this->items[$arrLP[$i]['id']]->getForumThread(
  5588. $this->course_int_id,
  5589. $this->lp_session_id
  5590. );
  5591. }
  5592. if ($forumThread) {
  5593. $forumIconUrl = $mainUrl.'&'.http_build_query([
  5594. 'action' => 'dissociate_forum',
  5595. 'id' => $arrLP[$i]['id'],
  5596. 'lp_id' => $this->lp_id,
  5597. ]);
  5598. $forumIcon = Display::url(
  5599. Display::return_icon(
  5600. 'forum.png',
  5601. get_lang('DissociateForumToLPItem'),
  5602. [],
  5603. ICON_SIZE_TINY
  5604. ),
  5605. $forumIconUrl,
  5606. ['class' => 'btn btn-default lp-btn-dissociate-forum']
  5607. );
  5608. } else {
  5609. $forumIconUrl = $mainUrl.'&'.http_build_query([
  5610. 'action' => 'create_forum',
  5611. 'id' => $arrLP[$i]['id'],
  5612. 'lp_id' => $this->lp_id,
  5613. ]);
  5614. $forumIcon = Display::url(
  5615. Display::return_icon(
  5616. 'forum.png',
  5617. get_lang('AssociateForumToLPItem'),
  5618. [],
  5619. ICON_SIZE_TINY
  5620. ),
  5621. $forumIconUrl,
  5622. ['class' => 'btn btn-default lp-btn-associate-forum']
  5623. );
  5624. }
  5625. }
  5626. } else {
  5627. $edit_icon .= '<a href="'.$mainUrl.'&action=edit_item&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'&path_item='.$arrLP[$i]['path'].'" class="btn btn-default">';
  5628. $edit_icon .= Display::return_icon(
  5629. 'edit.png',
  5630. get_lang('LearnpathEditModule'),
  5631. [],
  5632. ICON_SIZE_TINY
  5633. );
  5634. $edit_icon .= '</a>';
  5635. }
  5636. } else {
  5637. if ($arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM) {
  5638. $edit_icon .= '<a href="'.$mainUrl.'&action=edit_item&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'" class="btn btn-default">';
  5639. $edit_icon .= Display::return_icon(
  5640. 'edit.png',
  5641. get_lang('Edit'),
  5642. [],
  5643. ICON_SIZE_TINY
  5644. );
  5645. $edit_icon .= '</a>';
  5646. }
  5647. }
  5648. if ($pluginCalendar) {
  5649. $pluginLink = $pluginUrl.
  5650. '&action=toggle_visibility&lp_item_id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5651. $iconCalendar = Display::return_icon('agenda_na.png', get_lang('OneDay'), [], ICON_SIZE_TINY);
  5652. $itemInfo = $plugin->getItemVisibility($arrLP[$i]['id']);
  5653. if ($itemInfo && $itemInfo['value'] == 1) {
  5654. $iconCalendar = Display::return_icon('agenda.png', get_lang('OneDay'), [], ICON_SIZE_TINY);
  5655. }
  5656. $pluginCalendarIcon = Display::url(
  5657. $iconCalendar,
  5658. $pluginLink,
  5659. ['class' => 'btn btn-default']
  5660. );
  5661. }
  5662. if ($arrLP[$i]['item_type'] != 'final_item') {
  5663. $orderIcons = Display::url(
  5664. $upIcon,
  5665. 'javascript:void(0)',
  5666. ['class' => 'btn btn-default order_items', 'data-dir' => 'up', 'data-id' => $arrLP[$i]['id']]
  5667. );
  5668. $orderIcons .= Display::url(
  5669. $downIcon,
  5670. 'javascript:void(0)',
  5671. ['class' => 'btn btn-default order_items', 'data-dir' => 'down', 'data-id' => $arrLP[$i]['id']]
  5672. );
  5673. }
  5674. $delete_icon .= ' <a
  5675. href="'.$mainUrl.'&action=delete_item&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'"
  5676. onclick="return confirmation(\''.addslashes($title).'\');"
  5677. class="btn btn-default">';
  5678. $delete_icon .= Display::return_icon(
  5679. 'delete.png',
  5680. get_lang('LearnpathDeleteModule'),
  5681. [],
  5682. ICON_SIZE_TINY
  5683. );
  5684. $delete_icon .= '</a>';
  5685. $url = $mainUrl.'&view=build&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5686. $previewImage = Display::return_icon(
  5687. 'preview_view.png',
  5688. get_lang('Preview'),
  5689. [],
  5690. ICON_SIZE_TINY
  5691. );
  5692. switch ($arrLP[$i]['item_type']) {
  5693. case TOOL_DOCUMENT:
  5694. case TOOL_LP_FINAL_ITEM:
  5695. case TOOL_READOUT_TEXT:
  5696. $urlPreviewLink = $mainUrl.'&action=view_item&mode=preview_document&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5697. $previewIcon = Display::url(
  5698. $previewImage,
  5699. $urlPreviewLink,
  5700. [
  5701. 'target' => '_blank',
  5702. 'class' => 'btn btn-default',
  5703. 'data-title' => $arrLP[$i]['title'],
  5704. 'title' => $arrLP[$i]['title'],
  5705. ]
  5706. );
  5707. break;
  5708. case TOOL_THREAD:
  5709. case TOOL_FORUM:
  5710. case TOOL_QUIZ:
  5711. case TOOL_STUDENTPUBLICATION:
  5712. case TOOL_LP_FINAL_ITEM:
  5713. case TOOL_LINK:
  5714. $class = 'btn btn-default';
  5715. $target = '_blank';
  5716. $link = self::rl_get_resource_link_for_learnpath(
  5717. $this->course_int_id,
  5718. $this->lp_id,
  5719. $arrLP[$i]['id'],
  5720. 0
  5721. );
  5722. $previewIcon = Display::url(
  5723. $previewImage,
  5724. $link,
  5725. [
  5726. 'class' => $class,
  5727. 'data-title' => $arrLP[$i]['title'],
  5728. 'title' => $arrLP[$i]['title'],
  5729. 'target' => $target,
  5730. ]
  5731. );
  5732. break;
  5733. default:
  5734. $previewIcon = Display::url(
  5735. $previewImage,
  5736. $url.'&action=view_item',
  5737. ['class' => 'btn btn-default', 'target' => '_blank']
  5738. );
  5739. break;
  5740. }
  5741. if ($arrLP[$i]['item_type'] != 'dir') {
  5742. $prerequisities_icon = Display::url(
  5743. Display::return_icon(
  5744. 'accept.png',
  5745. get_lang('LearnpathPrerequisites'),
  5746. [],
  5747. ICON_SIZE_TINY
  5748. ),
  5749. $url.'&action=edit_item_prereq',
  5750. ['class' => 'btn btn-default']
  5751. );
  5752. if ($arrLP[$i]['item_type'] != 'final_item') {
  5753. $move_item_icon = Display::url(
  5754. Display::return_icon(
  5755. 'move.png',
  5756. get_lang('Move'),
  5757. [],
  5758. ICON_SIZE_TINY
  5759. ),
  5760. $url.'&action=move_item',
  5761. ['class' => 'btn btn-default']
  5762. );
  5763. }
  5764. $audio_icon = Display::url(
  5765. Display::return_icon(
  5766. 'audio.png',
  5767. get_lang('UplUpload'),
  5768. [],
  5769. ICON_SIZE_TINY
  5770. ),
  5771. $url.'&action=add_audio',
  5772. ['class' => 'btn btn-default']
  5773. );
  5774. }
  5775. }
  5776. if ($update_audio != 'true') {
  5777. $row = $move_icon.' '.$icon.
  5778. Display::span($title_cut).
  5779. Display::tag(
  5780. 'div',
  5781. "<div class=\"btn-group btn-group-xs\">
  5782. $previewIcon
  5783. $audio
  5784. $edit_icon
  5785. $pluginCalendarIcon
  5786. $forumIcon
  5787. $prerequisities_icon
  5788. $move_item_icon
  5789. $audio_icon
  5790. $orderIcons
  5791. $delete_icon
  5792. </div>",
  5793. ['class' => 'btn-toolbar button_actions']
  5794. );
  5795. } else {
  5796. $row =
  5797. Display::span($title.$icon).
  5798. Display::span($audio, ['class' => 'button_actions']);
  5799. }
  5800. $default_data[$arrLP[$i]['id']] = $row;
  5801. $default_content[$arrLP[$i]['id']] = $arrLP[$i];
  5802. if (empty($parent_id)) {
  5803. $elements[$arrLP[$i]['id']]['data'] = $row;
  5804. $elements[$arrLP[$i]['id']]['type'] = $arrLP[$i]['item_type'];
  5805. } else {
  5806. $parent_arrays = [];
  5807. if ($arrLP[$i]['depth'] > 1) {
  5808. // Getting list of parents
  5809. for ($j = 0; $j < $arrLP[$i]['depth']; $j++) {
  5810. foreach ($arrLP as $item) {
  5811. if ($item['id'] == $parent_id) {
  5812. if ($item['parent_item_id'] == 0) {
  5813. $parent_id = $item['id'];
  5814. break;
  5815. } else {
  5816. $parent_id = $item['parent_item_id'];
  5817. if (empty($parent_arrays)) {
  5818. $parent_arrays[] = intval($item['id']);
  5819. }
  5820. $parent_arrays[] = $parent_id;
  5821. break;
  5822. }
  5823. }
  5824. }
  5825. }
  5826. }
  5827. if (!empty($parent_arrays)) {
  5828. $parent_arrays = array_reverse($parent_arrays);
  5829. $val = '$elements';
  5830. $x = 0;
  5831. foreach ($parent_arrays as $item) {
  5832. if ($x != count($parent_arrays) - 1) {
  5833. $val .= '["'.$item.'"]["children"]';
  5834. } else {
  5835. $val .= '["'.$item.'"]["children"]';
  5836. }
  5837. $x++;
  5838. }
  5839. $val .= "";
  5840. $code_str = $val."[".$arrLP[$i]['id']."][\"load_data\"] = '".$arrLP[$i]['id']."' ; ";
  5841. eval($code_str);
  5842. } else {
  5843. $elements[$parent_id]['children'][$arrLP[$i]['id']]['data'] = $row;
  5844. $elements[$parent_id]['children'][$arrLP[$i]['id']]['type'] = $arrLP[$i]['item_type'];
  5845. }
  5846. }
  5847. }
  5848. return [
  5849. 'elements' => $elements,
  5850. 'default_data' => $default_data,
  5851. 'default_content' => $default_content,
  5852. 'return_audio' => $return_audio,
  5853. ];
  5854. }
  5855. /**
  5856. * @param string $updateAudio true/false strings
  5857. *
  5858. * @return string
  5859. */
  5860. public function returnLpItemList($updateAudio)
  5861. {
  5862. $result = $this->processBuildMenuElements($updateAudio);
  5863. $html = self::print_recursive(
  5864. $result['elements'],
  5865. $result['default_data'],
  5866. $result['default_content']
  5867. );
  5868. if (!empty($html)) {
  5869. $html .= Display::return_message(get_lang('DragAndDropAnElementHere'));
  5870. }
  5871. return $html;
  5872. }
  5873. /**
  5874. * @param string $update_audio
  5875. * @param bool $drop_element_here
  5876. *
  5877. * @return string
  5878. */
  5879. public function return_new_tree($update_audio = 'false', $drop_element_here = false)
  5880. {
  5881. $result = $this->processBuildMenuElements($update_audio);
  5882. $list = '<ul id="lp_item_list">';
  5883. $tree = $this->print_recursive(
  5884. $result['elements'],
  5885. $result['default_data'],
  5886. $result['default_content']
  5887. );
  5888. if (!empty($tree)) {
  5889. $list .= $tree;
  5890. } else {
  5891. if ($drop_element_here) {
  5892. $list .= Display::return_message(get_lang('DragAndDropAnElementHere'));
  5893. }
  5894. }
  5895. $list .= '</ul>';
  5896. $return = Display::panelCollapse(
  5897. $this->name,
  5898. $list,
  5899. 'scorm-list',
  5900. null,
  5901. 'scorm-list-accordion',
  5902. 'scorm-list-collapse'
  5903. );
  5904. if ($update_audio === 'true') {
  5905. $return = $result['return_audio'];
  5906. }
  5907. return $return;
  5908. }
  5909. /**
  5910. * @param array $elements
  5911. * @param array $default_data
  5912. * @param array $default_content
  5913. *
  5914. * @return string
  5915. */
  5916. public function print_recursive($elements, $default_data, $default_content)
  5917. {
  5918. $return = '';
  5919. foreach ($elements as $key => $item) {
  5920. if (isset($item['load_data']) || empty($item['data'])) {
  5921. $item['data'] = $default_data[$item['load_data']];
  5922. $item['type'] = $default_content[$item['load_data']]['item_type'];
  5923. }
  5924. $sub_list = '';
  5925. if (isset($item['type']) && $item['type'] === 'dir') {
  5926. // empty value
  5927. $sub_list = Display::tag('li', '', ['class' => 'sub_item empty']);
  5928. }
  5929. if (empty($item['children'])) {
  5930. $sub_list = Display::tag('ul', $sub_list, ['id' => 'UL_'.$key, 'class' => 'record li_container']);
  5931. $active = null;
  5932. if (isset($_REQUEST['id']) && $key == $_REQUEST['id']) {
  5933. $active = 'active';
  5934. }
  5935. $return .= Display::tag(
  5936. 'li',
  5937. Display::div($item['data'], ['class' => "item_data $active"]).$sub_list,
  5938. ['id' => $key, 'class' => 'record li_container']
  5939. );
  5940. } else {
  5941. // Sections
  5942. $data = '';
  5943. if (isset($item['children'])) {
  5944. $data = self::print_recursive($item['children'], $default_data, $default_content);
  5945. }
  5946. $sub_list = Display::tag('ul', $sub_list.$data, ['id' => 'UL_'.$key, 'class' => 'record li_container']);
  5947. $return .= Display::tag(
  5948. 'li',
  5949. Display::div($item['data'], ['class' => 'item_data']).$sub_list,
  5950. ['id' => $key, 'class' => 'record li_container']
  5951. );
  5952. }
  5953. }
  5954. return $return;
  5955. }
  5956. /**
  5957. * This function builds the action menu.
  5958. *
  5959. * @param bool $returnContent Optional
  5960. * @param bool $showRequirementButtons Optional. Allow show the requirements button
  5961. * @param bool $isConfigPage Optional. If is the config page, show the edit button
  5962. * @param bool $allowExpand Optional. Allow show the expand/contract button
  5963. *
  5964. * @return string
  5965. */
  5966. public function build_action_menu(
  5967. $returnContent = false,
  5968. $showRequirementButtons = true,
  5969. $isConfigPage = false,
  5970. $allowExpand = true
  5971. ) {
  5972. $actionsLeft = '';
  5973. $actionsRight = '';
  5974. $actionsLeft .= Display::url(
  5975. Display::return_icon(
  5976. 'back.png',
  5977. get_lang('ReturnToLearningPaths'),
  5978. '',
  5979. ICON_SIZE_MEDIUM
  5980. ),
  5981. 'lp_controller.php?'.api_get_cidreq()
  5982. );
  5983. $actionsLeft .= Display::url(
  5984. Display::return_icon(
  5985. 'preview_view.png',
  5986. get_lang('Preview'),
  5987. '',
  5988. ICON_SIZE_MEDIUM
  5989. ),
  5990. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  5991. 'action' => 'view',
  5992. 'lp_id' => $this->lp_id,
  5993. 'isStudentView' => 'true',
  5994. ])
  5995. );
  5996. $actionsLeft .= Display::url(
  5997. Display::return_icon(
  5998. 'upload_audio.png',
  5999. get_lang('UpdateAllAudioFragments'),
  6000. '',
  6001. ICON_SIZE_MEDIUM
  6002. ),
  6003. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6004. 'action' => 'admin_view',
  6005. 'lp_id' => $this->lp_id,
  6006. 'updateaudio' => 'true',
  6007. ])
  6008. );
  6009. if (!$isConfigPage) {
  6010. $actionsLeft .= Display::url(
  6011. Display::return_icon(
  6012. 'settings.png',
  6013. get_lang('CourseSettings'),
  6014. '',
  6015. ICON_SIZE_MEDIUM
  6016. ),
  6017. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6018. 'action' => 'edit',
  6019. 'lp_id' => $this->lp_id,
  6020. ])
  6021. );
  6022. } else {
  6023. $actionsLeft .= Display::url(
  6024. Display::return_icon(
  6025. 'edit.png',
  6026. get_lang('Edit'),
  6027. '',
  6028. ICON_SIZE_MEDIUM
  6029. ),
  6030. 'lp_controller.php?'.http_build_query([
  6031. 'action' => 'build',
  6032. 'lp_id' => $this->lp_id,
  6033. ]).'&'.api_get_cidreq()
  6034. );
  6035. }
  6036. if ($allowExpand) {
  6037. $actionsLeft .= Display::url(
  6038. Display::return_icon(
  6039. 'expand.png',
  6040. get_lang('Expand'),
  6041. ['id' => 'expand'],
  6042. ICON_SIZE_MEDIUM
  6043. ).
  6044. Display::return_icon(
  6045. 'contract.png',
  6046. get_lang('Collapse'),
  6047. ['id' => 'contract', 'class' => 'hide'],
  6048. ICON_SIZE_MEDIUM
  6049. ),
  6050. '#',
  6051. ['role' => 'button', 'id' => 'hide_bar_template']
  6052. );
  6053. }
  6054. if ($showRequirementButtons) {
  6055. $buttons = [
  6056. [
  6057. 'title' => get_lang('SetPrerequisiteForEachItem'),
  6058. 'href' => 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6059. 'action' => 'set_previous_step_as_prerequisite',
  6060. 'lp_id' => $this->lp_id,
  6061. ]),
  6062. ],
  6063. [
  6064. 'title' => get_lang('ClearAllPrerequisites'),
  6065. 'href' => 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6066. 'action' => 'clear_prerequisites',
  6067. 'lp_id' => $this->lp_id,
  6068. ]),
  6069. ],
  6070. ];
  6071. $actionsRight = Display::groupButtonWithDropDown(
  6072. get_lang('PrerequisitesOptions'),
  6073. $buttons,
  6074. true
  6075. );
  6076. }
  6077. $toolbar = Display::toolbarAction(
  6078. 'actions-lp-controller',
  6079. [$actionsLeft, $actionsRight]
  6080. );
  6081. if ($returnContent) {
  6082. return $toolbar;
  6083. }
  6084. echo $toolbar;
  6085. }
  6086. /**
  6087. * Creates the default learning path folder.
  6088. *
  6089. * @param array $course
  6090. * @param int $creatorId
  6091. *
  6092. * @return bool
  6093. */
  6094. public static function generate_learning_path_folder($course, $creatorId = 0)
  6095. {
  6096. // Creating learning_path folder
  6097. $dir = '/learning_path';
  6098. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document';
  6099. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6100. $folder = false;
  6101. if (!is_dir($filepath.'/'.$dir)) {
  6102. $folderData = create_unexisting_directory(
  6103. $course,
  6104. $creatorId,
  6105. 0,
  6106. null,
  6107. 0,
  6108. $filepath,
  6109. $dir,
  6110. get_lang('LearningPaths'),
  6111. 0
  6112. );
  6113. if (!empty($folderData)) {
  6114. $folder = true;
  6115. }
  6116. } else {
  6117. $folder = true;
  6118. }
  6119. return $folder;
  6120. }
  6121. /**
  6122. * @param array $course
  6123. * @param string $lp_name
  6124. * @param int $creatorId
  6125. *
  6126. * @return array
  6127. */
  6128. public function generate_lp_folder($course, $lp_name = '', $creatorId = 0)
  6129. {
  6130. $filepath = '';
  6131. $dir = '/learning_path/';
  6132. if (empty($lp_name)) {
  6133. $lp_name = $this->name;
  6134. }
  6135. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6136. $folder = self::generate_learning_path_folder($course, $creatorId);
  6137. // Limits title size
  6138. $title = api_substr(api_replace_dangerous_char($lp_name), 0, 80);
  6139. $dir = $dir.$title;
  6140. // Creating LP folder
  6141. $documentId = null;
  6142. if ($folder) {
  6143. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document';
  6144. if (!is_dir($filepath.'/'.$dir)) {
  6145. $folderData = create_unexisting_directory(
  6146. $course,
  6147. $creatorId,
  6148. 0,
  6149. 0,
  6150. 0,
  6151. $filepath,
  6152. $dir,
  6153. $lp_name
  6154. );
  6155. if (!empty($folderData)) {
  6156. $folder = true;
  6157. }
  6158. $documentId = $folderData['id'];
  6159. } else {
  6160. $folder = true;
  6161. }
  6162. $dir = $dir.'/';
  6163. if ($folder) {
  6164. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document'.$dir;
  6165. }
  6166. }
  6167. if (empty($documentId)) {
  6168. $dir = api_remove_trailing_slash($dir);
  6169. $documentId = DocumentManager::get_document_id($course, $dir, 0);
  6170. }
  6171. $array = [
  6172. 'dir' => $dir,
  6173. 'filepath' => $filepath,
  6174. 'folder' => $folder,
  6175. 'id' => $documentId,
  6176. ];
  6177. return $array;
  6178. }
  6179. /**
  6180. * Create a new document //still needs some finetuning.
  6181. *
  6182. * @param array $courseInfo
  6183. * @param string $content
  6184. * @param string $title
  6185. * @param string $extension
  6186. * @param int $parentId
  6187. * @param int $creatorId creator id
  6188. *
  6189. * @return int
  6190. */
  6191. public function create_document(
  6192. $courseInfo,
  6193. $content = '',
  6194. $title = '',
  6195. $extension = 'html',
  6196. $parentId = 0,
  6197. $creatorId = 0
  6198. ) {
  6199. if (!empty($courseInfo)) {
  6200. $course_id = $courseInfo['real_id'];
  6201. } else {
  6202. $course_id = api_get_course_int_id();
  6203. }
  6204. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6205. $sessionId = api_get_session_id();
  6206. // Generates folder
  6207. $result = $this->generate_lp_folder($courseInfo);
  6208. $dir = $result['dir'];
  6209. if (empty($parentId) || $parentId == '/') {
  6210. $postDir = isset($_POST['dir']) ? $_POST['dir'] : $dir;
  6211. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir; // Please, do not modify this dirname formatting.
  6212. if ($parentId === '/') {
  6213. $dir = '/';
  6214. }
  6215. // Please, do not modify this dirname formatting.
  6216. if (strstr($dir, '..')) {
  6217. $dir = '/';
  6218. }
  6219. if (!empty($dir[0]) && $dir[0] == '.') {
  6220. $dir = substr($dir, 1);
  6221. }
  6222. if (!empty($dir[0]) && $dir[0] != '/') {
  6223. $dir = '/'.$dir;
  6224. }
  6225. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  6226. $dir .= '/';
  6227. }
  6228. } else {
  6229. $parentInfo = DocumentManager::get_document_data_by_id(
  6230. $parentId,
  6231. $courseInfo['code']
  6232. );
  6233. if (!empty($parentInfo)) {
  6234. $dir = $parentInfo['path'].'/';
  6235. }
  6236. }
  6237. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  6238. if (!is_dir($filepath)) {
  6239. $dir = '/';
  6240. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  6241. }
  6242. // stripslashes() before calling api_replace_dangerous_char() because $_POST['title']
  6243. // is already escaped twice when it gets here.
  6244. $originalTitle = !empty($title) ? $title : $_POST['title'];
  6245. if (!empty($title)) {
  6246. $title = api_replace_dangerous_char(stripslashes($title));
  6247. } else {
  6248. $title = api_replace_dangerous_char(stripslashes($_POST['title']));
  6249. }
  6250. $title = disable_dangerous_file($title);
  6251. $filename = $title;
  6252. $content = !empty($content) ? $content : $_POST['content_lp'];
  6253. $tmp_filename = $filename;
  6254. $i = 0;
  6255. while (file_exists($filepath.$tmp_filename.'.'.$extension)) {
  6256. $tmp_filename = $filename.'_'.++$i;
  6257. }
  6258. $filename = $tmp_filename.'.'.$extension;
  6259. if ($extension == 'html') {
  6260. $content = stripslashes($content);
  6261. $content = str_replace(
  6262. api_get_path(WEB_COURSE_PATH),
  6263. api_get_path(REL_PATH).'courses/',
  6264. $content
  6265. );
  6266. // Change the path of mp3 to absolute.
  6267. // The first regexp deals with :// urls.
  6268. $content = preg_replace(
  6269. "|(flashvars=\"file=)([^:/]+)/|",
  6270. "$1".api_get_path(
  6271. REL_COURSE_PATH
  6272. ).$courseInfo['path'].'/document/',
  6273. $content
  6274. );
  6275. // The second regexp deals with audio/ urls.
  6276. $content = preg_replace(
  6277. "|(flashvars=\"file=)([^/]+)/|",
  6278. "$1".api_get_path(
  6279. REL_COURSE_PATH
  6280. ).$courseInfo['path'].'/document/$2/',
  6281. $content
  6282. );
  6283. // For flv player: To prevent edition problem with firefox,
  6284. // we have to use a strange tip (don't blame me please).
  6285. $content = str_replace(
  6286. '</body>',
  6287. '<style type="text/css">body{}</style></body>',
  6288. $content
  6289. );
  6290. }
  6291. if (!file_exists($filepath.$filename)) {
  6292. if ($fp = @fopen($filepath.$filename, 'w')) {
  6293. fputs($fp, $content);
  6294. fclose($fp);
  6295. $file_size = filesize($filepath.$filename);
  6296. $save_file_path = $dir.$filename;
  6297. $document_id = add_document(
  6298. $courseInfo,
  6299. $save_file_path,
  6300. 'file',
  6301. $file_size,
  6302. $tmp_filename,
  6303. '',
  6304. 0, //readonly
  6305. true,
  6306. null,
  6307. $sessionId,
  6308. $creatorId
  6309. );
  6310. if ($document_id) {
  6311. api_item_property_update(
  6312. $courseInfo,
  6313. TOOL_DOCUMENT,
  6314. $document_id,
  6315. 'DocumentAdded',
  6316. $creatorId,
  6317. null,
  6318. null,
  6319. null,
  6320. null,
  6321. $sessionId
  6322. );
  6323. $new_comment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
  6324. $new_title = $originalTitle;
  6325. if ($new_comment || $new_title) {
  6326. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6327. $ct = '';
  6328. if ($new_comment) {
  6329. $ct .= ", comment='".Database::escape_string($new_comment)."'";
  6330. }
  6331. if ($new_title) {
  6332. $ct .= ", title='".Database::escape_string($new_title)."' ";
  6333. }
  6334. $sql = "UPDATE ".$tbl_doc." SET ".substr($ct, 1)."
  6335. WHERE c_id = ".$course_id." AND id = ".$document_id;
  6336. Database::query($sql);
  6337. }
  6338. }
  6339. return $document_id;
  6340. }
  6341. }
  6342. }
  6343. /**
  6344. * Edit a document based on $_POST and $_GET parameters 'dir' and 'path'.
  6345. *
  6346. * @param array $_course array
  6347. */
  6348. public function edit_document($_course)
  6349. {
  6350. $course_id = api_get_course_int_id();
  6351. $urlAppend = api_get_configuration_value('url_append');
  6352. // Please, do not modify this dirname formatting.
  6353. $postDir = isset($_POST['dir']) ? $_POST['dir'] : '';
  6354. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir;
  6355. if (strstr($dir, '..')) {
  6356. $dir = '/';
  6357. }
  6358. if (isset($dir[0]) && $dir[0] == '.') {
  6359. $dir = substr($dir, 1);
  6360. }
  6361. if (isset($dir[0]) && $dir[0] != '/') {
  6362. $dir = '/'.$dir;
  6363. }
  6364. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  6365. $dir .= '/';
  6366. }
  6367. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.$dir;
  6368. if (!is_dir($filepath)) {
  6369. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  6370. }
  6371. $table_doc = Database::get_course_table(TABLE_DOCUMENT);
  6372. if (isset($_POST['path']) && !empty($_POST['path'])) {
  6373. $document_id = (int) $_POST['path'];
  6374. $documentInfo = DocumentManager::get_document_data_by_id($document_id, api_get_course_id(), false, null, true);
  6375. if (empty($documentInfo)) {
  6376. // Try with iid
  6377. $table = Database::get_course_table(TABLE_DOCUMENT);
  6378. $sql = "SELECT id, path FROM $table
  6379. WHERE c_id = $course_id AND iid = $document_id AND path NOT LIKE '%_DELETED_%' ";
  6380. $res_doc = Database::query($sql);
  6381. $row = Database::fetch_array($res_doc);
  6382. if ($row) {
  6383. $document_id = $row['id'];
  6384. $documentPath = $row['path'];
  6385. }
  6386. } else {
  6387. $documentPath = $documentInfo['path'];
  6388. }
  6389. $content = stripslashes($_POST['content_lp']);
  6390. $file = $filepath.$documentPath;
  6391. if (!file_exists($file)) {
  6392. return false;
  6393. }
  6394. if ($fp = @fopen($file, 'w')) {
  6395. $content = str_replace(
  6396. api_get_path(WEB_COURSE_PATH),
  6397. $urlAppend.api_get_path(REL_COURSE_PATH),
  6398. $content
  6399. );
  6400. // Change the path of mp3 to absolute.
  6401. // The first regexp deals with :// urls.
  6402. $content = preg_replace(
  6403. "|(flashvars=\"file=)([^:/]+)/|",
  6404. "$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/',
  6405. $content
  6406. );
  6407. // The second regexp deals with audio/ urls.
  6408. $content = preg_replace(
  6409. "|(flashvars=\"file=)([^:/]+)/|",
  6410. "$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/$2/',
  6411. $content
  6412. );
  6413. fputs($fp, $content);
  6414. fclose($fp);
  6415. $sql = "UPDATE $table_doc SET
  6416. title='".Database::escape_string($_POST['title'])."'
  6417. WHERE c_id = $course_id AND id = ".$document_id;
  6418. Database::query($sql);
  6419. }
  6420. }
  6421. }
  6422. /**
  6423. * Displays the selected item, with a panel for manipulating the item.
  6424. *
  6425. * @param int $item_id
  6426. * @param string $msg
  6427. * @param bool $show_actions
  6428. *
  6429. * @return string
  6430. */
  6431. public function display_item($item_id, $msg = null, $show_actions = true)
  6432. {
  6433. $course_id = api_get_course_int_id();
  6434. $return = '';
  6435. if (is_numeric($item_id)) {
  6436. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  6437. $sql = "SELECT lp.* FROM $tbl_lp_item as lp
  6438. WHERE lp.iid = ".intval($item_id);
  6439. $result = Database::query($sql);
  6440. while ($row = Database::fetch_array($result, 'ASSOC')) {
  6441. $_SESSION['parent_item_id'] = $row['item_type'] == 'dir' ? $item_id : 0;
  6442. // Prevents wrong parent selection for document, see Bug#1251.
  6443. if ($row['item_type'] != 'dir') {
  6444. $_SESSION['parent_item_id'] = $row['parent_item_id'];
  6445. }
  6446. if ($show_actions) {
  6447. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6448. }
  6449. $return .= '<div style="padding:10px;">';
  6450. if ($msg != '') {
  6451. $return .= $msg;
  6452. }
  6453. $return .= '<h3>'.$row['title'].'</h3>';
  6454. switch ($row['item_type']) {
  6455. case TOOL_THREAD:
  6456. $link = $this->rl_get_resource_link_for_learnpath(
  6457. $course_id,
  6458. $row['lp_id'],
  6459. $item_id,
  6460. 0
  6461. );
  6462. $return .= Display::url(
  6463. get_lang('GoToThread'),
  6464. $link,
  6465. ['class' => 'btn btn-primary']
  6466. );
  6467. break;
  6468. case TOOL_FORUM:
  6469. $return .= Display::url(
  6470. get_lang('GoToForum'),
  6471. api_get_path(WEB_CODE_PATH).'forum/viewforum.php?'.api_get_cidreq().'&forum='.$row['path'],
  6472. ['class' => 'btn btn-primary']
  6473. );
  6474. break;
  6475. case TOOL_QUIZ:
  6476. if (!empty($row['path'])) {
  6477. $exercise = new Exercise();
  6478. $exercise->read($row['path']);
  6479. $return .= $exercise->description.'<br />';
  6480. $return .= Display::url(
  6481. get_lang('GoToExercise'),
  6482. api_get_path(WEB_CODE_PATH).'exercise/overview.php?'.api_get_cidreq().'&exerciseId='.$exercise->id,
  6483. ['class' => 'btn btn-primary']
  6484. );
  6485. }
  6486. break;
  6487. case TOOL_LP_FINAL_ITEM:
  6488. $return .= $this->getSavedFinalItem();
  6489. break;
  6490. case TOOL_DOCUMENT:
  6491. case TOOL_READOUT_TEXT:
  6492. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6493. $sql_doc = "SELECT path FROM $tbl_doc
  6494. WHERE c_id = $course_id AND iid = ".intval($row['path']);
  6495. $result = Database::query($sql_doc);
  6496. $path_file = Database::result($result, 0, 0);
  6497. $path_parts = pathinfo($path_file);
  6498. // TODO: Correct the following naive comparisons.
  6499. if (in_array($path_parts['extension'], [
  6500. 'html',
  6501. 'txt',
  6502. 'png',
  6503. 'jpg',
  6504. 'JPG',
  6505. 'jpeg',
  6506. 'JPEG',
  6507. 'gif',
  6508. 'swf',
  6509. 'pdf',
  6510. 'htm',
  6511. ])) {
  6512. $return .= $this->display_document($row['path'], true, true);
  6513. }
  6514. break;
  6515. case TOOL_HOTPOTATOES:
  6516. $return .= $this->display_document($row['path'], false, true);
  6517. break;
  6518. }
  6519. $return .= '</div>';
  6520. }
  6521. }
  6522. return $return;
  6523. }
  6524. /**
  6525. * Shows the needed forms for editing a specific item.
  6526. *
  6527. * @param int $item_id
  6528. *
  6529. * @throws Exception
  6530. * @throws HTML_QuickForm_Error
  6531. *
  6532. * @return string
  6533. */
  6534. public function display_edit_item($item_id)
  6535. {
  6536. $course_id = api_get_course_int_id();
  6537. $return = '';
  6538. $item_id = (int) $item_id;
  6539. if (empty($item_id)) {
  6540. return '';
  6541. }
  6542. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  6543. $sql = "SELECT * FROM $tbl_lp_item
  6544. WHERE iid = ".$item_id;
  6545. $res = Database::query($sql);
  6546. $row = Database::fetch_array($res);
  6547. switch ($row['item_type']) {
  6548. case 'dir':
  6549. case 'asset':
  6550. case 'sco':
  6551. if (isset($_GET['view']) && $_GET['view'] == 'build') {
  6552. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6553. $return .= $this->display_item_form(
  6554. $row['item_type'],
  6555. get_lang('EditCurrentChapter').' :',
  6556. 'edit',
  6557. $item_id,
  6558. $row
  6559. );
  6560. } else {
  6561. $return .= $this->display_item_form(
  6562. $row['item_type'],
  6563. get_lang('EditCurrentChapter').' :',
  6564. 'edit_item',
  6565. $item_id,
  6566. $row
  6567. );
  6568. }
  6569. break;
  6570. case TOOL_DOCUMENT:
  6571. case TOOL_READOUT_TEXT:
  6572. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6573. $sql = "SELECT lp.*, doc.path as dir
  6574. FROM $tbl_lp_item as lp
  6575. LEFT JOIN $tbl_doc as doc
  6576. ON (doc.iid = lp.path AND lp.c_id = doc.c_id)
  6577. WHERE
  6578. doc.c_id = $course_id AND
  6579. lp.iid = ".$item_id;
  6580. $res_step = Database::query($sql);
  6581. $row_step = Database::fetch_array($res_step, 'ASSOC');
  6582. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6583. if ($row['item_type'] === TOOL_DOCUMENT) {
  6584. $return .= $this->display_document_form('edit', $item_id, $row_step);
  6585. }
  6586. if ($row['item_type'] === TOOL_READOUT_TEXT) {
  6587. $return .= $this->displayFrmReadOutText('edit', $item_id, $row_step);
  6588. }
  6589. break;
  6590. case TOOL_LINK:
  6591. $linkId = (int) $row['path'];
  6592. if (!empty($linkId)) {
  6593. $table = Database::get_course_table(TABLE_LINK);
  6594. $sql = 'SELECT url FROM '.$table.'
  6595. WHERE c_id = '.$course_id.' AND iid = '.$linkId;
  6596. $res_link = Database::query($sql);
  6597. $row_link = Database::fetch_array($res_link);
  6598. if (empty($row_link)) {
  6599. // Try with id
  6600. $sql = 'SELECT url FROM '.$table.'
  6601. WHERE c_id = '.$course_id.' AND id = '.$linkId;
  6602. $res_link = Database::query($sql);
  6603. $row_link = Database::fetch_array($res_link);
  6604. }
  6605. if (is_array($row_link)) {
  6606. $row['url'] = $row_link['url'];
  6607. }
  6608. }
  6609. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6610. $return .= $this->display_link_form('edit', $item_id, $row);
  6611. break;
  6612. case TOOL_LP_FINAL_ITEM:
  6613. Session::write('finalItem', true);
  6614. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6615. $sql = "SELECT lp.*, doc.path as dir
  6616. FROM $tbl_lp_item as lp
  6617. LEFT JOIN $tbl_doc as doc
  6618. ON (doc.iid = lp.path AND lp.c_id = doc.c_id)
  6619. WHERE
  6620. doc.c_id = $course_id AND
  6621. lp.iid = ".$item_id;
  6622. $res_step = Database::query($sql);
  6623. $row_step = Database::fetch_array($res_step, 'ASSOC');
  6624. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6625. $return .= $this->display_document_form('edit', $item_id, $row_step);
  6626. break;
  6627. case TOOL_QUIZ:
  6628. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6629. $return .= $this->display_quiz_form('edit', $item_id, $row);
  6630. break;
  6631. case TOOL_HOTPOTATOES:
  6632. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6633. $return .= $this->display_hotpotatoes_form('edit', $item_id, $row);
  6634. break;
  6635. case TOOL_STUDENTPUBLICATION:
  6636. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6637. $return .= $this->display_student_publication_form('edit', $item_id, $row);
  6638. break;
  6639. case TOOL_FORUM:
  6640. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6641. $return .= $this->display_forum_form('edit', $item_id, $row);
  6642. break;
  6643. case TOOL_THREAD:
  6644. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6645. $return .= $this->display_thread_form('edit', $item_id, $row);
  6646. break;
  6647. }
  6648. return $return;
  6649. }
  6650. /**
  6651. * Function that displays a list with al the resources that
  6652. * could be added to the learning path.
  6653. *
  6654. * @throws Exception
  6655. * @throws HTML_QuickForm_Error
  6656. *
  6657. * @return bool
  6658. */
  6659. public function display_resources()
  6660. {
  6661. $course_code = api_get_course_id();
  6662. // Get all the docs.
  6663. $documents = $this->get_documents(true);
  6664. // Get all the exercises.
  6665. $exercises = $this->get_exercises();
  6666. // Get all the links.
  6667. $links = $this->get_links();
  6668. // Get all the student publications.
  6669. $works = $this->get_student_publications();
  6670. // Get all the forums.
  6671. $forums = $this->get_forums(null, $course_code);
  6672. // Get the final item form (see BT#11048) .
  6673. $finish = $this->getFinalItemForm();
  6674. $headers = [
  6675. Display::return_icon('folder_document.png', get_lang('Documents'), [], ICON_SIZE_BIG),
  6676. Display::return_icon('quiz.png', get_lang('Quiz'), [], ICON_SIZE_BIG),
  6677. Display::return_icon('links.png', get_lang('Links'), [], ICON_SIZE_BIG),
  6678. Display::return_icon('works.png', get_lang('Works'), [], ICON_SIZE_BIG),
  6679. Display::return_icon('forum.png', get_lang('Forums'), [], ICON_SIZE_BIG),
  6680. Display::return_icon('add_learnpath_section.png', get_lang('NewChapter'), [], ICON_SIZE_BIG),
  6681. Display::return_icon('certificate.png', get_lang('Certificate'), [], ICON_SIZE_BIG),
  6682. ];
  6683. echo Display::return_message(get_lang('ClickOnTheLearnerViewToSeeYourLearningPath'), 'normal');
  6684. $dir = $this->display_item_form('dir', get_lang('EnterDataNewChapter'), 'add_item');
  6685. $selected = isset($_REQUEST['lp_build_selected']) ? (int) $_REQUEST['lp_build_selected'] : 0;
  6686. echo Display::tabs(
  6687. $headers,
  6688. [
  6689. $documents,
  6690. $exercises,
  6691. $links,
  6692. $works,
  6693. $forums,
  6694. $dir,
  6695. $finish,
  6696. ],
  6697. 'resource_tab',
  6698. [],
  6699. [],
  6700. $selected
  6701. );
  6702. return true;
  6703. }
  6704. /**
  6705. * Returns the extension of a document.
  6706. *
  6707. * @param string $filename
  6708. *
  6709. * @return string Extension (part after the last dot)
  6710. */
  6711. public function get_extension($filename)
  6712. {
  6713. $explode = explode('.', $filename);
  6714. return $explode[count($explode) - 1];
  6715. }
  6716. /**
  6717. * Displays a document by id.
  6718. *
  6719. * @param int $id
  6720. * @param bool $show_title
  6721. * @param bool $iframe
  6722. * @param bool $edit_link
  6723. *
  6724. * @return string
  6725. */
  6726. public function display_document($id, $show_title = false, $iframe = true, $edit_link = false)
  6727. {
  6728. $_course = api_get_course_info();
  6729. $course_id = api_get_course_int_id();
  6730. $id = (int) $id;
  6731. $return = '';
  6732. $table = Database::get_course_table(TABLE_DOCUMENT);
  6733. $sql_doc = "SELECT * FROM $table
  6734. WHERE c_id = $course_id AND iid = $id";
  6735. $res_doc = Database::query($sql_doc);
  6736. $row_doc = Database::fetch_array($res_doc);
  6737. // TODO: Add a path filter.
  6738. if ($iframe) {
  6739. $return .= '<iframe id="learnpath_preview_frame" frameborder="0" height="400" width="100%" scrolling="auto" src="'.api_get_path(WEB_COURSE_PATH).$_course['path'].'/document'.str_replace('%2F', '/', urlencode($row_doc['path'])).'?'.api_get_cidreq().'"></iframe>';
  6740. } else {
  6741. $return .= file_get_contents(api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/'.$row_doc['path']);
  6742. }
  6743. return $return;
  6744. }
  6745. /**
  6746. * Return HTML form to add/edit a quiz.
  6747. *
  6748. * @param string $action Action (add/edit)
  6749. * @param int $id Item ID if already exists
  6750. * @param mixed $extra_info Extra information (quiz ID if integer)
  6751. *
  6752. * @throws Exception
  6753. *
  6754. * @return string HTML form
  6755. */
  6756. public function display_quiz_form($action = 'add', $id = 0, $extra_info = '')
  6757. {
  6758. $course_id = api_get_course_int_id();
  6759. $id = (int) $id;
  6760. $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  6761. if ($id != 0 && is_array($extra_info)) {
  6762. $item_title = $extra_info['title'];
  6763. $item_description = $extra_info['description'];
  6764. } elseif (is_numeric($extra_info)) {
  6765. $sql = "SELECT title, description
  6766. FROM $tbl_quiz
  6767. WHERE c_id = $course_id AND iid = ".$extra_info;
  6768. $result = Database::query($sql);
  6769. $row = Database::fetch_array($result);
  6770. $item_title = $row['title'];
  6771. $item_description = $row['description'];
  6772. } else {
  6773. $item_title = '';
  6774. $item_description = '';
  6775. }
  6776. $item_title = Security::remove_XSS($item_title);
  6777. $item_description = Security::remove_XSS($item_description);
  6778. $parent = 0;
  6779. if ($id != 0 && is_array($extra_info)) {
  6780. $parent = $extra_info['parent_item_id'];
  6781. }
  6782. $arrLP = $this->getItemsForForm();
  6783. $this->tree_array($arrLP);
  6784. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  6785. unset($this->arrMenu);
  6786. $form = new FormValidator(
  6787. 'quiz_form',
  6788. 'POST',
  6789. $this->getCurrentBuildingModeURL()
  6790. );
  6791. $defaults = [];
  6792. if ($action === 'add') {
  6793. $legend = get_lang('CreateTheExercise');
  6794. } elseif ($action === 'move') {
  6795. $legend = get_lang('MoveTheCurrentExercise');
  6796. } else {
  6797. $legend = get_lang('EditCurrentExecice');
  6798. }
  6799. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  6800. $legend .= Display::return_message(get_lang('Warning').' ! '.get_lang('WarningEditingDocument'));
  6801. }
  6802. $form->addHeader($legend);
  6803. if ($action != 'move') {
  6804. $this->setItemTitle($form);
  6805. $defaults['title'] = $item_title;
  6806. }
  6807. // Select for Parent item, root or chapter
  6808. $selectParent = $form->addSelect(
  6809. 'parent',
  6810. get_lang('Parent'),
  6811. [],
  6812. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);']
  6813. );
  6814. $selectParent->addOption($this->name, 0);
  6815. $arrHide = [
  6816. $id,
  6817. ];
  6818. for ($i = 0; $i < count($arrLP); $i++) {
  6819. if ($action != 'add') {
  6820. if (
  6821. ($arrLP[$i]['item_type'] == 'dir') &&
  6822. !in_array($arrLP[$i]['id'], $arrHide) &&
  6823. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  6824. ) {
  6825. $selectParent->addOption(
  6826. $arrLP[$i]['title'],
  6827. $arrLP[$i]['id'],
  6828. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  6829. );
  6830. if ($parent == $arrLP[$i]['id']) {
  6831. $selectParent->setSelected($arrLP[$i]['id']);
  6832. }
  6833. } else {
  6834. $arrHide[] = $arrLP[$i]['id'];
  6835. }
  6836. } else {
  6837. if ($arrLP[$i]['item_type'] == 'dir') {
  6838. $selectParent->addOption(
  6839. $arrLP[$i]['title'],
  6840. $arrLP[$i]['id'],
  6841. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  6842. );
  6843. if ($parent == $arrLP[$i]['id']) {
  6844. $selectParent->setSelected($arrLP[$i]['id']);
  6845. }
  6846. }
  6847. }
  6848. }
  6849. if (is_array($arrLP)) {
  6850. reset($arrLP);
  6851. }
  6852. $selectPrevious = $form->addSelect(
  6853. 'previous',
  6854. get_lang('Position'),
  6855. [],
  6856. ['id' => 'previous']
  6857. );
  6858. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  6859. for ($i = 0; $i < count($arrLP); $i++) {
  6860. if ($arrLP[$i]['parent_item_id'] == $parent &&
  6861. $arrLP[$i]['id'] != $id
  6862. ) {
  6863. $selectPrevious->addOption(
  6864. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  6865. $arrLP[$i]['id']
  6866. );
  6867. if (is_array($extra_info)) {
  6868. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  6869. $selectPrevious->setSelected($arrLP[$i]['id']);
  6870. }
  6871. } elseif ($action == 'add') {
  6872. $selectPrevious->setSelected($arrLP[$i]['id']);
  6873. }
  6874. }
  6875. }
  6876. if ($action != 'move') {
  6877. $arrHide = [];
  6878. for ($i = 0; $i < count($arrLP); $i++) {
  6879. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  6880. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  6881. }
  6882. }
  6883. }
  6884. if ($action === 'add') {
  6885. $form->addButtonSave(get_lang('AddExercise'), 'submit_button');
  6886. } else {
  6887. $form->addButtonSave(get_lang('EditCurrentExecice'), 'submit_button');
  6888. }
  6889. if ($action === 'move') {
  6890. $form->addHidden('title', $item_title);
  6891. $form->addHidden('description', $item_description);
  6892. }
  6893. if (is_numeric($extra_info)) {
  6894. $form->addHidden('path', $extra_info);
  6895. } elseif (is_array($extra_info)) {
  6896. $form->addHidden('path', $extra_info['path']);
  6897. }
  6898. $form->addHidden('type', TOOL_QUIZ);
  6899. $form->addHidden('post_time', time());
  6900. $form->setDefaults($defaults);
  6901. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  6902. }
  6903. /**
  6904. * Addition of Hotpotatoes tests.
  6905. *
  6906. * @param string $action
  6907. * @param int $id Internal ID of the item
  6908. * @param string $extra_info
  6909. *
  6910. * @return string HTML structure to display the hotpotatoes addition formular
  6911. */
  6912. public function display_hotpotatoes_form($action = 'add', $id = 0, $extra_info = '')
  6913. {
  6914. $course_id = api_get_course_int_id();
  6915. $uploadPath = DIR_HOTPOTATOES;
  6916. if ($id != 0 && is_array($extra_info)) {
  6917. $item_title = stripslashes($extra_info['title']);
  6918. $item_description = stripslashes($extra_info['description']);
  6919. } elseif (is_numeric($extra_info)) {
  6920. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  6921. $sql = "SELECT * FROM $TBL_DOCUMENT
  6922. WHERE
  6923. c_id = $course_id AND
  6924. path LIKE '".$uploadPath."/%/%htm%' AND
  6925. iid = ".(int) $extra_info."
  6926. ORDER BY iid ASC";
  6927. $res_hot = Database::query($sql);
  6928. $row = Database::fetch_array($res_hot);
  6929. $item_title = $row['title'];
  6930. $item_description = $row['description'];
  6931. if (!empty($row['comment'])) {
  6932. $item_title = $row['comment'];
  6933. }
  6934. } else {
  6935. $item_title = '';
  6936. $item_description = '';
  6937. }
  6938. $parent = 0;
  6939. if ($id != 0 && is_array($extra_info)) {
  6940. $parent = $extra_info['parent_item_id'];
  6941. }
  6942. $arrLP = $this->getItemsForForm();
  6943. $legend = '<legend>';
  6944. if ($action == 'add') {
  6945. $legend .= get_lang('CreateTheExercise');
  6946. } elseif ($action == 'move') {
  6947. $legend .= get_lang('MoveTheCurrentExercise');
  6948. } else {
  6949. $legend .= get_lang('EditCurrentExecice');
  6950. }
  6951. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  6952. $legend .= Display:: return_message(
  6953. get_lang('Warning').' ! '.get_lang('WarningEditingDocument')
  6954. );
  6955. }
  6956. $legend .= '</legend>';
  6957. $return = '<form method="POST">';
  6958. $return .= $legend;
  6959. $return .= '<table cellpadding="0" cellspacing="0" class="lp_form">';
  6960. $return .= '<tr>';
  6961. $return .= '<td class="label"><label for="idParent">'.get_lang('Parent').' :</label></td>';
  6962. $return .= '<td class="input">';
  6963. $return .= '<select id="idParent" name="parent" onChange="javascript: load_cbo(this.value);" size="1">';
  6964. $return .= '<option class="top" value="0">'.$this->name.'</option>';
  6965. $arrHide = [$id];
  6966. if (count($arrLP) > 0) {
  6967. for ($i = 0; $i < count($arrLP); $i++) {
  6968. if ($action != 'add') {
  6969. if ($arrLP[$i]['item_type'] == 'dir' &&
  6970. !in_array($arrLP[$i]['id'], $arrHide) &&
  6971. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  6972. ) {
  6973. $return .= '<option '.(($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '').'style="padding-left:'.($arrLP[$i]['depth'] * 10).'px;" value="'.$arrLP[$i]['id'].'">'.$arrLP[$i]['title'].'</option>';
  6974. } else {
  6975. $arrHide[] = $arrLP[$i]['id'];
  6976. }
  6977. } else {
  6978. if ($arrLP[$i]['item_type'] == 'dir') {
  6979. $return .= '<option '.(($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '').'style="padding-left:'.($arrLP[$i]['depth'] * 10).'px;" value="'.$arrLP[$i]['id'].'">'.$arrLP[$i]['title'].'</option>';
  6980. }
  6981. }
  6982. }
  6983. reset($arrLP);
  6984. }
  6985. $return .= '</select>';
  6986. $return .= '</td>';
  6987. $return .= '</tr>';
  6988. $return .= '<tr>';
  6989. $return .= '<td class="label"><label for="previous">'.get_lang('Position').' :</label></td>';
  6990. $return .= '<td class="input">';
  6991. $return .= '<select id="previous" name="previous" size="1">';
  6992. $return .= '<option class="top" value="0">'.get_lang('FirstPosition').'</option>';
  6993. for ($i = 0; $i < count($arrLP); $i++) {
  6994. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  6995. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  6996. $selected = 'selected="selected" ';
  6997. } elseif ($action == 'add') {
  6998. $selected = 'selected="selected" ';
  6999. } else {
  7000. $selected = '';
  7001. }
  7002. $return .= '<option '.$selected.'value="'.$arrLP[$i]['id'].'">'.
  7003. get_lang('After').' "'.$arrLP[$i]['title'].'"</option>';
  7004. }
  7005. }
  7006. $return .= '</select>';
  7007. $return .= '</td>';
  7008. $return .= '</tr>';
  7009. if ($action != 'move') {
  7010. $return .= '<tr>';
  7011. $return .= '<td class="label"><label for="idTitle">'.get_lang('Title').' :</label></td>';
  7012. $return .= '<td class="input"><input id="idTitle" name="title" type="text" value="'.$item_title.'" /></td>';
  7013. $return .= '</tr>';
  7014. $id_prerequisite = 0;
  7015. if (is_array($arrLP) && count($arrLP) > 0) {
  7016. foreach ($arrLP as $key => $value) {
  7017. if ($value['id'] == $id) {
  7018. $id_prerequisite = $value['prerequisite'];
  7019. break;
  7020. }
  7021. }
  7022. $arrHide = [];
  7023. for ($i = 0; $i < count($arrLP); $i++) {
  7024. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7025. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7026. }
  7027. }
  7028. }
  7029. }
  7030. $return .= '<tr>';
  7031. $return .= '<td>&nbsp; </td><td><button class="save" name="submit_button" action="edit" type="submit">'.
  7032. get_lang('SaveHotpotatoes').'</button></td>';
  7033. $return .= '</tr>';
  7034. $return .= '</table>';
  7035. if ($action == 'move') {
  7036. $return .= '<input name="title" type="hidden" value="'.$item_title.'" />';
  7037. $return .= '<input name="description" type="hidden" value="'.$item_description.'" />';
  7038. }
  7039. if (is_numeric($extra_info)) {
  7040. $return .= '<input name="path" type="hidden" value="'.$extra_info.'" />';
  7041. } elseif (is_array($extra_info)) {
  7042. $return .= '<input name="path" type="hidden" value="'.$extra_info['path'].'" />';
  7043. }
  7044. $return .= '<input name="type" type="hidden" value="'.TOOL_HOTPOTATOES.'" />';
  7045. $return .= '<input name="post_time" type="hidden" value="'.time().'" />';
  7046. $return .= '</form>';
  7047. return $return;
  7048. }
  7049. /**
  7050. * Return the form to display the forum edit/add option.
  7051. *
  7052. * @param string $action
  7053. * @param int $id ID of the lp_item if already exists
  7054. * @param string $extra_info
  7055. *
  7056. * @throws Exception
  7057. *
  7058. * @return string HTML form
  7059. */
  7060. public function display_forum_form($action = 'add', $id = 0, $extra_info = '')
  7061. {
  7062. $course_id = api_get_course_int_id();
  7063. $tbl_forum = Database::get_course_table(TABLE_FORUM);
  7064. $item_title = '';
  7065. $item_description = '';
  7066. if ($id != 0 && is_array($extra_info)) {
  7067. $item_title = stripslashes($extra_info['title']);
  7068. } elseif (is_numeric($extra_info)) {
  7069. $sql = "SELECT forum_title as title, forum_comment as comment
  7070. FROM $tbl_forum
  7071. WHERE c_id = $course_id AND forum_id = ".$extra_info;
  7072. $result = Database::query($sql);
  7073. $row = Database::fetch_array($result);
  7074. $item_title = $row['title'];
  7075. $item_description = $row['comment'];
  7076. }
  7077. $parent = 0;
  7078. if ($id != 0 && is_array($extra_info)) {
  7079. $parent = $extra_info['parent_item_id'];
  7080. }
  7081. $arrLP = $this->getItemsForForm();
  7082. $this->tree_array($arrLP);
  7083. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7084. unset($this->arrMenu);
  7085. if ($action == 'add') {
  7086. $legend = get_lang('CreateTheForum');
  7087. } elseif ($action == 'move') {
  7088. $legend = get_lang('MoveTheCurrentForum');
  7089. } else {
  7090. $legend = get_lang('EditCurrentForum');
  7091. }
  7092. $form = new FormValidator(
  7093. 'forum_form',
  7094. 'POST',
  7095. $this->getCurrentBuildingModeURL()
  7096. );
  7097. $defaults = [];
  7098. $form->addHeader($legend);
  7099. if ($action != 'move') {
  7100. $this->setItemTitle($form);
  7101. $defaults['title'] = $item_title;
  7102. }
  7103. $selectParent = $form->addSelect(
  7104. 'parent',
  7105. get_lang('Parent'),
  7106. [],
  7107. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);', 'class' => 'learnpath_item_form']
  7108. );
  7109. $selectParent->addOption($this->name, 0);
  7110. $arrHide = [
  7111. $id,
  7112. ];
  7113. for ($i = 0; $i < count($arrLP); $i++) {
  7114. if ($action != 'add') {
  7115. if ($arrLP[$i]['item_type'] == 'dir' &&
  7116. !in_array($arrLP[$i]['id'], $arrHide) &&
  7117. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7118. ) {
  7119. $selectParent->addOption(
  7120. $arrLP[$i]['title'],
  7121. $arrLP[$i]['id'],
  7122. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7123. );
  7124. if ($parent == $arrLP[$i]['id']) {
  7125. $selectParent->setSelected($arrLP[$i]['id']);
  7126. }
  7127. } else {
  7128. $arrHide[] = $arrLP[$i]['id'];
  7129. }
  7130. } else {
  7131. if ($arrLP[$i]['item_type'] == 'dir') {
  7132. $selectParent->addOption(
  7133. $arrLP[$i]['title'],
  7134. $arrLP[$i]['id'],
  7135. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7136. );
  7137. if ($parent == $arrLP[$i]['id']) {
  7138. $selectParent->setSelected($arrLP[$i]['id']);
  7139. }
  7140. }
  7141. }
  7142. }
  7143. if (is_array($arrLP)) {
  7144. reset($arrLP);
  7145. }
  7146. $selectPrevious = $form->addSelect(
  7147. 'previous',
  7148. get_lang('Position'),
  7149. [],
  7150. ['id' => 'previous', 'class' => 'learnpath_item_form']
  7151. );
  7152. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  7153. for ($i = 0; $i < count($arrLP); $i++) {
  7154. if ($arrLP[$i]['parent_item_id'] == $parent &&
  7155. $arrLP[$i]['id'] != $id
  7156. ) {
  7157. $selectPrevious->addOption(
  7158. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  7159. $arrLP[$i]['id']
  7160. );
  7161. if (isset($extra_info['previous_item_id']) &&
  7162. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7163. ) {
  7164. $selectPrevious->setSelected($arrLP[$i]['id']);
  7165. } elseif ($action == 'add') {
  7166. $selectPrevious->setSelected($arrLP[$i]['id']);
  7167. }
  7168. }
  7169. }
  7170. if ($action != 'move') {
  7171. $id_prerequisite = 0;
  7172. if (is_array($arrLP)) {
  7173. foreach ($arrLP as $key => $value) {
  7174. if ($value['id'] == $id) {
  7175. $id_prerequisite = $value['prerequisite'];
  7176. break;
  7177. }
  7178. }
  7179. }
  7180. $arrHide = [];
  7181. for ($i = 0; $i < count($arrLP); $i++) {
  7182. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7183. if (isset($extra_info['previous_item_id']) &&
  7184. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7185. ) {
  7186. $s_selected_position = $arrLP[$i]['id'];
  7187. } elseif ($action == 'add') {
  7188. $s_selected_position = 0;
  7189. }
  7190. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7191. }
  7192. }
  7193. }
  7194. if ($action == 'add') {
  7195. $form->addButtonSave(get_lang('AddForumToCourse'), 'submit_button');
  7196. } else {
  7197. $form->addButtonSave(get_lang('EditCurrentForum'), 'submit_button');
  7198. }
  7199. if ($action == 'move') {
  7200. $form->addHidden('title', $item_title);
  7201. $form->addHidden('description', $item_description);
  7202. }
  7203. if (is_numeric($extra_info)) {
  7204. $form->addHidden('path', $extra_info);
  7205. } elseif (is_array($extra_info)) {
  7206. $form->addHidden('path', $extra_info['path']);
  7207. }
  7208. $form->addHidden('type', TOOL_FORUM);
  7209. $form->addHidden('post_time', time());
  7210. $form->setDefaults($defaults);
  7211. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  7212. }
  7213. /**
  7214. * Return HTML form to add/edit forum threads.
  7215. *
  7216. * @param string $action
  7217. * @param int $id Item ID if already exists in learning path
  7218. * @param string $extra_info
  7219. *
  7220. * @throws Exception
  7221. *
  7222. * @return string HTML form
  7223. */
  7224. public function display_thread_form($action = 'add', $id = 0, $extra_info = '')
  7225. {
  7226. $course_id = api_get_course_int_id();
  7227. if (empty($course_id)) {
  7228. return null;
  7229. }
  7230. $tbl_forum = Database::get_course_table(TABLE_FORUM_THREAD);
  7231. $item_title = '';
  7232. $item_description = '';
  7233. if ($id != 0 && is_array($extra_info)) {
  7234. $item_title = stripslashes($extra_info['title']);
  7235. } elseif (is_numeric($extra_info)) {
  7236. $sql = "SELECT thread_title as title FROM $tbl_forum
  7237. WHERE c_id = $course_id AND thread_id = ".$extra_info;
  7238. $result = Database::query($sql);
  7239. $row = Database::fetch_array($result);
  7240. $item_title = $row['title'];
  7241. $item_description = '';
  7242. }
  7243. $parent = 0;
  7244. if ($id != 0 && is_array($extra_info)) {
  7245. $parent = $extra_info['parent_item_id'];
  7246. }
  7247. $arrLP = $this->getItemsForForm();
  7248. $this->tree_array($arrLP);
  7249. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7250. unset($this->arrMenu);
  7251. $form = new FormValidator(
  7252. 'thread_form',
  7253. 'POST',
  7254. $this->getCurrentBuildingModeURL()
  7255. );
  7256. $defaults = [];
  7257. if ($action == 'add') {
  7258. $legend = get_lang('CreateTheForum');
  7259. } elseif ($action == 'move') {
  7260. $legend = get_lang('MoveTheCurrentForum');
  7261. } else {
  7262. $legend = get_lang('EditCurrentForum');
  7263. }
  7264. $form->addHeader($legend);
  7265. $selectParent = $form->addSelect(
  7266. 'parent',
  7267. get_lang('Parent'),
  7268. [],
  7269. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);']
  7270. );
  7271. $selectParent->addOption($this->name, 0);
  7272. $arrHide = [
  7273. $id,
  7274. ];
  7275. for ($i = 0; $i < count($arrLP); $i++) {
  7276. if ($action != 'add') {
  7277. if (
  7278. ($arrLP[$i]['item_type'] == 'dir') &&
  7279. !in_array($arrLP[$i]['id'], $arrHide) &&
  7280. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7281. ) {
  7282. $selectParent->addOption(
  7283. $arrLP[$i]['title'],
  7284. $arrLP[$i]['id'],
  7285. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7286. );
  7287. if ($parent == $arrLP[$i]['id']) {
  7288. $selectParent->setSelected($arrLP[$i]['id']);
  7289. }
  7290. } else {
  7291. $arrHide[] = $arrLP[$i]['id'];
  7292. }
  7293. } else {
  7294. if ($arrLP[$i]['item_type'] == 'dir') {
  7295. $selectParent->addOption(
  7296. $arrLP[$i]['title'],
  7297. $arrLP[$i]['id'],
  7298. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7299. );
  7300. if ($parent == $arrLP[$i]['id']) {
  7301. $selectParent->setSelected($arrLP[$i]['id']);
  7302. }
  7303. }
  7304. }
  7305. }
  7306. if ($arrLP != null) {
  7307. reset($arrLP);
  7308. }
  7309. $selectPrevious = $form->addSelect(
  7310. 'previous',
  7311. get_lang('Position'),
  7312. [],
  7313. ['id' => 'previous']
  7314. );
  7315. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  7316. for ($i = 0; $i < count($arrLP); $i++) {
  7317. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  7318. $selectPrevious->addOption(
  7319. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  7320. $arrLP[$i]['id']
  7321. );
  7322. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7323. $selectPrevious->setSelected($arrLP[$i]['id']);
  7324. } elseif ($action == 'add') {
  7325. $selectPrevious->setSelected($arrLP[$i]['id']);
  7326. }
  7327. }
  7328. }
  7329. if ($action != 'move') {
  7330. $this->setItemTitle($form);
  7331. $defaults['title'] = $item_title;
  7332. $id_prerequisite = 0;
  7333. if ($arrLP != null) {
  7334. foreach ($arrLP as $key => $value) {
  7335. if ($value['id'] == $id) {
  7336. $id_prerequisite = $value['prerequisite'];
  7337. break;
  7338. }
  7339. }
  7340. }
  7341. $arrHide = [];
  7342. $s_selected_position = 0;
  7343. for ($i = 0; $i < count($arrLP); $i++) {
  7344. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7345. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7346. $s_selected_position = $arrLP[$i]['id'];
  7347. } elseif ($action == 'add') {
  7348. $s_selected_position = 0;
  7349. }
  7350. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7351. }
  7352. }
  7353. $selectPrerequisites = $form->addSelect(
  7354. 'prerequisites',
  7355. get_lang('LearnpathPrerequisites'),
  7356. [],
  7357. ['id' => 'prerequisites']
  7358. );
  7359. $selectPrerequisites->addOption(get_lang('NoPrerequisites'), 0);
  7360. foreach ($arrHide as $key => $value) {
  7361. $selectPrerequisites->addOption($value['value'], $key);
  7362. if ($key == $s_selected_position && $action == 'add') {
  7363. $selectPrerequisites->setSelected($key);
  7364. } elseif ($key == $id_prerequisite && $action == 'edit') {
  7365. $selectPrerequisites->setSelected($key);
  7366. }
  7367. }
  7368. }
  7369. $form->addButtonSave(get_lang('Ok'), 'submit_button');
  7370. if ($action == 'move') {
  7371. $form->addHidden('title', $item_title);
  7372. $form->addHidden('description', $item_description);
  7373. }
  7374. if (is_numeric($extra_info)) {
  7375. $form->addHidden('path', $extra_info);
  7376. } elseif (is_array($extra_info)) {
  7377. $form->addHidden('path', $extra_info['path']);
  7378. }
  7379. $form->addHidden('type', TOOL_THREAD);
  7380. $form->addHidden('post_time', time());
  7381. $form->setDefaults($defaults);
  7382. return $form->returnForm();
  7383. }
  7384. /**
  7385. * Return the HTML form to display an item (generally a dir item).
  7386. *
  7387. * @param string $item_type
  7388. * @param string $title
  7389. * @param string $action
  7390. * @param int $id
  7391. * @param string $extra_info
  7392. *
  7393. * @throws Exception
  7394. * @throws HTML_QuickForm_Error
  7395. *
  7396. * @return string HTML form
  7397. */
  7398. public function display_item_form(
  7399. $item_type,
  7400. $title = '',
  7401. $action = 'add_item',
  7402. $id = 0,
  7403. $extra_info = 'new'
  7404. ) {
  7405. $_course = api_get_course_info();
  7406. global $charset;
  7407. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7408. $item_title = '';
  7409. $item_description = '';
  7410. $item_path_fck = '';
  7411. if ($id != 0 && is_array($extra_info)) {
  7412. $item_title = $extra_info['title'];
  7413. $item_description = $extra_info['description'];
  7414. $item_path = api_get_path(WEB_COURSE_PATH).$_course['path'].'/scorm/'.$this->path.'/'.stripslashes($extra_info['path']);
  7415. $item_path_fck = '/scorm/'.$this->path.'/'.stripslashes($extra_info['path']);
  7416. }
  7417. $parent = 0;
  7418. if ($id != 0 && is_array($extra_info)) {
  7419. $parent = $extra_info['parent_item_id'];
  7420. }
  7421. $id = (int) $id;
  7422. $sql = "SELECT * FROM $tbl_lp_item
  7423. WHERE
  7424. lp_id = ".$this->lp_id." AND
  7425. iid != $id";
  7426. if ($item_type == 'dir') {
  7427. $sql .= " AND parent_item_id = 0";
  7428. }
  7429. $result = Database::query($sql);
  7430. $arrLP = [];
  7431. while ($row = Database::fetch_array($result)) {
  7432. $arrLP[] = [
  7433. 'id' => $row['iid'],
  7434. 'item_type' => $row['item_type'],
  7435. 'title' => $this->cleanItemTitle($row['title']),
  7436. 'title_raw' => $row['title'],
  7437. 'path' => $row['path'],
  7438. 'description' => $row['description'],
  7439. 'parent_item_id' => $row['parent_item_id'],
  7440. 'previous_item_id' => $row['previous_item_id'],
  7441. 'next_item_id' => $row['next_item_id'],
  7442. 'max_score' => $row['max_score'],
  7443. 'min_score' => $row['min_score'],
  7444. 'mastery_score' => $row['mastery_score'],
  7445. 'prerequisite' => $row['prerequisite'],
  7446. 'display_order' => $row['display_order'],
  7447. ];
  7448. }
  7449. $this->tree_array($arrLP);
  7450. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7451. unset($this->arrMenu);
  7452. $url = api_get_self().'?'.api_get_cidreq().'&action='.$action.'&type='.$item_type.'&lp_id='.$this->lp_id;
  7453. $form = new FormValidator('form_'.$item_type, 'POST', $url);
  7454. $defaults['title'] = api_html_entity_decode(
  7455. $item_title,
  7456. ENT_QUOTES,
  7457. $charset
  7458. );
  7459. $defaults['description'] = $item_description;
  7460. $form->addHeader($title);
  7461. $arrHide[0]['value'] = Security::remove_XSS($this->name);
  7462. $arrHide[0]['padding'] = 20;
  7463. $charset = api_get_system_encoding();
  7464. for ($i = 0; $i < count($arrLP); $i++) {
  7465. if ($action != 'add') {
  7466. if ($arrLP[$i]['item_type'] === 'dir' && !in_array($arrLP[$i]['id'], $arrHide) &&
  7467. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7468. ) {
  7469. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7470. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7471. if ($parent == $arrLP[$i]['id']) {
  7472. $s_selected_parent = $arrHide[$arrLP[$i]['id']];
  7473. }
  7474. }
  7475. } else {
  7476. if ($arrLP[$i]['item_type'] === 'dir') {
  7477. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7478. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7479. if ($parent == $arrLP[$i]['id']) {
  7480. $s_selected_parent = $arrHide[$arrLP[$i]['id']];
  7481. }
  7482. }
  7483. }
  7484. }
  7485. if ($action != 'move') {
  7486. $this->setItemTitle($form);
  7487. } else {
  7488. $form->addElement('hidden', 'title');
  7489. }
  7490. $parentSelect = $form->addElement(
  7491. 'select',
  7492. 'parent',
  7493. get_lang('Parent'),
  7494. '',
  7495. [
  7496. 'id' => 'idParent',
  7497. 'onchange' => 'javascript: load_cbo(this.value);',
  7498. ]
  7499. );
  7500. foreach ($arrHide as $key => $value) {
  7501. $parentSelect->addOption(
  7502. $value['value'],
  7503. $key,
  7504. 'style="padding-left:'.$value['padding'].'px;"'
  7505. );
  7506. $lastPosition = $key;
  7507. }
  7508. if (!empty($s_selected_parent)) {
  7509. $parentSelect->setSelected($s_selected_parent);
  7510. }
  7511. if (is_array($arrLP)) {
  7512. reset($arrLP);
  7513. }
  7514. $arrHide = [];
  7515. // POSITION
  7516. for ($i = 0; $i < count($arrLP); $i++) {
  7517. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id &&
  7518. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM) {
  7519. //this is the same!
  7520. if (isset($extra_info['previous_item_id']) &&
  7521. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7522. ) {
  7523. $s_selected_position = $arrLP[$i]['id'];
  7524. } elseif ($action == 'add') {
  7525. $s_selected_position = $arrLP[$i]['id'];
  7526. }
  7527. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  7528. }
  7529. }
  7530. $position = $form->addElement(
  7531. 'select',
  7532. 'previous',
  7533. get_lang('Position'),
  7534. '',
  7535. ['id' => 'previous']
  7536. );
  7537. $padding = isset($value['padding']) ? $value['padding'] : 0;
  7538. $position->addOption(get_lang('FirstPosition'), 0, 'style="padding-left:'.$padding.'px;"');
  7539. $lastPosition = null;
  7540. foreach ($arrHide as $key => $value) {
  7541. $position->addOption($value['value'], $key, 'style="padding-left:'.$padding.'px;"');
  7542. $lastPosition = $key;
  7543. }
  7544. if (!empty($s_selected_position)) {
  7545. $position->setSelected($s_selected_position);
  7546. }
  7547. // When new chapter add at the end
  7548. if ($action === 'add_item') {
  7549. $position->setSelected($lastPosition);
  7550. }
  7551. if (is_array($arrLP)) {
  7552. reset($arrLP);
  7553. }
  7554. $form->addButtonSave(get_lang('SaveSection'), 'submit_button');
  7555. //fix in order to use the tab
  7556. if ($item_type === 'dir') {
  7557. $form->addElement('hidden', 'type', 'dir');
  7558. }
  7559. $extension = null;
  7560. if (!empty($item_path)) {
  7561. $extension = pathinfo($item_path, PATHINFO_EXTENSION);
  7562. }
  7563. //assets can't be modified
  7564. //$item_type == 'asset' ||
  7565. if (($item_type == 'sco') && ($extension == 'html' || $extension == 'htm')) {
  7566. if ($item_type == 'sco') {
  7567. $form->addElement(
  7568. 'html',
  7569. '<script>alert("'.get_lang('WarningWhenEditingScorm').'")</script>'
  7570. );
  7571. }
  7572. $renderer = $form->defaultRenderer();
  7573. $renderer->setElementTemplate(
  7574. '<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{label}<br />{element}',
  7575. 'content_lp'
  7576. );
  7577. $relative_prefix = '';
  7578. $editor_config = [
  7579. 'ToolbarSet' => 'LearningPathDocuments',
  7580. 'Width' => '100%',
  7581. 'Height' => '500',
  7582. 'FullPage' => true,
  7583. 'CreateDocumentDir' => $relative_prefix,
  7584. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/scorm/',
  7585. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().$item_path_fck,
  7586. ];
  7587. $form->addElement('html_editor', 'content_lp', '', null, $editor_config);
  7588. $content_path = api_get_path(SYS_COURSE_PATH).api_get_course_path().$item_path_fck;
  7589. $defaults['content_lp'] = file_get_contents($content_path);
  7590. }
  7591. if (!empty($id)) {
  7592. $form->addHidden('id', $id);
  7593. }
  7594. $form->addElement('hidden', 'type', $item_type);
  7595. $form->addElement('hidden', 'post_time', time());
  7596. $form->setDefaults($defaults);
  7597. return $form->returnForm();
  7598. }
  7599. /**
  7600. * @return string
  7601. */
  7602. public function getCurrentBuildingModeURL()
  7603. {
  7604. $pathItem = isset($_GET['path_item']) ? (int) $_GET['path_item'] : '';
  7605. $action = isset($_GET['action']) ? Security::remove_XSS($_GET['action']) : '';
  7606. $id = isset($_GET['id']) ? (int) $_GET['id'] : '';
  7607. $view = isset($_GET['view']) ? Security::remove_XSS($_GET['view']) : '';
  7608. $currentUrl = api_get_self().'?'.api_get_cidreq().
  7609. '&action='.$action.'&lp_id='.$this->lp_id.'&path_item='.$pathItem.'&view='.$view.'&id='.$id;
  7610. return $currentUrl;
  7611. }
  7612. /**
  7613. * Returns the form to update or create a document.
  7614. *
  7615. * @param string $action (add/edit)
  7616. * @param int $id ID of the lp_item (if already exists)
  7617. * @param mixed $extra_info Integer if document ID, string if info ('new')
  7618. *
  7619. * @throws Exception
  7620. * @throws HTML_QuickForm_Error
  7621. *
  7622. * @return string HTML form
  7623. */
  7624. public function display_document_form($action = 'add', $id = 0, $extra_info = 'new')
  7625. {
  7626. $course_id = api_get_course_int_id();
  7627. $_course = api_get_course_info();
  7628. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  7629. $no_display_edit_textarea = false;
  7630. $item_description = '';
  7631. //If action==edit document
  7632. //We don't display the document form if it's not an editable document (html or txt file)
  7633. if ($action === 'edit') {
  7634. if (is_array($extra_info)) {
  7635. $path_parts = pathinfo($extra_info['dir']);
  7636. if ($path_parts['extension'] != 'txt' && $path_parts['extension'] != 'html') {
  7637. $no_display_edit_textarea = true;
  7638. }
  7639. }
  7640. }
  7641. $no_display_add = false;
  7642. // If action==add an existing document
  7643. // We don't display the document form if it's not an editable document (html or txt file).
  7644. if ($action === 'add') {
  7645. if (is_numeric($extra_info)) {
  7646. $extra_info = (int) $extra_info;
  7647. $sql_doc = "SELECT path FROM $tbl_doc
  7648. WHERE c_id = $course_id AND iid = ".$extra_info;
  7649. $result = Database::query($sql_doc);
  7650. $path_file = Database::result($result, 0, 0);
  7651. $path_parts = pathinfo($path_file);
  7652. if ($path_parts['extension'] != 'txt' && $path_parts['extension'] != 'html') {
  7653. $no_display_add = true;
  7654. }
  7655. }
  7656. }
  7657. $item_title = '';
  7658. $item_description = '';
  7659. if ($id != 0 && is_array($extra_info)) {
  7660. $item_title = stripslashes($extra_info['title']);
  7661. $item_description = stripslashes($extra_info['description']);
  7662. if (empty($item_title)) {
  7663. $path_parts = pathinfo($extra_info['path']);
  7664. $item_title = stripslashes($path_parts['filename']);
  7665. }
  7666. } elseif (is_numeric($extra_info)) {
  7667. $sql = "SELECT path, title FROM $tbl_doc
  7668. WHERE
  7669. c_id = ".$course_id." AND
  7670. iid = ".intval($extra_info);
  7671. $result = Database::query($sql);
  7672. $row = Database::fetch_array($result);
  7673. $item_title = $row['title'];
  7674. $item_title = str_replace('_', ' ', $item_title);
  7675. if (empty($item_title)) {
  7676. $path_parts = pathinfo($row['path']);
  7677. $item_title = stripslashes($path_parts['filename']);
  7678. }
  7679. }
  7680. $return = '<legend>';
  7681. $parent = 0;
  7682. if ($id != 0 && is_array($extra_info)) {
  7683. $parent = $extra_info['parent_item_id'];
  7684. }
  7685. $arrLP = $this->getItemsForForm();
  7686. $this->tree_array($arrLP);
  7687. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7688. unset($this->arrMenu);
  7689. if ($action == 'add') {
  7690. $return .= get_lang('CreateTheDocument');
  7691. } elseif ($action == 'move') {
  7692. $return .= get_lang('MoveTheCurrentDocument');
  7693. } else {
  7694. $return .= get_lang('EditTheCurrentDocument');
  7695. }
  7696. $return .= '</legend>';
  7697. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  7698. $return .= Display::return_message(
  7699. '<strong>'.get_lang('Warning').' !</strong><br />'.get_lang('WarningEditingDocument'),
  7700. false
  7701. );
  7702. }
  7703. $form = new FormValidator(
  7704. 'form',
  7705. 'POST',
  7706. $this->getCurrentBuildingModeURL(),
  7707. '',
  7708. ['enctype' => 'multipart/form-data']
  7709. );
  7710. $defaults['title'] = Security::remove_XSS($item_title);
  7711. if (empty($item_title)) {
  7712. $defaults['title'] = Security::remove_XSS($item_title);
  7713. }
  7714. $defaults['description'] = $item_description;
  7715. $form->addElement('html', $return);
  7716. if ($action != 'move') {
  7717. $data = $this->generate_lp_folder($_course);
  7718. if ($action != 'edit') {
  7719. $folders = DocumentManager::get_all_document_folders(
  7720. $_course,
  7721. 0,
  7722. true
  7723. );
  7724. DocumentManager::build_directory_selector(
  7725. $folders,
  7726. '',
  7727. [],
  7728. true,
  7729. $form,
  7730. 'directory_parent_id'
  7731. );
  7732. }
  7733. if (isset($data['id'])) {
  7734. $defaults['directory_parent_id'] = $data['id'];
  7735. }
  7736. $this->setItemTitle($form);
  7737. }
  7738. $arrHide[0]['value'] = $this->name;
  7739. $arrHide[0]['padding'] = 20;
  7740. for ($i = 0; $i < count($arrLP); $i++) {
  7741. if ($action != 'add') {
  7742. if ($arrLP[$i]['item_type'] == 'dir' &&
  7743. !in_array($arrLP[$i]['id'], $arrHide) &&
  7744. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7745. ) {
  7746. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7747. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7748. }
  7749. } else {
  7750. if ($arrLP[$i]['item_type'] == 'dir') {
  7751. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7752. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7753. }
  7754. }
  7755. }
  7756. $parentSelect = $form->addSelect(
  7757. 'parent',
  7758. get_lang('Parent'),
  7759. [],
  7760. [
  7761. 'id' => 'idParent',
  7762. 'onchange' => 'javascript: load_cbo(this.value);',
  7763. ]
  7764. );
  7765. $my_count = 0;
  7766. foreach ($arrHide as $key => $value) {
  7767. if ($my_count != 0) {
  7768. // The LP name is also the first section and is not in the same charset like the other sections.
  7769. $value['value'] = Security::remove_XSS($value['value']);
  7770. $parentSelect->addOption(
  7771. $value['value'],
  7772. $key,
  7773. 'style="padding-left:'.$value['padding'].'px;"'
  7774. );
  7775. } else {
  7776. $value['value'] = Security::remove_XSS($value['value']);
  7777. $parentSelect->addOption(
  7778. $value['value'],
  7779. $key,
  7780. 'style="padding-left:'.$value['padding'].'px;"'
  7781. );
  7782. }
  7783. $my_count++;
  7784. }
  7785. if (!empty($id)) {
  7786. $parentSelect->setSelected($parent);
  7787. } else {
  7788. $parent_item_id = Session::read('parent_item_id', 0);
  7789. $parentSelect->setSelected($parent_item_id);
  7790. }
  7791. if (is_array($arrLP)) {
  7792. reset($arrLP);
  7793. }
  7794. $arrHide = [];
  7795. // POSITION
  7796. for ($i = 0; $i < count($arrLP); $i++) {
  7797. if (($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) ||
  7798. $arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM
  7799. ) {
  7800. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  7801. }
  7802. }
  7803. $selectedPosition = isset($extra_info['previous_item_id']) ? $extra_info['previous_item_id'] : 0;
  7804. $position = $form->addSelect(
  7805. 'previous',
  7806. get_lang('Position'),
  7807. [],
  7808. ['id' => 'previous']
  7809. );
  7810. $position->addOption(get_lang('FirstPosition'), 0);
  7811. foreach ($arrHide as $key => $value) {
  7812. $padding = isset($value['padding']) ? $value['padding'] : 20;
  7813. $position->addOption(
  7814. $value['value'],
  7815. $key,
  7816. 'style="padding-left:'.$padding.'px;"'
  7817. );
  7818. }
  7819. $position->setSelected($selectedPosition);
  7820. if (is_array($arrLP)) {
  7821. reset($arrLP);
  7822. }
  7823. if ($action != 'move') {
  7824. $arrHide = [];
  7825. for ($i = 0; $i < count($arrLP); $i++) {
  7826. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir' &&
  7827. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM
  7828. ) {
  7829. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7830. }
  7831. }
  7832. if (!$no_display_add) {
  7833. $item_type = isset($extra_info['item_type']) ? $extra_info['item_type'] : null;
  7834. $edit = isset($_GET['edit']) ? $_GET['edit'] : null;
  7835. if ($extra_info == 'new' || $item_type == TOOL_DOCUMENT ||
  7836. $item_type == TOOL_LP_FINAL_ITEM || $edit == 'true'
  7837. ) {
  7838. if (isset($_POST['content'])) {
  7839. $content = stripslashes($_POST['content']);
  7840. } elseif (is_array($extra_info)) {
  7841. //If it's an html document or a text file
  7842. if (!$no_display_edit_textarea) {
  7843. $content = $this->display_document(
  7844. $extra_info['path'],
  7845. false,
  7846. false
  7847. );
  7848. }
  7849. } elseif (is_numeric($extra_info)) {
  7850. $content = $this->display_document(
  7851. $extra_info,
  7852. false,
  7853. false
  7854. );
  7855. } else {
  7856. $content = '';
  7857. }
  7858. if (!$no_display_edit_textarea) {
  7859. // We need to calculate here some specific settings for the online editor.
  7860. // The calculated settings work for documents in the Documents tool
  7861. // (on the root or in subfolders).
  7862. // For documents in native scorm packages it is unclear whether the
  7863. // online editor should be activated or not.
  7864. // A new document, it is in the root of the repository.
  7865. $relative_path = '';
  7866. $relative_prefix = '';
  7867. if (is_array($extra_info) && $extra_info != 'new') {
  7868. // The document already exists. Whe have to determine its relative path towards the repository root.
  7869. $relative_path = explode('/', $extra_info['dir']);
  7870. $cnt = count($relative_path) - 2;
  7871. if ($cnt < 0) {
  7872. $cnt = 0;
  7873. }
  7874. $relative_prefix = str_repeat('../', $cnt);
  7875. $relative_path = array_slice($relative_path, 1, $cnt);
  7876. $relative_path = implode('/', $relative_path);
  7877. if (strlen($relative_path) > 0) {
  7878. $relative_path = $relative_path.'/';
  7879. }
  7880. } else {
  7881. $result = $this->generate_lp_folder($_course);
  7882. $relative_path = api_substr($result['dir'], 1, strlen($result['dir']));
  7883. $relative_prefix = '../../';
  7884. }
  7885. $editor_config = [
  7886. 'ToolbarSet' => 'LearningPathDocuments',
  7887. 'Width' => '100%',
  7888. 'Height' => '500',
  7889. 'FullPage' => true,
  7890. 'CreateDocumentDir' => $relative_prefix,
  7891. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/',
  7892. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/'.$relative_path,
  7893. ];
  7894. if ($_GET['action'] == 'add_item') {
  7895. $class = 'add';
  7896. $text = get_lang('LPCreateDocument');
  7897. } else {
  7898. if ($_GET['action'] == 'edit_item') {
  7899. $class = 'save';
  7900. $text = get_lang('SaveDocument');
  7901. }
  7902. }
  7903. $form->addButtonSave($text, 'submit_button');
  7904. $renderer = $form->defaultRenderer();
  7905. $renderer->setElementTemplate('&nbsp;{label}{element}', 'content_lp');
  7906. $form->addElement('html', '<div class="editor-lp">');
  7907. $form->addHtmlEditor('content_lp', null, null, true, $editor_config, true);
  7908. $form->addElement('html', '</div>');
  7909. $defaults['content_lp'] = $content;
  7910. }
  7911. } elseif (is_numeric($extra_info)) {
  7912. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  7913. $return = $this->display_document($extra_info, true, true, true);
  7914. $form->addElement('html', $return);
  7915. }
  7916. }
  7917. }
  7918. if (isset($extra_info['item_type']) &&
  7919. $extra_info['item_type'] == TOOL_LP_FINAL_ITEM
  7920. ) {
  7921. $parentSelect->freeze();
  7922. $position->freeze();
  7923. }
  7924. if ($action == 'move') {
  7925. $form->addElement('hidden', 'title', $item_title);
  7926. $form->addElement('hidden', 'description', $item_description);
  7927. }
  7928. if (is_numeric($extra_info)) {
  7929. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  7930. $form->addElement('hidden', 'path', $extra_info);
  7931. } elseif (is_array($extra_info)) {
  7932. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  7933. $form->addElement('hidden', 'path', $extra_info['path']);
  7934. }
  7935. $form->addElement('hidden', 'type', TOOL_DOCUMENT);
  7936. $form->addElement('hidden', 'post_time', time());
  7937. $form->setDefaults($defaults);
  7938. return $form->returnForm();
  7939. }
  7940. /**
  7941. * Returns the form to update or create a read-out text.
  7942. *
  7943. * @param string $action "add" or "edit"
  7944. * @param int $id ID of the lp_item (if already exists)
  7945. * @param mixed $extra_info Integer if document ID, string if info ('new')
  7946. *
  7947. * @throws Exception
  7948. * @throws HTML_QuickForm_Error
  7949. *
  7950. * @return string HTML form
  7951. */
  7952. public function displayFrmReadOutText($action = 'add', $id = 0, $extra_info = 'new')
  7953. {
  7954. $course_id = api_get_course_int_id();
  7955. $_course = api_get_course_info();
  7956. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  7957. $no_display_edit_textarea = false;
  7958. $item_description = '';
  7959. //If action==edit document
  7960. //We don't display the document form if it's not an editable document (html or txt file)
  7961. if ($action == 'edit') {
  7962. if (is_array($extra_info)) {
  7963. $path_parts = pathinfo($extra_info['dir']);
  7964. if ($path_parts['extension'] != "txt" && $path_parts['extension'] != "html") {
  7965. $no_display_edit_textarea = true;
  7966. }
  7967. }
  7968. }
  7969. $no_display_add = false;
  7970. $item_title = '';
  7971. $item_description = '';
  7972. if ($id != 0 && is_array($extra_info)) {
  7973. $item_title = stripslashes($extra_info['title']);
  7974. $item_description = stripslashes($extra_info['description']);
  7975. $item_terms = stripslashes($extra_info['terms']);
  7976. if (empty($item_title)) {
  7977. $path_parts = pathinfo($extra_info['path']);
  7978. $item_title = stripslashes($path_parts['filename']);
  7979. }
  7980. } elseif (is_numeric($extra_info)) {
  7981. $sql = "SELECT path, title FROM $tbl_doc WHERE c_id = ".$course_id." AND iid = ".intval($extra_info);
  7982. $result = Database::query($sql);
  7983. $row = Database::fetch_array($result);
  7984. $item_title = $row['title'];
  7985. $item_title = str_replace('_', ' ', $item_title);
  7986. if (empty($item_title)) {
  7987. $path_parts = pathinfo($row['path']);
  7988. $item_title = stripslashes($path_parts['filename']);
  7989. }
  7990. }
  7991. $parent = 0;
  7992. if ($id != 0 && is_array($extra_info)) {
  7993. $parent = $extra_info['parent_item_id'];
  7994. }
  7995. $arrLP = $this->getItemsForForm();
  7996. $this->tree_array($arrLP);
  7997. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7998. unset($this->arrMenu);
  7999. if ($action === 'add') {
  8000. $formHeader = get_lang('CreateTheDocument');
  8001. } else {
  8002. $formHeader = get_lang('EditTheCurrentDocument');
  8003. }
  8004. if ('edit' === $action) {
  8005. $urlAudioIcon = Display::url(
  8006. Display::return_icon('audio.png', get_lang('CreateReadOutText'), [], ICON_SIZE_TINY),
  8007. api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq().'&lp_id='.$this->lp_id.'&'
  8008. .http_build_query(['view' => 'build', 'id' => $id, 'action' => 'add_audio'])
  8009. );
  8010. } else {
  8011. $urlAudioIcon = Display::return_icon('audio.png', get_lang('CreateReadOutText'), [], ICON_SIZE_TINY);
  8012. }
  8013. $form = new FormValidator(
  8014. 'frm_add_reading',
  8015. 'POST',
  8016. $this->getCurrentBuildingModeURL(),
  8017. '',
  8018. ['enctype' => 'multipart/form-data']
  8019. );
  8020. $form->addHeader($formHeader);
  8021. $form->addHtml(
  8022. Display::return_message(
  8023. sprintf(get_lang('FrmReadOutTextIntro'), $urlAudioIcon),
  8024. 'normal',
  8025. false
  8026. )
  8027. );
  8028. $defaults['title'] = !empty($item_title) ? Security::remove_XSS($item_title) : '';
  8029. $defaults['description'] = $item_description;
  8030. $data = $this->generate_lp_folder($_course);
  8031. if ($action != 'edit') {
  8032. $folders = DocumentManager::get_all_document_folders($_course, 0, true);
  8033. DocumentManager::build_directory_selector(
  8034. $folders,
  8035. '',
  8036. [],
  8037. true,
  8038. $form,
  8039. 'directory_parent_id'
  8040. );
  8041. }
  8042. if (isset($data['id'])) {
  8043. $defaults['directory_parent_id'] = $data['id'];
  8044. }
  8045. $this->setItemTitle($form);
  8046. $arrHide[0]['value'] = $this->name;
  8047. $arrHide[0]['padding'] = 20;
  8048. for ($i = 0; $i < count($arrLP); $i++) {
  8049. if ($action != 'add') {
  8050. if ($arrLP[$i]['item_type'] == 'dir' &&
  8051. !in_array($arrLP[$i]['id'], $arrHide) &&
  8052. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8053. ) {
  8054. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8055. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  8056. }
  8057. } else {
  8058. if ($arrLP[$i]['item_type'] == 'dir') {
  8059. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8060. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  8061. }
  8062. }
  8063. }
  8064. $parent_select = $form->addSelect(
  8065. 'parent',
  8066. get_lang('Parent'),
  8067. [],
  8068. ['onchange' => "javascript: load_cbo(this.value, 'frm_add_reading_previous');"]
  8069. );
  8070. $my_count = 0;
  8071. foreach ($arrHide as $key => $value) {
  8072. if ($my_count != 0) {
  8073. // The LP name is also the first section and is not in the same charset like the other sections.
  8074. $value['value'] = Security::remove_XSS($value['value']);
  8075. $parent_select->addOption(
  8076. $value['value'],
  8077. $key,
  8078. 'style="padding-left:'.$value['padding'].'px;"'
  8079. );
  8080. } else {
  8081. $value['value'] = Security::remove_XSS($value['value']);
  8082. $parent_select->addOption(
  8083. $value['value'],
  8084. $key,
  8085. 'style="padding-left:'.$value['padding'].'px;"'
  8086. );
  8087. }
  8088. $my_count++;
  8089. }
  8090. if (!empty($id)) {
  8091. $parent_select->setSelected($parent);
  8092. } else {
  8093. $parent_item_id = Session::read('parent_item_id', 0);
  8094. $parent_select->setSelected($parent_item_id);
  8095. }
  8096. if (is_array($arrLP)) {
  8097. reset($arrLP);
  8098. }
  8099. $arrHide = [];
  8100. $s_selected_position = null;
  8101. // POSITION
  8102. $lastPosition = null;
  8103. for ($i = 0; $i < count($arrLP); $i++) {
  8104. if (($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) &&
  8105. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM
  8106. ) {
  8107. if ((isset($extra_info['previous_item_id']) &&
  8108. $extra_info['previous_item_id'] == $arrLP[$i]['id']) || $action == 'add'
  8109. ) {
  8110. $s_selected_position = $arrLP[$i]['id'];
  8111. }
  8112. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  8113. }
  8114. $lastPosition = $arrLP[$i]['id'];
  8115. }
  8116. if (empty($s_selected_position)) {
  8117. $s_selected_position = $lastPosition;
  8118. }
  8119. $position = $form->addSelect(
  8120. 'previous',
  8121. get_lang('Position'),
  8122. []
  8123. );
  8124. $position->addOption(get_lang('FirstPosition'), 0);
  8125. foreach ($arrHide as $key => $value) {
  8126. $padding = isset($value['padding']) ? $value['padding'] : 20;
  8127. $position->addOption(
  8128. $value['value'],
  8129. $key,
  8130. 'style="padding-left:'.$padding.'px;"'
  8131. );
  8132. }
  8133. $position->setSelected($s_selected_position);
  8134. if (is_array($arrLP)) {
  8135. reset($arrLP);
  8136. }
  8137. $arrHide = [];
  8138. for ($i = 0; $i < count($arrLP); $i++) {
  8139. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir' &&
  8140. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM
  8141. ) {
  8142. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8143. }
  8144. }
  8145. if (!$no_display_add) {
  8146. $item_type = isset($extra_info['item_type']) ? $extra_info['item_type'] : null;
  8147. $edit = isset($_GET['edit']) ? $_GET['edit'] : null;
  8148. if ($extra_info == 'new' || $item_type == TOOL_READOUT_TEXT || $edit == 'true') {
  8149. if (!$no_display_edit_textarea) {
  8150. $content = '';
  8151. if (isset($_POST['content'])) {
  8152. $content = stripslashes($_POST['content']);
  8153. } elseif (is_array($extra_info)) {
  8154. $content = $this->display_document($extra_info['path'], false, false);
  8155. } elseif (is_numeric($extra_info)) {
  8156. $content = $this->display_document($extra_info, false, false);
  8157. }
  8158. // A new document, it is in the root of the repository.
  8159. if (is_array($extra_info) && $extra_info != 'new') {
  8160. } else {
  8161. $this->generate_lp_folder($_course);
  8162. }
  8163. if ($_GET['action'] == 'add_item') {
  8164. $text = get_lang('LPCreateDocument');
  8165. } else {
  8166. $text = get_lang('SaveDocument');
  8167. }
  8168. $form->addTextarea('content_lp', get_lang('Content'), ['rows' => 20]);
  8169. $form
  8170. ->defaultRenderer()
  8171. ->setElementTemplate($form->getDefaultElementTemplate(), 'content_lp');
  8172. $form->addButtonSave($text, 'submit_button');
  8173. $defaults['content_lp'] = $content;
  8174. }
  8175. } elseif (is_numeric($extra_info)) {
  8176. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  8177. $return = $this->display_document($extra_info, true, true, true);
  8178. $form->addElement('html', $return);
  8179. }
  8180. }
  8181. if (is_numeric($extra_info)) {
  8182. $form->addElement('hidden', 'path', $extra_info);
  8183. } elseif (is_array($extra_info)) {
  8184. $form->addElement('hidden', 'path', $extra_info['path']);
  8185. }
  8186. $form->addElement('hidden', 'type', TOOL_READOUT_TEXT);
  8187. $form->addElement('hidden', 'post_time', time());
  8188. $form->setDefaults($defaults);
  8189. return $form->returnForm();
  8190. }
  8191. /**
  8192. * @param array $courseInfo
  8193. * @param string $content
  8194. * @param string $title
  8195. * @param int $parentId
  8196. *
  8197. * @throws \Doctrine\ORM\ORMException
  8198. * @throws \Doctrine\ORM\OptimisticLockException
  8199. * @throws \Doctrine\ORM\TransactionRequiredException
  8200. *
  8201. * @return int
  8202. */
  8203. public function createReadOutText($courseInfo, $content = '', $title = '', $parentId = 0)
  8204. {
  8205. $creatorId = api_get_user_id();
  8206. $sessionId = api_get_session_id();
  8207. // Generates folder
  8208. $result = $this->generate_lp_folder($courseInfo);
  8209. $dir = $result['dir'];
  8210. if (empty($parentId) || $parentId == '/') {
  8211. $postDir = isset($_POST['dir']) ? $_POST['dir'] : $dir;
  8212. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir; // Please, do not modify this dirname formatting.
  8213. if ($parentId === '/') {
  8214. $dir = '/';
  8215. }
  8216. // Please, do not modify this dirname formatting.
  8217. if (strstr($dir, '..')) {
  8218. $dir = '/';
  8219. }
  8220. if (!empty($dir[0]) && $dir[0] == '.') {
  8221. $dir = substr($dir, 1);
  8222. }
  8223. if (!empty($dir[0]) && $dir[0] != '/') {
  8224. $dir = '/'.$dir;
  8225. }
  8226. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  8227. $dir .= '/';
  8228. }
  8229. } else {
  8230. $parentInfo = DocumentManager::get_document_data_by_id(
  8231. $parentId,
  8232. $courseInfo['code']
  8233. );
  8234. if (!empty($parentInfo)) {
  8235. $dir = $parentInfo['path'].'/';
  8236. }
  8237. }
  8238. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  8239. if (!is_dir($filepath)) {
  8240. $dir = '/';
  8241. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  8242. }
  8243. $originalTitle = !empty($title) ? $title : $_POST['title'];
  8244. if (!empty($title)) {
  8245. $title = api_replace_dangerous_char(stripslashes($title));
  8246. } else {
  8247. $title = api_replace_dangerous_char(stripslashes($_POST['title']));
  8248. }
  8249. $title = disable_dangerous_file($title);
  8250. $filename = $title;
  8251. $content = !empty($content) ? $content : $_POST['content_lp'];
  8252. $tmpFileName = $filename;
  8253. $i = 0;
  8254. while (file_exists($filepath.$tmpFileName.'.html')) {
  8255. $tmpFileName = $filename.'_'.++$i;
  8256. }
  8257. $filename = $tmpFileName.'.html';
  8258. $content = stripslashes($content);
  8259. if (file_exists($filepath.$filename)) {
  8260. return 0;
  8261. }
  8262. $putContent = file_put_contents($filepath.$filename, $content);
  8263. if ($putContent === false) {
  8264. return 0;
  8265. }
  8266. $fileSize = filesize($filepath.$filename);
  8267. $saveFilePath = $dir.$filename;
  8268. $documentId = add_document(
  8269. $courseInfo,
  8270. $saveFilePath,
  8271. 'file',
  8272. $fileSize,
  8273. $tmpFileName,
  8274. '',
  8275. 0, //readonly
  8276. true,
  8277. null,
  8278. $sessionId,
  8279. $creatorId
  8280. );
  8281. if (!$documentId) {
  8282. return 0;
  8283. }
  8284. api_item_property_update(
  8285. $courseInfo,
  8286. TOOL_DOCUMENT,
  8287. $documentId,
  8288. 'DocumentAdded',
  8289. $creatorId,
  8290. null,
  8291. null,
  8292. null,
  8293. null,
  8294. $sessionId
  8295. );
  8296. $newComment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
  8297. $newTitle = $originalTitle;
  8298. if ($newComment || $newTitle) {
  8299. $em = Database::getManager();
  8300. /** @var CDocument $doc */
  8301. $doc = $em->find('ChamiloCourseBundle:CDocument', $documentId);
  8302. if ($newComment) {
  8303. $doc->setComment($newComment);
  8304. }
  8305. if ($newTitle) {
  8306. $doc->setTitle($newTitle);
  8307. }
  8308. $em->persist($doc);
  8309. $em->flush();
  8310. }
  8311. return $documentId;
  8312. }
  8313. /**
  8314. * Return HTML form to add/edit a link item.
  8315. *
  8316. * @param string $action (add/edit)
  8317. * @param int $id Item ID if exists
  8318. * @param mixed $extra_info
  8319. *
  8320. * @throws Exception
  8321. * @throws HTML_QuickForm_Error
  8322. *
  8323. * @return string HTML form
  8324. */
  8325. public function display_link_form($action = 'add', $id = 0, $extra_info = '')
  8326. {
  8327. $course_id = api_get_course_int_id();
  8328. $tbl_link = Database::get_course_table(TABLE_LINK);
  8329. $item_title = '';
  8330. $item_description = '';
  8331. $item_url = '';
  8332. if ($id != 0 && is_array($extra_info)) {
  8333. $item_title = stripslashes($extra_info['title']);
  8334. $item_description = stripslashes($extra_info['description']);
  8335. $item_url = stripslashes($extra_info['url']);
  8336. } elseif (is_numeric($extra_info)) {
  8337. $extra_info = (int) $extra_info;
  8338. $sql = "SELECT title, description, url
  8339. FROM $tbl_link
  8340. WHERE c_id = $course_id AND iid = $extra_info";
  8341. $result = Database::query($sql);
  8342. $row = Database::fetch_array($result);
  8343. $item_title = $row['title'];
  8344. $item_description = $row['description'];
  8345. $item_url = $row['url'];
  8346. }
  8347. $form = new FormValidator(
  8348. 'edit_link',
  8349. 'POST',
  8350. $this->getCurrentBuildingModeURL()
  8351. );
  8352. $defaults = [];
  8353. $parent = 0;
  8354. if ($id != 0 && is_array($extra_info)) {
  8355. $parent = $extra_info['parent_item_id'];
  8356. }
  8357. $arrLP = $this->getItemsForForm();
  8358. $this->tree_array($arrLP);
  8359. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  8360. unset($this->arrMenu);
  8361. if ($action == 'add') {
  8362. $legend = get_lang('CreateTheLink');
  8363. } elseif ($action == 'move') {
  8364. $legend = get_lang('MoveCurrentLink');
  8365. } else {
  8366. $legend = get_lang('EditCurrentLink');
  8367. }
  8368. $form->addHeader($legend);
  8369. if ($action != 'move') {
  8370. $this->setItemTitle($form);
  8371. $defaults['title'] = $item_title;
  8372. }
  8373. $selectParent = $form->addSelect(
  8374. 'parent',
  8375. get_lang('Parent'),
  8376. [],
  8377. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);', 'class' => 'learnpath_item_form']
  8378. );
  8379. $selectParent->addOption($this->name, 0);
  8380. $arrHide = [
  8381. $id,
  8382. ];
  8383. $parent_item_id = Session::read('parent_item_id', 0);
  8384. for ($i = 0; $i < count($arrLP); $i++) {
  8385. if ($action != 'add') {
  8386. if (
  8387. ($arrLP[$i]['item_type'] == 'dir') &&
  8388. !in_array($arrLP[$i]['id'], $arrHide) &&
  8389. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8390. ) {
  8391. $selectParent->addOption(
  8392. $arrLP[$i]['title'],
  8393. $arrLP[$i]['id'],
  8394. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px;']
  8395. );
  8396. if ($parent == $arrLP[$i]['id']) {
  8397. $selectParent->setSelected($arrLP[$i]['id']);
  8398. }
  8399. } else {
  8400. $arrHide[] = $arrLP[$i]['id'];
  8401. }
  8402. } else {
  8403. if ($arrLP[$i]['item_type'] == 'dir') {
  8404. $selectParent->addOption(
  8405. $arrLP[$i]['title'],
  8406. $arrLP[$i]['id'],
  8407. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  8408. );
  8409. if ($parent_item_id == $arrLP[$i]['id']) {
  8410. $selectParent->setSelected($arrLP[$i]['id']);
  8411. }
  8412. }
  8413. }
  8414. }
  8415. if (is_array($arrLP)) {
  8416. reset($arrLP);
  8417. }
  8418. $selectPrevious = $form->addSelect(
  8419. 'previous',
  8420. get_lang('Position'),
  8421. [],
  8422. ['id' => 'previous', 'class' => 'learnpath_item_form']
  8423. );
  8424. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  8425. for ($i = 0; $i < count($arrLP); $i++) {
  8426. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  8427. $selectPrevious->addOption(
  8428. $arrLP[$i]['title'],
  8429. $arrLP[$i]['id']
  8430. );
  8431. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  8432. $selectPrevious->setSelected($arrLP[$i]['id']);
  8433. } elseif ($action == 'add') {
  8434. $selectPrevious->setSelected($arrLP[$i]['id']);
  8435. }
  8436. }
  8437. }
  8438. if ($action != 'move') {
  8439. $urlAttributes = ['class' => 'learnpath_item_form'];
  8440. if (is_numeric($extra_info)) {
  8441. $urlAttributes['disabled'] = 'disabled';
  8442. }
  8443. $form->addElement('url', 'url', get_lang('Url'), $urlAttributes);
  8444. $defaults['url'] = $item_url;
  8445. $arrHide = [];
  8446. for ($i = 0; $i < count($arrLP); $i++) {
  8447. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  8448. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8449. }
  8450. }
  8451. }
  8452. if ($action == 'add') {
  8453. $form->addButtonSave(get_lang('AddLinkToCourse'), 'submit_button');
  8454. } else {
  8455. $form->addButtonSave(get_lang('EditCurrentLink'), 'submit_button');
  8456. }
  8457. if ($action == 'move') {
  8458. $form->addHidden('title', $item_title);
  8459. $form->addHidden('description', $item_description);
  8460. }
  8461. if (is_numeric($extra_info)) {
  8462. $form->addHidden('path', $extra_info);
  8463. } elseif (is_array($extra_info)) {
  8464. $form->addHidden('path', $extra_info['path']);
  8465. }
  8466. $form->addHidden('type', TOOL_LINK);
  8467. $form->addHidden('post_time', time());
  8468. $form->setDefaults($defaults);
  8469. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  8470. }
  8471. /**
  8472. * Return HTML form to add/edit a student publication (work).
  8473. *
  8474. * @param string $action
  8475. * @param int $id Item ID if already exists
  8476. * @param string $extra_info
  8477. *
  8478. * @throws Exception
  8479. *
  8480. * @return string HTML form
  8481. */
  8482. public function display_student_publication_form(
  8483. $action = 'add',
  8484. $id = 0,
  8485. $extra_info = ''
  8486. ) {
  8487. $course_id = api_get_course_int_id();
  8488. $tbl_publication = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  8489. $item_title = get_lang('Student_publication');
  8490. if ($id != 0 && is_array($extra_info)) {
  8491. $item_title = stripslashes($extra_info['title']);
  8492. $item_description = stripslashes($extra_info['description']);
  8493. } elseif (is_numeric($extra_info)) {
  8494. $extra_info = (int) $extra_info;
  8495. $sql = "SELECT title, description
  8496. FROM $tbl_publication
  8497. WHERE c_id = $course_id AND id = ".$extra_info;
  8498. $result = Database::query($sql);
  8499. $row = Database::fetch_array($result);
  8500. if ($row) {
  8501. $item_title = $row['title'];
  8502. }
  8503. }
  8504. $parent = 0;
  8505. if ($id != 0 && is_array($extra_info)) {
  8506. $parent = $extra_info['parent_item_id'];
  8507. }
  8508. $arrLP = $this->getItemsForForm();
  8509. $this->tree_array($arrLP);
  8510. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  8511. unset($this->arrMenu);
  8512. $form = new FormValidator('frm_student_publication', 'post', '#');
  8513. if ($action == 'add') {
  8514. $form->addHeader(get_lang('Student_publication'));
  8515. } elseif ($action == 'move') {
  8516. $form->addHeader(get_lang('MoveCurrentStudentPublication'));
  8517. } else {
  8518. $form->addHeader(get_lang('EditCurrentStudentPublication'));
  8519. }
  8520. if ($action != 'move') {
  8521. $this->setItemTitle($form);
  8522. }
  8523. $parentSelect = $form->addSelect(
  8524. 'parent',
  8525. get_lang('Parent'),
  8526. ['0' => $this->name],
  8527. [
  8528. 'onchange' => 'javascript: load_cbo(this.value);',
  8529. 'class' => 'learnpath_item_form',
  8530. 'id' => 'idParent',
  8531. ]
  8532. );
  8533. $arrHide = [$id];
  8534. for ($i = 0; $i < count($arrLP); $i++) {
  8535. if ($action != 'add') {
  8536. if (
  8537. ($arrLP[$i]['item_type'] == 'dir') &&
  8538. !in_array($arrLP[$i]['id'], $arrHide) &&
  8539. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8540. ) {
  8541. $parentSelect->addOption(
  8542. $arrLP[$i]['title'],
  8543. $arrLP[$i]['id'],
  8544. ['style' => 'padding-left: '.(($arrLP[$i]['depth'] * 10) + 20).'px;']
  8545. );
  8546. if ($parent == $arrLP[$i]['id']) {
  8547. $parentSelect->setSelected($arrLP[$i]['id']);
  8548. }
  8549. } else {
  8550. $arrHide[] = $arrLP[$i]['id'];
  8551. }
  8552. } else {
  8553. if ($arrLP[$i]['item_type'] == 'dir') {
  8554. $parentSelect->addOption(
  8555. $arrLP[$i]['title'],
  8556. $arrLP[$i]['id'],
  8557. ['style' => 'padding-left: '.(($arrLP[$i]['depth'] * 10) + 20).'px;']
  8558. );
  8559. if ($parent == $arrLP[$i]['id']) {
  8560. $parentSelect->setSelected($arrLP[$i]['id']);
  8561. }
  8562. }
  8563. }
  8564. }
  8565. if (is_array($arrLP)) {
  8566. reset($arrLP);
  8567. }
  8568. $previousSelect = $form->addSelect(
  8569. 'previous',
  8570. get_lang('Position'),
  8571. ['0' => get_lang('FirstPosition')],
  8572. ['id' => 'previous', 'class' => 'learnpath_item_form']
  8573. );
  8574. for ($i = 0; $i < count($arrLP); $i++) {
  8575. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  8576. $previousSelect->addOption(
  8577. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  8578. $arrLP[$i]['id']
  8579. );
  8580. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  8581. $previousSelect->setSelected($arrLP[$i]['id']);
  8582. } elseif ($action == 'add') {
  8583. $previousSelect->setSelected($arrLP[$i]['id']);
  8584. }
  8585. }
  8586. }
  8587. if ($action == 'add') {
  8588. $form->addButtonCreate(get_lang('AddAssignmentToCourse'), 'submit_button');
  8589. } else {
  8590. $form->addButtonCreate(get_lang('EditCurrentStudentPublication'), 'submit_button');
  8591. }
  8592. if ($action == 'move') {
  8593. $form->addHidden('title', $item_title);
  8594. $form->addHidden('description', $item_description);
  8595. }
  8596. if (is_numeric($extra_info)) {
  8597. $form->addHidden('path', $extra_info);
  8598. } elseif (is_array($extra_info)) {
  8599. $form->addHidden('path', $extra_info['path']);
  8600. }
  8601. $form->addHidden('type', TOOL_STUDENTPUBLICATION);
  8602. $form->addHidden('post_time', time());
  8603. $form->setDefaults(['title' => $item_title]);
  8604. $return = '<div class="sectioncomment">';
  8605. $return .= $form->returnForm();
  8606. $return .= '</div>';
  8607. return $return;
  8608. }
  8609. /**
  8610. * Displays the menu for manipulating a step.
  8611. *
  8612. * @param id $item_id
  8613. * @param string $item_type
  8614. *
  8615. * @return string
  8616. */
  8617. public function display_manipulate($item_id, $item_type = TOOL_DOCUMENT)
  8618. {
  8619. $_course = api_get_course_info();
  8620. $course_code = api_get_course_id();
  8621. $item_id = (int) $item_id;
  8622. $return = '<div class="actions">';
  8623. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8624. $sql = "SELECT * FROM $tbl_lp_item
  8625. WHERE iid = ".$item_id;
  8626. $result = Database::query($sql);
  8627. $row = Database::fetch_assoc($result);
  8628. $audio_player = null;
  8629. // We display an audio player if needed.
  8630. if (!empty($row['audio'])) {
  8631. $webAudioPath = '../..'.api_get_path(REL_COURSE_PATH).$_course['path'].'/document/audio/'.$row['audio'];
  8632. $audio_player .= '<div class="lp_mediaplayer" id="container">'
  8633. .'<audio src="'.$webAudioPath.'" controls>'
  8634. .'</div><br>';
  8635. }
  8636. $url = api_get_self().'?'.api_get_cidreq().'&view=build&id='.$item_id.'&lp_id='.$this->lp_id;
  8637. if ($item_type != TOOL_LP_FINAL_ITEM) {
  8638. $return .= Display::url(
  8639. Display::return_icon(
  8640. 'edit.png',
  8641. get_lang('Edit'),
  8642. [],
  8643. ICON_SIZE_SMALL
  8644. ),
  8645. $url.'&action=edit_item&path_item='.$row['path']
  8646. );
  8647. $return .= Display::url(
  8648. Display::return_icon(
  8649. 'move.png',
  8650. get_lang('Move'),
  8651. [],
  8652. ICON_SIZE_SMALL
  8653. ),
  8654. $url.'&action=move_item'
  8655. );
  8656. }
  8657. // Commented for now as prerequisites cannot be added to chapters.
  8658. if ($item_type != 'dir') {
  8659. $return .= Display::url(
  8660. Display::return_icon(
  8661. 'accept.png',
  8662. get_lang('LearnpathPrerequisites'),
  8663. [],
  8664. ICON_SIZE_SMALL
  8665. ),
  8666. $url.'&action=edit_item_prereq'
  8667. );
  8668. }
  8669. $return .= Display::url(
  8670. Display::return_icon(
  8671. 'delete.png',
  8672. get_lang('Delete'),
  8673. [],
  8674. ICON_SIZE_SMALL
  8675. ),
  8676. $url.'&action=delete_item'
  8677. );
  8678. if (in_array($item_type, [TOOL_DOCUMENT, TOOL_LP_FINAL_ITEM, TOOL_HOTPOTATOES])) {
  8679. $documentData = DocumentManager::get_document_data_by_id($row['path'], $course_code);
  8680. if (empty($documentData)) {
  8681. // Try with iid
  8682. $table = Database::get_course_table(TABLE_DOCUMENT);
  8683. $sql = "SELECT path FROM $table
  8684. WHERE
  8685. c_id = ".api_get_course_int_id()." AND
  8686. iid = ".$row['path']." AND
  8687. path NOT LIKE '%_DELETED_%'";
  8688. $result = Database::query($sql);
  8689. $documentData = Database::fetch_array($result);
  8690. if ($documentData) {
  8691. $documentData['absolute_path_from_document'] = '/document'.$documentData['path'];
  8692. }
  8693. }
  8694. if (isset($documentData['absolute_path_from_document'])) {
  8695. $return .= get_lang('File').': '.$documentData['absolute_path_from_document'];
  8696. }
  8697. }
  8698. $return .= '</div>';
  8699. if (!empty($audio_player)) {
  8700. $return .= $audio_player;
  8701. }
  8702. return $return;
  8703. }
  8704. /**
  8705. * Creates the javascript needed for filling up the checkboxes without page reload.
  8706. *
  8707. * @return string
  8708. */
  8709. public function get_js_dropdown_array()
  8710. {
  8711. $course_id = api_get_course_int_id();
  8712. $return = 'var child_name = new Array();'."\n";
  8713. $return .= 'var child_value = new Array();'."\n\n";
  8714. $return .= 'child_name[0] = new Array();'."\n";
  8715. $return .= 'child_value[0] = new Array();'."\n\n";
  8716. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8717. $sql = "SELECT * FROM ".$tbl_lp_item."
  8718. WHERE
  8719. c_id = $course_id AND
  8720. lp_id = ".$this->lp_id." AND
  8721. parent_item_id = 0
  8722. ORDER BY display_order ASC";
  8723. $res_zero = Database::query($sql);
  8724. $i = 0;
  8725. $list = $this->getItemsForForm(true);
  8726. foreach ($list as $row_zero) {
  8727. if ($row_zero['item_type'] !== TOOL_LP_FINAL_ITEM) {
  8728. if ($row_zero['item_type'] == TOOL_QUIZ) {
  8729. $row_zero['title'] = Exercise::get_formated_title_variable($row_zero['title']);
  8730. }
  8731. $js_var = json_encode(get_lang('After').' '.$row_zero['title']);
  8732. $return .= 'child_name[0]['.$i.'] = '.$js_var.' ;'."\n";
  8733. $return .= 'child_value[0]['.$i++.'] = "'.$row_zero['iid'].'";'."\n";
  8734. }
  8735. }
  8736. $return .= "\n";
  8737. $sql = "SELECT * FROM $tbl_lp_item
  8738. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8739. $res = Database::query($sql);
  8740. while ($row = Database::fetch_array($res)) {
  8741. $sql_parent = "SELECT * FROM ".$tbl_lp_item."
  8742. WHERE
  8743. c_id = ".$course_id." AND
  8744. parent_item_id = ".$row['iid']."
  8745. ORDER BY display_order ASC";
  8746. $res_parent = Database::query($sql_parent);
  8747. $i = 0;
  8748. $return .= 'child_name['.$row['iid'].'] = new Array();'."\n";
  8749. $return .= 'child_value['.$row['iid'].'] = new Array();'."\n\n";
  8750. while ($row_parent = Database::fetch_array($res_parent)) {
  8751. $js_var = json_encode(get_lang('After').' '.$this->cleanItemTitle($row_parent['title']));
  8752. $return .= 'child_name['.$row['iid'].']['.$i.'] = '.$js_var.' ;'."\n";
  8753. $return .= 'child_value['.$row['iid'].']['.$i++.'] = "'.$row_parent['iid'].'";'."\n";
  8754. }
  8755. $return .= "\n";
  8756. }
  8757. $return .= "
  8758. function load_cbo(id) {
  8759. if (!id) {
  8760. return false;
  8761. }
  8762. var cbo = document.getElementById('previous');
  8763. for(var i = cbo.length - 1; i > 0; i--) {
  8764. cbo.options[i] = null;
  8765. }
  8766. var k=0;
  8767. for(var i = 1; i <= child_name[id].length; i++){
  8768. var option = new Option(child_name[id][i - 1], child_value[id][i - 1]);
  8769. option.style.paddingLeft = '40px';
  8770. cbo.options[i] = option;
  8771. k = i;
  8772. }
  8773. cbo.options[k].selected = true;
  8774. $('#previous').selectpicker('refresh');
  8775. }";
  8776. return $return;
  8777. }
  8778. /**
  8779. * Display the form to allow moving an item.
  8780. *
  8781. * @param int $item_id Item ID
  8782. *
  8783. * @throws Exception
  8784. * @throws HTML_QuickForm_Error
  8785. *
  8786. * @return string HTML form
  8787. */
  8788. public function display_move_item($item_id)
  8789. {
  8790. $return = '';
  8791. if (is_numeric($item_id)) {
  8792. $item_id = (int) $item_id;
  8793. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8794. $sql = "SELECT * FROM $tbl_lp_item
  8795. WHERE iid = $item_id";
  8796. $res = Database::query($sql);
  8797. $row = Database::fetch_array($res);
  8798. switch ($row['item_type']) {
  8799. case 'dir':
  8800. case 'asset':
  8801. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8802. $return .= $this->display_item_form(
  8803. $row['item_type'],
  8804. get_lang('MoveCurrentChapter'),
  8805. 'move',
  8806. $item_id,
  8807. $row
  8808. );
  8809. break;
  8810. case TOOL_DOCUMENT:
  8811. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8812. $return .= $this->display_document_form('move', $item_id, $row);
  8813. break;
  8814. case TOOL_LINK:
  8815. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8816. $return .= $this->display_link_form('move', $item_id, $row);
  8817. break;
  8818. case TOOL_HOTPOTATOES:
  8819. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8820. $return .= $this->display_link_form('move', $item_id, $row);
  8821. break;
  8822. case TOOL_QUIZ:
  8823. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8824. $return .= $this->display_quiz_form('move', $item_id, $row);
  8825. break;
  8826. case TOOL_STUDENTPUBLICATION:
  8827. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8828. $return .= $this->display_student_publication_form('move', $item_id, $row);
  8829. break;
  8830. case TOOL_FORUM:
  8831. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8832. $return .= $this->display_forum_form('move', $item_id, $row);
  8833. break;
  8834. case TOOL_THREAD:
  8835. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8836. $return .= $this->display_forum_form('move', $item_id, $row);
  8837. break;
  8838. }
  8839. }
  8840. return $return;
  8841. }
  8842. /**
  8843. * Return HTML form to allow prerequisites selection.
  8844. *
  8845. * @todo use FormValidator
  8846. *
  8847. * @param int Item ID
  8848. *
  8849. * @return string HTML form
  8850. */
  8851. public function display_item_prerequisites_form($item_id = 0)
  8852. {
  8853. $course_id = api_get_course_int_id();
  8854. $item_id = (int) $item_id;
  8855. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8856. /* Current prerequisite */
  8857. $sql = "SELECT * FROM $tbl_lp_item
  8858. WHERE iid = $item_id";
  8859. $result = Database::query($sql);
  8860. $row = Database::fetch_array($result);
  8861. $prerequisiteId = $row['prerequisite'];
  8862. $return = '<legend>';
  8863. $return .= get_lang('AddEditPrerequisites');
  8864. $return .= '</legend>';
  8865. $return .= '<form method="POST">';
  8866. $return .= '<div class="table-responsive">';
  8867. $return .= '<table class="table table-hover">';
  8868. $return .= '<thead>';
  8869. $return .= '<tr>';
  8870. $return .= '<th>'.get_lang('LearnpathPrerequisites').'</th>';
  8871. $return .= '<th width="140">'.get_lang('Minimum').'</th>';
  8872. $return .= '<th width="140">'.get_lang('Maximum').'</th>';
  8873. $return .= '</tr>';
  8874. $return .= '</thead>';
  8875. // Adding the none option to the prerequisites see http://www.chamilo.org/es/node/146
  8876. $return .= '<tbody>';
  8877. $return .= '<tr>';
  8878. $return .= '<td colspan="3">';
  8879. $return .= '<div class="radio learnpath"><label for="idNone">';
  8880. $return .= '<input checked="checked" id="idNone" name="prerequisites" type="radio" />';
  8881. $return .= get_lang('None').'</label>';
  8882. $return .= '</div>';
  8883. $return .= '</tr>';
  8884. $sql = "SELECT * FROM $tbl_lp_item
  8885. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8886. $result = Database::query($sql);
  8887. $selectedMinScore = [];
  8888. $selectedMaxScore = [];
  8889. $masteryScore = [];
  8890. while ($row = Database::fetch_array($result)) {
  8891. if ($row['iid'] == $item_id) {
  8892. $selectedMinScore[$row['prerequisite']] = $row['prerequisite_min_score'];
  8893. $selectedMaxScore[$row['prerequisite']] = $row['prerequisite_max_score'];
  8894. }
  8895. $masteryScore[$row['iid']] = $row['mastery_score'];
  8896. }
  8897. $arrLP = $this->getItemsForForm();
  8898. $this->tree_array($arrLP);
  8899. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  8900. unset($this->arrMenu);
  8901. for ($i = 0; $i < count($arrLP); $i++) {
  8902. $item = $arrLP[$i];
  8903. if ($item['id'] == $item_id) {
  8904. break;
  8905. }
  8906. $selectedMaxScoreValue = isset($selectedMaxScore[$item['id']]) ? $selectedMaxScore[$item['id']] : $item['max_score'];
  8907. $selectedMinScoreValue = isset($selectedMinScore[$item['id']]) ? $selectedMinScore[$item['id']] : 0;
  8908. $masteryScoreAsMinValue = isset($masteryScore[$item['id']]) ? $masteryScore[$item['id']] : 0;
  8909. $return .= '<tr>';
  8910. $return .= '<td '.(($item['item_type'] != TOOL_QUIZ && $item['item_type'] != TOOL_HOTPOTATOES) ? ' colspan="3"' : '').'>';
  8911. $return .= '<div style="margin-left:'.($item['depth'] * 20).'px;" class="radio learnpath">';
  8912. $return .= '<label for="id'.$item['id'].'">';
  8913. $return .= '<input'.(in_array($prerequisiteId, [$item['id'], $item['ref']]) ? ' checked="checked" ' : '').($item['item_type'] == 'dir' ? ' disabled="disabled" ' : ' ').'id="id'.$item['id'].'" name="prerequisites" type="radio" value="'.$item['id'].'" />';
  8914. $icon_name = str_replace(' ', '', $item['item_type']);
  8915. if (file_exists('../img/lp_'.$icon_name.'.png')) {
  8916. $return .= Display::return_icon('lp_'.$icon_name.'.png');
  8917. } else {
  8918. if (file_exists('../img/lp_'.$icon_name.'.png')) {
  8919. $return .= Display::return_icon('lp_'.$icon_name.'.png');
  8920. } else {
  8921. $return .= Display::return_icon('folder_document.png');
  8922. }
  8923. }
  8924. $return .= $item['title'].'</label>';
  8925. $return .= '</div>';
  8926. $return .= '</td>';
  8927. if ($item['item_type'] == TOOL_QUIZ) {
  8928. // lets update max_score Quiz information depending of the Quiz Advanced properties
  8929. $lpItemObj = new LpItem($course_id, $item['id']);
  8930. $exercise = new Exercise($course_id);
  8931. $exercise->read($lpItemObj->path);
  8932. $lpItemObj->max_score = $exercise->get_max_score();
  8933. $lpItemObj->update();
  8934. $item['max_score'] = $lpItemObj->max_score;
  8935. if (empty($selectedMinScoreValue) && !empty($masteryScoreAsMinValue)) {
  8936. // Backwards compatibility with 1.9.x use mastery_score as min value
  8937. $selectedMinScoreValue = $masteryScoreAsMinValue;
  8938. }
  8939. $return .= '<td>';
  8940. $return .= '<input
  8941. class="form-control"
  8942. size="4" maxlength="3"
  8943. name="min_'.$item['id'].'"
  8944. type="number"
  8945. min="0"
  8946. step="1"
  8947. max="'.$item['max_score'].'"
  8948. value="'.$selectedMinScoreValue.'"
  8949. />';
  8950. $return .= '</td>';
  8951. $return .= '<td>';
  8952. $return .= '<input
  8953. class="form-control"
  8954. size="4"
  8955. maxlength="3"
  8956. name="max_'.$item['id'].'"
  8957. type="number"
  8958. min="0"
  8959. step="1"
  8960. max="'.$item['max_score'].'"
  8961. value="'.$selectedMaxScoreValue.'"
  8962. />';
  8963. $return .= '</td>';
  8964. }
  8965. if ($item['item_type'] == TOOL_HOTPOTATOES) {
  8966. $return .= '<td>';
  8967. $return .= '<input
  8968. size="4"
  8969. maxlength="3"
  8970. name="min_'.$item['id'].'"
  8971. type="number"
  8972. min="0"
  8973. step="1"
  8974. max="'.$item['max_score'].'"
  8975. value="'.$selectedMinScoreValue.'"
  8976. />';
  8977. $return .= '</td>';
  8978. $return .= '<td>';
  8979. $return .= '<input
  8980. size="4"
  8981. maxlength="3"
  8982. name="max_'.$item['id'].'"
  8983. type="number"
  8984. min="0"
  8985. step="1"
  8986. max="'.$item['max_score'].'"
  8987. value="'.$selectedMaxScoreValue.'"
  8988. />';
  8989. $return .= '</td>';
  8990. }
  8991. $return .= '</tr>';
  8992. }
  8993. $return .= '<tr>';
  8994. $return .= '</tr>';
  8995. $return .= '</tbody>';
  8996. $return .= '</table>';
  8997. $return .= '</div>';
  8998. $return .= '<div class="form-group">';
  8999. $return .= '<button class="btn btn-primary" name="submit_button" type="submit">'.
  9000. get_lang('ModifyPrerequisites').'</button>';
  9001. $return .= '</form>';
  9002. return $return;
  9003. }
  9004. /**
  9005. * Return HTML list to allow prerequisites selection for lp.
  9006. *
  9007. * @return string HTML form
  9008. */
  9009. public function display_lp_prerequisites_list()
  9010. {
  9011. $course_id = api_get_course_int_id();
  9012. $lp_id = $this->lp_id;
  9013. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  9014. // get current prerequisite
  9015. $sql = "SELECT * FROM $tbl_lp WHERE iid = $lp_id ";
  9016. $result = Database::query($sql);
  9017. $row = Database::fetch_array($result);
  9018. $prerequisiteId = $row['prerequisite'];
  9019. $session_id = api_get_session_id();
  9020. $session_condition = api_get_session_condition($session_id, true, true);
  9021. $sql = "SELECT * FROM $tbl_lp
  9022. WHERE c_id = $course_id $session_condition
  9023. ORDER BY display_order ";
  9024. $rs = Database::query($sql);
  9025. $return = '';
  9026. $return .= '<select name="prerequisites" class="form-control">';
  9027. $return .= '<option value="0">'.get_lang('None').'</option>';
  9028. if (Database::num_rows($rs) > 0) {
  9029. while ($row = Database::fetch_array($rs)) {
  9030. if ($row['id'] == $lp_id) {
  9031. continue;
  9032. }
  9033. $return .= '<option value="'.$row['id'].'" '.(($row['id'] == $prerequisiteId) ? ' selected ' : '').'>'.$row['name'].'</option>';
  9034. }
  9035. }
  9036. $return .= '</select>';
  9037. return $return;
  9038. }
  9039. /**
  9040. * Creates a list with all the documents in it.
  9041. *
  9042. * @param bool $showInvisibleFiles
  9043. *
  9044. * @throws Exception
  9045. * @throws HTML_QuickForm_Error
  9046. *
  9047. * @return string
  9048. */
  9049. public function get_documents($showInvisibleFiles = false)
  9050. {
  9051. $course_info = api_get_course_info();
  9052. $sessionId = api_get_session_id();
  9053. $documentTree = DocumentManager::get_document_preview(
  9054. $course_info,
  9055. $this->lp_id,
  9056. null,
  9057. $sessionId,
  9058. true,
  9059. null,
  9060. null,
  9061. $showInvisibleFiles,
  9062. true
  9063. );
  9064. $headers = [
  9065. get_lang('Files'),
  9066. get_lang('CreateTheDocument'),
  9067. get_lang('CreateReadOutText'),
  9068. get_lang('Upload'),
  9069. ];
  9070. $form = new FormValidator(
  9071. 'form_upload',
  9072. 'POST',
  9073. $this->getCurrentBuildingModeURL(),
  9074. '',
  9075. ['enctype' => 'multipart/form-data']
  9076. );
  9077. $folders = DocumentManager::get_all_document_folders(
  9078. api_get_course_info(),
  9079. 0,
  9080. true
  9081. );
  9082. $lpPathInfo = $this->generate_lp_folder(api_get_course_info());
  9083. DocumentManager::build_directory_selector(
  9084. $folders,
  9085. $lpPathInfo['id'],
  9086. [],
  9087. true,
  9088. $form,
  9089. 'directory_parent_id'
  9090. );
  9091. $group = [
  9092. $form->createElement(
  9093. 'radio',
  9094. 'if_exists',
  9095. get_lang('UplWhatIfFileExists'),
  9096. get_lang('UplDoNothing'),
  9097. 'nothing'
  9098. ),
  9099. $form->createElement(
  9100. 'radio',
  9101. 'if_exists',
  9102. null,
  9103. get_lang('UplOverwriteLong'),
  9104. 'overwrite'
  9105. ),
  9106. $form->createElement(
  9107. 'radio',
  9108. 'if_exists',
  9109. null,
  9110. get_lang('UplRenameLong'),
  9111. 'rename'
  9112. ),
  9113. ];
  9114. $form->addGroup($group, null, get_lang('UplWhatIfFileExists'));
  9115. $fileExistsOption = api_get_setting('document_if_file_exists_option');
  9116. $defaultFileExistsOption = 'rename';
  9117. if (!empty($fileExistsOption)) {
  9118. $defaultFileExistsOption = $fileExistsOption;
  9119. }
  9120. $form->setDefaults(['if_exists' => $defaultFileExistsOption]);
  9121. // Check box options
  9122. $form->addElement(
  9123. 'checkbox',
  9124. 'unzip',
  9125. get_lang('Options'),
  9126. get_lang('Uncompress')
  9127. );
  9128. $url = api_get_path(WEB_AJAX_PATH).'document.ajax.php?'.api_get_cidreq().'&a=upload_file&curdirpath=';
  9129. $form->addMultipleUpload($url);
  9130. $new = $this->display_document_form('add', 0);
  9131. $frmReadOutText = $this->displayFrmReadOutText('add');
  9132. $tabs = Display::tabs(
  9133. $headers,
  9134. [$documentTree, $new, $frmReadOutText, $form->returnForm()],
  9135. 'subtab'
  9136. );
  9137. return $tabs;
  9138. }
  9139. /**
  9140. * Creates a list with all the exercises (quiz) in it.
  9141. *
  9142. * @return string
  9143. */
  9144. public function get_exercises()
  9145. {
  9146. $course_id = api_get_course_int_id();
  9147. $session_id = api_get_session_id();
  9148. $userInfo = api_get_user_info();
  9149. // New for hotpotatoes.
  9150. $uploadPath = DIR_HOTPOTATOES; //defined in main_api
  9151. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  9152. $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  9153. $condition_session = api_get_session_condition($session_id, true, true);
  9154. $setting = api_get_configuration_value('show_invisible_exercise_in_lp_list');
  9155. $activeCondition = ' active <> -1 ';
  9156. if ($setting) {
  9157. $activeCondition = ' active = 1 ';
  9158. }
  9159. $categoryCondition = '';
  9160. $categoryId = isset($_REQUEST['category_id']) ? (int) $_REQUEST['category_id'] : 0;
  9161. if (api_get_configuration_value('allow_exercise_categories') && !empty($categoryId)) {
  9162. $categoryCondition = " AND exercise_category_id = $categoryId ";
  9163. }
  9164. $keywordCondition = '';
  9165. $keyword = isset($_REQUEST['keyword']) ? $_REQUEST['keyword'] : '';
  9166. if (!empty($keyword)) {
  9167. $keyword = Database::escape_string($keyword);
  9168. $keywordCondition = " AND title LIKE '%$keyword%' ";
  9169. }
  9170. $sql_quiz = "SELECT * FROM $tbl_quiz
  9171. WHERE
  9172. c_id = $course_id AND
  9173. $activeCondition
  9174. $condition_session
  9175. $categoryCondition
  9176. $keywordCondition
  9177. ORDER BY title ASC";
  9178. $sql_hot = "SELECT * FROM $tbl_doc
  9179. WHERE
  9180. c_id = $course_id AND
  9181. path LIKE '".$uploadPath."/%/%htm%'
  9182. $condition_session
  9183. ORDER BY id ASC";
  9184. $res_quiz = Database::query($sql_quiz);
  9185. $res_hot = Database::query($sql_hot);
  9186. $currentUrl = api_get_self().'?'.api_get_cidreq().'&action=add_item&type=step&lp_id='.$this->lp_id.'#resource_tab-2';
  9187. // Create a search-box
  9188. $form = new FormValidator('search_simple', 'get', $currentUrl);
  9189. $form->addHidden('action', 'add_item');
  9190. $form->addHidden('type', 'step');
  9191. $form->addHidden('lp_id', $this->lp_id);
  9192. $form->addHidden('lp_build_selected', '2');
  9193. $form->addCourseHiddenParams();
  9194. $form->addText(
  9195. 'keyword',
  9196. get_lang('Search'),
  9197. false,
  9198. [
  9199. 'aria-label' => get_lang('Search'),
  9200. ]
  9201. );
  9202. if (api_get_configuration_value('allow_exercise_categories')) {
  9203. $manager = new ExerciseCategoryManager();
  9204. $options = $manager->getCategoriesForSelect(api_get_course_int_id());
  9205. if (!empty($options)) {
  9206. $form->addSelect(
  9207. 'category_id',
  9208. get_lang('Category'),
  9209. $options,
  9210. ['placeholder' => get_lang('SelectAnOption')]
  9211. );
  9212. }
  9213. }
  9214. $form->addButtonSearch(get_lang('Search'));
  9215. $return = $form->returnForm();
  9216. $return .= '<ul class="lp_resource">';
  9217. $return .= '<li class="lp_resource_element">';
  9218. $return .= Display::return_icon('new_exercice.png');
  9219. $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'exercise/exercise_admin.php?'.api_get_cidreq().'&lp_id='.$this->lp_id.'">'.
  9220. get_lang('NewExercise').'</a>';
  9221. $return .= '</li>';
  9222. $previewIcon = Display::return_icon(
  9223. 'preview_view.png',
  9224. get_lang('Preview')
  9225. );
  9226. $quizIcon = Display::return_icon('quiz.png', '', [], ICON_SIZE_TINY);
  9227. $moveIcon = Display::return_icon('move_everywhere.png', get_lang('Move'), [], ICON_SIZE_TINY);
  9228. $exerciseUrl = api_get_path(WEB_CODE_PATH).'exercise/showinframes.php?'.api_get_cidreq();
  9229. // Display hotpotatoes
  9230. while ($row_hot = Database::fetch_array($res_hot)) {
  9231. $link = Display::url(
  9232. $previewIcon,
  9233. $exerciseUrl.'&file='.$row_hot['path'],
  9234. ['target' => '_blank']
  9235. );
  9236. $return .= '<li class="lp_resource_element" data_id="'.$row_hot['id'].'" data_type="hotpotatoes" title="'.$row_hot['title'].'" >';
  9237. $return .= '<a class="moved" href="#">';
  9238. $return .= Display::return_icon(
  9239. 'move_everywhere.png',
  9240. get_lang('Move'),
  9241. [],
  9242. ICON_SIZE_TINY
  9243. );
  9244. $return .= '</a> ';
  9245. $return .= Display::return_icon('hotpotatoes_s.png');
  9246. $return .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_HOTPOTATOES.'&file='.$row_hot['id'].'&lp_id='.$this->lp_id.'">'.
  9247. ((!empty($row_hot['comment'])) ? $row_hot['comment'] : Security::remove_XSS($row_hot['title'])).$link.'</a>';
  9248. $return .= '</li>';
  9249. }
  9250. $exerciseUrl = api_get_path(WEB_CODE_PATH).'exercise/overview.php?'.api_get_cidreq();
  9251. while ($row_quiz = Database::fetch_array($res_quiz)) {
  9252. $title = strip_tags(
  9253. api_html_entity_decode($row_quiz['title'])
  9254. );
  9255. $visibility = api_get_item_visibility(
  9256. ['real_id' => $course_id],
  9257. TOOL_QUIZ,
  9258. $row_quiz['iid'],
  9259. $session_id
  9260. );
  9261. $link = Display::url(
  9262. $previewIcon,
  9263. $exerciseUrl.'&exerciseId='.$row_quiz['id'],
  9264. ['target' => '_blank']
  9265. );
  9266. $return .= '<li class="lp_resource_element" data_id="'.$row_quiz['id'].'" data_type="quiz" title="'.$title.'" >';
  9267. $return .= Display::url($moveIcon, '#', ['class' => 'moved']);
  9268. $return .= $quizIcon;
  9269. $sessionStar = api_get_session_image(
  9270. $row_quiz['session_id'],
  9271. $userInfo['status']
  9272. );
  9273. $return .= Display::url(
  9274. Security::remove_XSS(cut($title, 80)).$link.$sessionStar,
  9275. api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_QUIZ.'&file='.$row_quiz['id'].'&lp_id='.$this->lp_id,
  9276. [
  9277. 'class' => $visibility == 0 ? 'moved text-muted' : 'moved',
  9278. ]
  9279. );
  9280. $return .= '</li>';
  9281. }
  9282. $return .= '</ul>';
  9283. return $return;
  9284. }
  9285. /**
  9286. * Creates a list with all the links in it.
  9287. *
  9288. * @return string
  9289. */
  9290. public function get_links()
  9291. {
  9292. $selfUrl = api_get_self();
  9293. $courseIdReq = api_get_cidreq();
  9294. $course = api_get_course_info();
  9295. $userInfo = api_get_user_info();
  9296. $course_id = $course['real_id'];
  9297. $tbl_link = Database::get_course_table(TABLE_LINK);
  9298. $linkCategoryTable = Database::get_course_table(TABLE_LINK_CATEGORY);
  9299. $moveEverywhereIcon = Display::return_icon(
  9300. 'move_everywhere.png',
  9301. get_lang('Move'),
  9302. [],
  9303. ICON_SIZE_TINY
  9304. );
  9305. $session_id = api_get_session_id();
  9306. $condition_session = api_get_session_condition(
  9307. $session_id,
  9308. true,
  9309. true,
  9310. 'link.session_id'
  9311. );
  9312. $sql = "SELECT
  9313. link.id as link_id,
  9314. link.title as link_title,
  9315. link.session_id as link_session_id,
  9316. link.category_id as category_id,
  9317. link_category.category_title as category_title
  9318. FROM $tbl_link as link
  9319. LEFT JOIN $linkCategoryTable as link_category
  9320. ON (link.category_id = link_category.id AND link.c_id = link_category.c_id)
  9321. WHERE link.c_id = $course_id $condition_session
  9322. ORDER BY link_category.category_title ASC, link.title ASC";
  9323. $result = Database::query($sql);
  9324. $categorizedLinks = [];
  9325. $categories = [];
  9326. while ($link = Database::fetch_array($result)) {
  9327. if (!$link['category_id']) {
  9328. $link['category_title'] = get_lang('Uncategorized');
  9329. }
  9330. $categories[$link['category_id']] = $link['category_title'];
  9331. $categorizedLinks[$link['category_id']][$link['link_id']] = $link;
  9332. }
  9333. $linksHtmlCode =
  9334. '<script>
  9335. function toggle_tool(tool, id) {
  9336. if(document.getElementById(tool+"_"+id+"_content").style.display == "none"){
  9337. document.getElementById(tool+"_"+id+"_content").style.display = "block";
  9338. document.getElementById(tool+"_"+id+"_opener").src = "'.Display::returnIconPath('remove.gif').'";
  9339. } else {
  9340. document.getElementById(tool+"_"+id+"_content").style.display = "none";
  9341. document.getElementById(tool+"_"+id+"_opener").src = "'.Display::returnIconPath('add.gif').'";
  9342. }
  9343. }
  9344. </script>
  9345. <ul class="lp_resource">
  9346. <li class="lp_resource_element">
  9347. '.Display::return_icon('linksnew.gif').'
  9348. <a href="'.api_get_path(WEB_CODE_PATH).'link/link.php?'.$courseIdReq.'&action=addlink&lp_id='.$this->lp_id.'" title="'.get_lang('LinkAdd').'">'.
  9349. get_lang('LinkAdd').'
  9350. </a>
  9351. </li>';
  9352. foreach ($categorizedLinks as $categoryId => $links) {
  9353. $linkNodes = null;
  9354. foreach ($links as $key => $linkInfo) {
  9355. $title = $linkInfo['link_title'];
  9356. $linkSessionId = $linkInfo['link_session_id'];
  9357. $link = Display::url(
  9358. Display::return_icon('preview_view.png', get_lang('Preview')),
  9359. api_get_path(WEB_CODE_PATH).'link/link_goto.php?'.api_get_cidreq().'&link_id='.$key,
  9360. ['target' => '_blank']
  9361. );
  9362. if (api_get_item_visibility($course, TOOL_LINK, $key, $session_id) != 2) {
  9363. $sessionStar = api_get_session_image($linkSessionId, $userInfo['status']);
  9364. $linkNodes .=
  9365. '<li class="lp_resource_element" data_id="'.$key.'" data_type="'.TOOL_LINK.'" title="'.$title.'" >
  9366. <a class="moved" href="#">'.
  9367. $moveEverywhereIcon.
  9368. '</a>
  9369. '.Display::return_icon('links.png', '', [], ICON_SIZE_TINY).'
  9370. <a class="moved" href="'.$selfUrl.'?'.$courseIdReq.'&action=add_item&type='.
  9371. TOOL_LINK.'&file='.$key.'&lp_id='.$this->lp_id.'">'.
  9372. Security::remove_XSS($title).$sessionStar.$link.
  9373. '</a>
  9374. </li>';
  9375. }
  9376. }
  9377. $linksHtmlCode .=
  9378. '<li>
  9379. <a style="cursor:hand" onclick="javascript: toggle_tool(\''.TOOL_LINK.'\','.$categoryId.')" style="vertical-align:middle">
  9380. <img src="'.Display::returnIconPath('add.gif').'" id="'.TOOL_LINK.'_'.$categoryId.'_opener"
  9381. align="absbottom" />
  9382. </a>
  9383. <span style="vertical-align:middle">'.Security::remove_XSS($categories[$categoryId]).'</span>
  9384. </li>
  9385. <div style="display:none" id="'.TOOL_LINK.'_'.$categoryId.'_content">'.$linkNodes.'</div>';
  9386. }
  9387. $linksHtmlCode .= '</ul>';
  9388. return $linksHtmlCode;
  9389. }
  9390. /**
  9391. * Creates a list with all the student publications in it.
  9392. *
  9393. * @return string
  9394. */
  9395. public function get_student_publications()
  9396. {
  9397. $return = '<ul class="lp_resource">';
  9398. $return .= '<li class="lp_resource_element">';
  9399. $return .= Display::return_icon('works_new.gif');
  9400. $return .= ' <a href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_STUDENTPUBLICATION.'&lp_id='.$this->lp_id.'">'.
  9401. get_lang('AddAssignmentPage').'</a>';
  9402. $return .= '</li>';
  9403. require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
  9404. $works = getWorkListTeacher(0, 100, null, null, null);
  9405. if (!empty($works)) {
  9406. foreach ($works as $work) {
  9407. $link = Display::url(
  9408. Display::return_icon('preview_view.png', get_lang('Preview')),
  9409. api_get_path(WEB_CODE_PATH).'work/work_list_all.php?'.api_get_cidreq().'&id='.$work['iid'],
  9410. ['target' => '_blank']
  9411. );
  9412. $return .= '<li class="lp_resource_element" data_id="'.$work['iid'].'" data_type="'.TOOL_STUDENTPUBLICATION.'" title="'.Security::remove_XSS(cut(strip_tags($work['title']), 80)).'">';
  9413. $return .= '<a class="moved" href="#">';
  9414. $return .= Display::return_icon(
  9415. 'move_everywhere.png',
  9416. get_lang('Move'),
  9417. [],
  9418. ICON_SIZE_TINY
  9419. );
  9420. $return .= '</a> ';
  9421. $return .= Display::return_icon('works.png', '', [], ICON_SIZE_TINY);
  9422. $return .= ' <a class="moved" href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_STUDENTPUBLICATION.'&file='.$work['iid'].'&lp_id='.$this->lp_id.'">'.
  9423. Security::remove_XSS(cut(strip_tags($work['title']), 80)).' '.$link.'
  9424. </a>';
  9425. $return .= '</li>';
  9426. }
  9427. }
  9428. $return .= '</ul>';
  9429. return $return;
  9430. }
  9431. /**
  9432. * Creates a list with all the forums in it.
  9433. *
  9434. * @return string
  9435. */
  9436. public function get_forums()
  9437. {
  9438. require_once '../forum/forumfunction.inc.php';
  9439. $forumCategories = get_forum_categories();
  9440. $forumsInNoCategory = get_forums_in_category(0);
  9441. if (!empty($forumsInNoCategory)) {
  9442. $forumCategories = array_merge(
  9443. $forumCategories,
  9444. [
  9445. [
  9446. 'cat_id' => 0,
  9447. 'session_id' => 0,
  9448. 'visibility' => 1,
  9449. 'cat_comment' => null,
  9450. ],
  9451. ]
  9452. );
  9453. }
  9454. $forumList = get_forums();
  9455. $a_forums = [];
  9456. foreach ($forumCategories as $forumCategory) {
  9457. // The forums in this category.
  9458. $forumsInCategory = get_forums_in_category($forumCategory['cat_id']);
  9459. if (!empty($forumsInCategory)) {
  9460. foreach ($forumList as $forum) {
  9461. if (isset($forum['forum_category']) &&
  9462. $forum['forum_category'] == $forumCategory['cat_id']
  9463. ) {
  9464. $a_forums[] = $forum;
  9465. }
  9466. }
  9467. }
  9468. }
  9469. $return = '<ul class="lp_resource">';
  9470. // First add link
  9471. $return .= '<li class="lp_resource_element">';
  9472. $return .= Display::return_icon('new_forum.png');
  9473. $return .= Display::url(
  9474. get_lang('CreateANewForum'),
  9475. api_get_path(WEB_CODE_PATH).'forum/index.php?'.api_get_cidreq().'&'.http_build_query([
  9476. 'action' => 'add',
  9477. 'content' => 'forum',
  9478. 'lp_id' => $this->lp_id,
  9479. ]),
  9480. ['title' => get_lang('CreateANewForum')]
  9481. );
  9482. $return .= '</li>';
  9483. $return .= '<script>
  9484. function toggle_forum(forum_id) {
  9485. if (document.getElementById("forum_"+forum_id+"_content").style.display == "none") {
  9486. document.getElementById("forum_"+forum_id+"_content").style.display = "block";
  9487. document.getElementById("forum_"+forum_id+"_opener").src = "'.Display::returnIconPath('remove.gif').'";
  9488. } else {
  9489. document.getElementById("forum_"+forum_id+"_content").style.display = "none";
  9490. document.getElementById("forum_"+forum_id+"_opener").src = "'.Display::returnIconPath('add.gif').'";
  9491. }
  9492. }
  9493. </script>';
  9494. foreach ($a_forums as $forum) {
  9495. if (!empty($forum['forum_id'])) {
  9496. $link = Display::url(
  9497. Display::return_icon('preview_view.png', get_lang('Preview')),
  9498. api_get_path(WEB_CODE_PATH).'forum/viewforum.php?'.api_get_cidreq().'&forum='.$forum['forum_id'],
  9499. ['target' => '_blank']
  9500. );
  9501. $return .= '<li class="lp_resource_element" data_id="'.$forum['forum_id'].'" data_type="'.TOOL_FORUM.'" title="'.$forum['forum_title'].'" >';
  9502. $return .= '<a class="moved" href="#">';
  9503. $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), [], ICON_SIZE_TINY);
  9504. $return .= ' </a>';
  9505. $return .= Display::return_icon('forum.png', '', [], ICON_SIZE_TINY);
  9506. $return .= '<a onclick="javascript:toggle_forum('.$forum['forum_id'].');" style="cursor:hand; vertical-align:middle">
  9507. <img src="'.Display::returnIconPath('add.gif').'" id="forum_'.$forum['forum_id'].'_opener" align="absbottom" />
  9508. </a>
  9509. <a class="moved" href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_FORUM.'&forum_id='.$forum['forum_id'].'&lp_id='.$this->lp_id.'" style="vertical-align:middle">'.
  9510. Security::remove_XSS($forum['forum_title']).' '.$link.'</a>';
  9511. $return .= '</li>';
  9512. $return .= '<div style="display:none" id="forum_'.$forum['forum_id'].'_content">';
  9513. $a_threads = get_threads($forum['forum_id']);
  9514. if (is_array($a_threads)) {
  9515. foreach ($a_threads as $thread) {
  9516. $link = Display::url(
  9517. Display::return_icon('preview_view.png', get_lang('Preview')),
  9518. api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.api_get_cidreq().'&forum='.$forum['forum_id'].'&thread='.$thread['thread_id'],
  9519. ['target' => '_blank']
  9520. );
  9521. $return .= '<li class="lp_resource_element" data_id="'.$thread['thread_id'].'" data_type="'.TOOL_THREAD.'" title="'.$thread['thread_title'].'" >';
  9522. $return .= '&nbsp;<a class="moved" href="#">';
  9523. $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), [], ICON_SIZE_TINY);
  9524. $return .= ' </a>';
  9525. $return .= Display::return_icon('forumthread.png', get_lang('Thread'), [], ICON_SIZE_TINY);
  9526. $return .= '<a class="moved" href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_THREAD.'&thread_id='.$thread['thread_id'].'&lp_id='.$this->lp_id.'">'.
  9527. Security::remove_XSS($thread['thread_title']).' '.$link.'</a>';
  9528. $return .= '</li>';
  9529. }
  9530. }
  9531. $return .= '</div>';
  9532. }
  9533. }
  9534. $return .= '</ul>';
  9535. return $return;
  9536. }
  9537. /**
  9538. * // TODO: The output encoding should be equal to the system encoding.
  9539. *
  9540. * Exports the learning path as a SCORM package. This is the main function that
  9541. * gathers the content, transforms it, writes the imsmanifest.xml file, zips the
  9542. * whole thing and returns the zip.
  9543. *
  9544. * This method needs to be called in PHP5, as it will fail with non-adequate
  9545. * XML package (like the ones for PHP4), and it is *not* a static method, so
  9546. * you need to call it on a learnpath object.
  9547. *
  9548. * @TODO The method might be redefined later on in the scorm class itself to avoid
  9549. * creating a SCORM structure if there is one already. However, if the initial SCORM
  9550. * path has been modified, it should use the generic method here below.
  9551. *
  9552. * @return string Returns the zip package string, or null if error
  9553. */
  9554. public function scormExport()
  9555. {
  9556. api_set_more_memory_and_time_limits();
  9557. $_course = api_get_course_info();
  9558. $course_id = $_course['real_id'];
  9559. // Create the zip handler (this will remain available throughout the method).
  9560. $archivePath = api_get_path(SYS_ARCHIVE_PATH);
  9561. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  9562. $temp_dir_short = uniqid('scorm_export', true);
  9563. $temp_zip_dir = $archivePath.'/'.$temp_dir_short;
  9564. $temp_zip_file = $temp_zip_dir.'/'.md5(time()).'.zip';
  9565. $zip_folder = new PclZip($temp_zip_file);
  9566. $current_course_path = api_get_path(SYS_COURSE_PATH).api_get_course_path();
  9567. $root_path = $main_path = api_get_path(SYS_PATH);
  9568. $files_cleanup = [];
  9569. // Place to temporarily stash the zip file.
  9570. // create the temp dir if it doesn't exist
  9571. // or do a cleanup before creating the zip file.
  9572. if (!is_dir($temp_zip_dir)) {
  9573. mkdir($temp_zip_dir, api_get_permissions_for_new_directories());
  9574. } else {
  9575. // Cleanup: Check the temp dir for old files and delete them.
  9576. $handle = opendir($temp_zip_dir);
  9577. while (false !== ($file = readdir($handle))) {
  9578. if ($file != '.' && $file != '..') {
  9579. unlink("$temp_zip_dir/$file");
  9580. }
  9581. }
  9582. closedir($handle);
  9583. }
  9584. $zip_files = $zip_files_abs = $zip_files_dist = [];
  9585. if (is_dir($current_course_path.'/scorm/'.$this->path) &&
  9586. is_file($current_course_path.'/scorm/'.$this->path.'/imsmanifest.xml')
  9587. ) {
  9588. // Remove the possible . at the end of the path.
  9589. $dest_path_to_lp = substr($this->path, -1) == '.' ? substr($this->path, 0, -1) : $this->path;
  9590. $dest_path_to_scorm_folder = str_replace('//', '/', $temp_zip_dir.'/scorm/'.$dest_path_to_lp);
  9591. mkdir(
  9592. $dest_path_to_scorm_folder,
  9593. api_get_permissions_for_new_directories(),
  9594. true
  9595. );
  9596. copyr(
  9597. $current_course_path.'/scorm/'.$this->path,
  9598. $dest_path_to_scorm_folder,
  9599. ['imsmanifest'],
  9600. $zip_files
  9601. );
  9602. }
  9603. // Build a dummy imsmanifest structure.
  9604. // Do not add to the zip yet (we still need it).
  9605. // This structure is developed following regulations for SCORM 1.2 packaging in the SCORM 1.2 Content
  9606. // Aggregation Model official document, section "2.3 Content Packaging".
  9607. // We are going to build a UTF-8 encoded manifest.
  9608. // Later we will recode it to the desired (and supported) encoding.
  9609. $xmldoc = new DOMDocument('1.0');
  9610. $root = $xmldoc->createElement('manifest');
  9611. $root->setAttribute('identifier', 'SingleCourseManifest');
  9612. $root->setAttribute('version', '1.1');
  9613. $root->setAttribute('xmlns', 'http://www.imsproject.org/xsd/imscp_rootv1p1p2');
  9614. $root->setAttribute('xmlns:adlcp', 'http://www.adlnet.org/xsd/adlcp_rootv1p2');
  9615. $root->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
  9616. $root->setAttribute(
  9617. 'xsi:schemaLocation',
  9618. 'http://www.imsproject.org/xsd/imscp_rootv1p1p2 imscp_rootv1p1p2.xsd http://www.imsglobal.org/xsd/imsmd_rootv1p2p1 imsmd_rootv1p2p1.xsd http://www.adlnet.org/xsd/adlcp_rootv1p2 adlcp_rootv1p2.xsd'
  9619. );
  9620. // Build mandatory sub-root container elements.
  9621. $metadata = $xmldoc->createElement('metadata');
  9622. $md_schema = $xmldoc->createElement('schema', 'ADL SCORM');
  9623. $metadata->appendChild($md_schema);
  9624. $md_schemaversion = $xmldoc->createElement('schemaversion', '1.2');
  9625. $metadata->appendChild($md_schemaversion);
  9626. $root->appendChild($metadata);
  9627. $organizations = $xmldoc->createElement('organizations');
  9628. $resources = $xmldoc->createElement('resources');
  9629. // Build the only organization we will use in building our learnpaths.
  9630. $organizations->setAttribute('default', 'chamilo_scorm_export');
  9631. $organization = $xmldoc->createElement('organization');
  9632. $organization->setAttribute('identifier', 'chamilo_scorm_export');
  9633. // To set the title of the SCORM entity (=organization), we take the name given
  9634. // in Chamilo and convert it to HTML entities using the Chamilo charset (not the
  9635. // learning path charset) as it is the encoding that defines how it is stored
  9636. // in the database. Then we convert it to HTML entities again as the "&" character
  9637. // alone is not authorized in XML (must be &amp;).
  9638. // The title is then decoded twice when extracting (see scorm::parse_manifest).
  9639. $org_title = $xmldoc->createElement('title', api_utf8_encode($this->get_name()));
  9640. $organization->appendChild($org_title);
  9641. $folder_name = 'document';
  9642. // Removes the learning_path/scorm_folder path when exporting see #4841
  9643. $path_to_remove = '';
  9644. $path_to_replace = '';
  9645. $result = $this->generate_lp_folder($_course);
  9646. if (isset($result['dir']) && strpos($result['dir'], 'learning_path')) {
  9647. $path_to_remove = 'document'.$result['dir'];
  9648. $path_to_replace = $folder_name.'/';
  9649. }
  9650. // Fixes chamilo scorm exports
  9651. if ($this->ref === 'chamilo_scorm_export') {
  9652. $path_to_remove = 'scorm/'.$this->path.'/document/';
  9653. }
  9654. // For each element, add it to the imsmanifest structure, then add it to the zip.
  9655. $link_updates = [];
  9656. $links_to_create = [];
  9657. foreach ($this->ordered_items as $index => $itemId) {
  9658. /** @var learnpathItem $item */
  9659. $item = $this->items[$itemId];
  9660. if (!in_array($item->type, [TOOL_QUIZ, TOOL_FORUM, TOOL_THREAD, TOOL_LINK, TOOL_STUDENTPUBLICATION])) {
  9661. // Get included documents from this item.
  9662. if ($item->type === 'sco') {
  9663. $inc_docs = $item->get_resources_from_source(
  9664. null,
  9665. $current_course_path.'/scorm/'.$this->path.'/'.$item->get_path()
  9666. );
  9667. } else {
  9668. $inc_docs = $item->get_resources_from_source();
  9669. }
  9670. // Give a child element <item> to the <organization> element.
  9671. $my_item_id = $item->get_id();
  9672. $my_item = $xmldoc->createElement('item');
  9673. $my_item->setAttribute('identifier', 'ITEM_'.$my_item_id);
  9674. $my_item->setAttribute('identifierref', 'RESOURCE_'.$my_item_id);
  9675. $my_item->setAttribute('isvisible', 'true');
  9676. // Give a child element <title> to the <item> element.
  9677. $my_title = $xmldoc->createElement(
  9678. 'title',
  9679. htmlspecialchars(
  9680. api_utf8_encode($item->get_title()),
  9681. ENT_QUOTES,
  9682. 'UTF-8'
  9683. )
  9684. );
  9685. $my_item->appendChild($my_title);
  9686. // Give a child element <adlcp:prerequisites> to the <item> element.
  9687. $my_prereqs = $xmldoc->createElement(
  9688. 'adlcp:prerequisites',
  9689. $this->get_scorm_prereq_string($my_item_id)
  9690. );
  9691. $my_prereqs->setAttribute('type', 'aicc_script');
  9692. $my_item->appendChild($my_prereqs);
  9693. // Give a child element <adlcp:maxtimeallowed> to the <item> element - not yet supported.
  9694. //$xmldoc->createElement('adlcp:maxtimeallowed','');
  9695. // Give a child element <adlcp:timelimitaction> to the <item> element - not yet supported.
  9696. //$xmldoc->createElement('adlcp:timelimitaction','');
  9697. // Give a child element <adlcp:datafromlms> to the <item> element - not yet supported.
  9698. //$xmldoc->createElement('adlcp:datafromlms','');
  9699. // Give a child element <adlcp:masteryscore> to the <item> element.
  9700. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  9701. $my_item->appendChild($my_masteryscore);
  9702. // Attach this item to the organization element or hits parent if there is one.
  9703. if (!empty($item->parent) && $item->parent != 0) {
  9704. $children = $organization->childNodes;
  9705. $possible_parent = $this->get_scorm_xml_node($children, 'ITEM_'.$item->parent);
  9706. if (is_object($possible_parent)) {
  9707. $possible_parent->appendChild($my_item);
  9708. } else {
  9709. if ($this->debug > 0) {
  9710. error_log('Parent ITEM_'.$item->parent.' of item ITEM_'.$my_item_id.' not found');
  9711. }
  9712. }
  9713. } else {
  9714. if ($this->debug > 0) {
  9715. error_log('No parent');
  9716. }
  9717. $organization->appendChild($my_item);
  9718. }
  9719. // Get the path of the file(s) from the course directory root.
  9720. $my_file_path = $item->get_file_path('scorm/'.$this->path.'/');
  9721. $my_xml_file_path = $my_file_path;
  9722. if (!empty($path_to_remove)) {
  9723. // From docs
  9724. $my_xml_file_path = str_replace($path_to_remove, $path_to_replace, $my_file_path);
  9725. // From quiz
  9726. if ($this->ref === 'chamilo_scorm_export') {
  9727. $path_to_remove = 'scorm/'.$this->path.'/';
  9728. $my_xml_file_path = str_replace($path_to_remove, '', $my_file_path);
  9729. }
  9730. }
  9731. $my_sub_dir = dirname($my_file_path);
  9732. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  9733. $my_xml_sub_dir = $my_sub_dir;
  9734. // Give a <resource> child to the <resources> element
  9735. $my_resource = $xmldoc->createElement('resource');
  9736. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  9737. $my_resource->setAttribute('type', 'webcontent');
  9738. $my_resource->setAttribute('href', $my_xml_file_path);
  9739. // adlcp:scormtype can be either 'sco' or 'asset'.
  9740. if ($item->type === 'sco') {
  9741. $my_resource->setAttribute('adlcp:scormtype', 'sco');
  9742. } else {
  9743. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  9744. }
  9745. // xml:base is the base directory to find the files declared in this resource.
  9746. $my_resource->setAttribute('xml:base', '');
  9747. // Give a <file> child to the <resource> element.
  9748. $my_file = $xmldoc->createElement('file');
  9749. $my_file->setAttribute('href', $my_xml_file_path);
  9750. $my_resource->appendChild($my_file);
  9751. // Dependency to other files - not yet supported.
  9752. $i = 1;
  9753. if ($inc_docs) {
  9754. foreach ($inc_docs as $doc_info) {
  9755. if (count($doc_info) < 1 || empty($doc_info[0])) {
  9756. continue;
  9757. }
  9758. $my_dep = $xmldoc->createElement('resource');
  9759. $res_id = 'RESOURCE_'.$item->get_id().'_'.$i;
  9760. $my_dep->setAttribute('identifier', $res_id);
  9761. $my_dep->setAttribute('type', 'webcontent');
  9762. $my_dep->setAttribute('adlcp:scormtype', 'asset');
  9763. $my_dep_file = $xmldoc->createElement('file');
  9764. // Check type of URL.
  9765. if ($doc_info[1] == 'remote') {
  9766. // Remote file. Save url as is.
  9767. $my_dep_file->setAttribute('href', $doc_info[0]);
  9768. $my_dep->setAttribute('xml:base', '');
  9769. } elseif ($doc_info[1] === 'local') {
  9770. switch ($doc_info[2]) {
  9771. case 'url':
  9772. // Local URL - save path as url for now, don't zip file.
  9773. $abs_path = api_get_path(SYS_PATH).
  9774. str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  9775. $current_dir = dirname($abs_path);
  9776. $current_dir = str_replace('\\', '/', $current_dir);
  9777. $file_path = realpath($abs_path);
  9778. $file_path = str_replace('\\', '/', $file_path);
  9779. $my_dep_file->setAttribute('href', $file_path);
  9780. $my_dep->setAttribute('xml:base', '');
  9781. if (strstr($file_path, $main_path) !== false) {
  9782. // The calculated real path is really inside Chamilo's root path.
  9783. // Reduce file path to what's under the DocumentRoot.
  9784. $replace = $file_path;
  9785. $file_path = substr($file_path, strlen($root_path) - 1);
  9786. $destinationFile = $file_path;
  9787. if (strstr($file_path, 'upload/users') !== false) {
  9788. $pos = strpos($file_path, 'my_files/');
  9789. if ($pos !== false) {
  9790. $onlyDirectory = str_replace(
  9791. 'upload/users/',
  9792. '',
  9793. substr($file_path, $pos, strlen($file_path))
  9794. );
  9795. }
  9796. $replace = $onlyDirectory;
  9797. $destinationFile = $replace;
  9798. }
  9799. $zip_files_abs[] = $file_path;
  9800. $link_updates[$my_file_path][] = [
  9801. 'orig' => $doc_info[0],
  9802. 'dest' => $destinationFile,
  9803. 'replace' => $replace,
  9804. ];
  9805. $my_dep_file->setAttribute('href', $file_path);
  9806. $my_dep->setAttribute('xml:base', '');
  9807. } elseif (empty($file_path)) {
  9808. $file_path = $_SERVER['DOCUMENT_ROOT'].$abs_path;
  9809. $file_path = str_replace('//', '/', $file_path);
  9810. if (file_exists($file_path)) {
  9811. // We get the relative path.
  9812. $file_path = substr($file_path, strlen($current_dir));
  9813. $zip_files[] = $my_sub_dir.'/'.$file_path;
  9814. $link_updates[$my_file_path][] = [
  9815. 'orig' => $doc_info[0],
  9816. 'dest' => $file_path,
  9817. ];
  9818. $my_dep_file->setAttribute('href', $file_path);
  9819. $my_dep->setAttribute('xml:base', '');
  9820. }
  9821. }
  9822. break;
  9823. case 'abs':
  9824. // Absolute path from DocumentRoot. Save file and leave path as is in the zip.
  9825. $my_dep_file->setAttribute('href', $doc_info[0]);
  9826. $my_dep->setAttribute('xml:base', '');
  9827. // The next lines fix a bug when using the "subdir" mode of Chamilo, whereas
  9828. // an image path would be constructed as /var/www/subdir/subdir/img/foo.bar
  9829. $abs_img_path_without_subdir = $doc_info[0];
  9830. $relp = api_get_path(REL_PATH); // The url-append config param.
  9831. $pos = strpos($abs_img_path_without_subdir, $relp);
  9832. if ($pos === 0) {
  9833. $abs_img_path_without_subdir = trim('/'.substr($abs_img_path_without_subdir, strlen($relp)));
  9834. }
  9835. $file_path = realpath(api_get_path(SYS_APP_PATH).$abs_img_path_without_subdir);
  9836. $file_path = str_replace(['\\', '//'], '/', $file_path);
  9837. // Prepare the current directory path (until just under 'document') with a trailing slash.
  9838. $cur_path = substr($current_course_path, -1) == '/' ? $current_course_path : $current_course_path.'/';
  9839. // Check if the current document is in that path.
  9840. if (strstr($file_path, $cur_path) !== false) {
  9841. $destinationFile = substr($file_path, strlen($cur_path));
  9842. $filePathNoCoursePart = substr($file_path, strlen($cur_path));
  9843. $fileToTest = $cur_path.$my_file_path;
  9844. if (!empty($path_to_remove)) {
  9845. $fileToTest = str_replace(
  9846. $path_to_remove.'/',
  9847. $path_to_replace,
  9848. $cur_path.$my_file_path
  9849. );
  9850. }
  9851. $relative_path = api_get_relative_path($fileToTest, $file_path);
  9852. // Put the current document in the zip (this array is the array
  9853. // that will manage documents already in the course folder - relative).
  9854. $zip_files[] = $filePathNoCoursePart;
  9855. // Update the links to the current document in the
  9856. // containing document (make them relative).
  9857. $link_updates[$my_file_path][] = [
  9858. 'orig' => $doc_info[0],
  9859. 'dest' => $destinationFile,
  9860. 'replace' => $relative_path,
  9861. ];
  9862. $my_dep_file->setAttribute('href', $file_path);
  9863. $my_dep->setAttribute('xml:base', '');
  9864. } elseif (strstr($file_path, $main_path) !== false) {
  9865. // The calculated real path is really inside Chamilo's root path.
  9866. // Reduce file path to what's under the DocumentRoot.
  9867. $file_path = substr($file_path, strlen($root_path));
  9868. $zip_files_abs[] = $file_path;
  9869. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => $file_path];
  9870. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9871. $my_dep->setAttribute('xml:base', '');
  9872. } elseif (empty($file_path)) {
  9873. // Probably this is an image inside "/main" directory
  9874. $file_path = api_get_path(SYS_PATH).$abs_img_path_without_subdir;
  9875. $abs_path = api_get_path(SYS_PATH).str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  9876. if (file_exists($file_path)) {
  9877. if (strstr($file_path, 'main/default_course_document') !== false) {
  9878. // We get the relative path.
  9879. $pos = strpos($file_path, 'main/default_course_document/');
  9880. if ($pos !== false) {
  9881. $onlyDirectory = str_replace(
  9882. 'main/default_course_document/',
  9883. '',
  9884. substr($file_path, $pos, strlen($file_path))
  9885. );
  9886. }
  9887. $destinationFile = 'default_course_document/'.$onlyDirectory;
  9888. $fileAbs = substr($file_path, strlen(api_get_path(SYS_PATH)));
  9889. $zip_files_abs[] = $fileAbs;
  9890. $link_updates[$my_file_path][] = [
  9891. 'orig' => $doc_info[0],
  9892. 'dest' => $destinationFile,
  9893. ];
  9894. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9895. $my_dep->setAttribute('xml:base', '');
  9896. }
  9897. }
  9898. }
  9899. break;
  9900. case 'rel':
  9901. // Path relative to the current document.
  9902. // Save xml:base as current document's directory and save file in zip as subdir.file_path
  9903. if (substr($doc_info[0], 0, 2) === '..') {
  9904. // Relative path going up.
  9905. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  9906. $current_dir = str_replace('\\', '/', $current_dir);
  9907. $file_path = realpath($current_dir.$doc_info[0]);
  9908. $file_path = str_replace('\\', '/', $file_path);
  9909. if (strstr($file_path, $main_path) !== false) {
  9910. // The calculated real path is really inside Chamilo's root path.
  9911. // Reduce file path to what's under the DocumentRoot.
  9912. $file_path = substr($file_path, strlen($root_path));
  9913. $zip_files_abs[] = $file_path;
  9914. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => $file_path];
  9915. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9916. $my_dep->setAttribute('xml:base', '');
  9917. }
  9918. } else {
  9919. $zip_files[] = $my_sub_dir.'/'.$doc_info[0];
  9920. $my_dep_file->setAttribute('href', $doc_info[0]);
  9921. $my_dep->setAttribute('xml:base', $my_xml_sub_dir);
  9922. }
  9923. break;
  9924. default:
  9925. $my_dep_file->setAttribute('href', $doc_info[0]);
  9926. $my_dep->setAttribute('xml:base', '');
  9927. break;
  9928. }
  9929. }
  9930. $my_dep->appendChild($my_dep_file);
  9931. $resources->appendChild($my_dep);
  9932. $dependency = $xmldoc->createElement('dependency');
  9933. $dependency->setAttribute('identifierref', $res_id);
  9934. $my_resource->appendChild($dependency);
  9935. $i++;
  9936. }
  9937. }
  9938. $resources->appendChild($my_resource);
  9939. $zip_files[] = $my_file_path;
  9940. } else {
  9941. // If the item is a quiz or a link or whatever non-exportable, we include a step indicating it.
  9942. switch ($item->type) {
  9943. case TOOL_LINK:
  9944. $my_item = $xmldoc->createElement('item');
  9945. $my_item->setAttribute('identifier', 'ITEM_'.$item->get_id());
  9946. $my_item->setAttribute('identifierref', 'RESOURCE_'.$item->get_id());
  9947. $my_item->setAttribute('isvisible', 'true');
  9948. // Give a child element <title> to the <item> element.
  9949. $my_title = $xmldoc->createElement(
  9950. 'title',
  9951. htmlspecialchars(
  9952. api_utf8_encode($item->get_title()),
  9953. ENT_QUOTES,
  9954. 'UTF-8'
  9955. )
  9956. );
  9957. $my_item->appendChild($my_title);
  9958. // Give a child element <adlcp:prerequisites> to the <item> element.
  9959. $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $item->get_prereq_string());
  9960. $my_prereqs->setAttribute('type', 'aicc_script');
  9961. $my_item->appendChild($my_prereqs);
  9962. // Give a child element <adlcp:maxtimeallowed> to the <item> element - not yet supported.
  9963. //$xmldoc->createElement('adlcp:maxtimeallowed', '');
  9964. // Give a child element <adlcp:timelimitaction> to the <item> element - not yet supported.
  9965. //$xmldoc->createElement('adlcp:timelimitaction', '');
  9966. // Give a child element <adlcp:datafromlms> to the <item> element - not yet supported.
  9967. //$xmldoc->createElement('adlcp:datafromlms', '');
  9968. // Give a child element <adlcp:masteryscore> to the <item> element.
  9969. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  9970. $my_item->appendChild($my_masteryscore);
  9971. // Attach this item to the organization element or its parent if there is one.
  9972. if (!empty($item->parent) && $item->parent != 0) {
  9973. $children = $organization->childNodes;
  9974. for ($i = 0; $i < $children->length; $i++) {
  9975. $item_temp = $children->item($i);
  9976. if ($item_temp->nodeName == 'item') {
  9977. if ($item_temp->getAttribute('identifier') == 'ITEM_'.$item->parent) {
  9978. $item_temp->appendChild($my_item);
  9979. }
  9980. }
  9981. }
  9982. } else {
  9983. $organization->appendChild($my_item);
  9984. }
  9985. $my_file_path = 'link_'.$item->get_id().'.html';
  9986. $sql = 'SELECT url, title FROM '.Database::get_course_table(TABLE_LINK).'
  9987. WHERE c_id = '.$course_id.' AND id = '.$item->path;
  9988. $rs = Database::query($sql);
  9989. if ($link = Database::fetch_array($rs)) {
  9990. $url = $link['url'];
  9991. $title = stripslashes($link['title']);
  9992. $links_to_create[$my_file_path] = ['title' => $title, 'url' => $url];
  9993. $my_xml_file_path = $my_file_path;
  9994. $my_sub_dir = dirname($my_file_path);
  9995. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  9996. $my_xml_sub_dir = $my_sub_dir;
  9997. // Give a <resource> child to the <resources> element.
  9998. $my_resource = $xmldoc->createElement('resource');
  9999. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  10000. $my_resource->setAttribute('type', 'webcontent');
  10001. $my_resource->setAttribute('href', $my_xml_file_path);
  10002. // adlcp:scormtype can be either 'sco' or 'asset'.
  10003. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  10004. // xml:base is the base directory to find the files declared in this resource.
  10005. $my_resource->setAttribute('xml:base', '');
  10006. // give a <file> child to the <resource> element.
  10007. $my_file = $xmldoc->createElement('file');
  10008. $my_file->setAttribute('href', $my_xml_file_path);
  10009. $my_resource->appendChild($my_file);
  10010. $resources->appendChild($my_resource);
  10011. }
  10012. break;
  10013. case TOOL_QUIZ:
  10014. $exe_id = $item->path;
  10015. // Should be using ref when everything will be cleaned up in this regard.
  10016. $exe = new Exercise();
  10017. $exe->read($exe_id);
  10018. $my_item = $xmldoc->createElement('item');
  10019. $my_item->setAttribute('identifier', 'ITEM_'.$item->get_id());
  10020. $my_item->setAttribute('identifierref', 'RESOURCE_'.$item->get_id());
  10021. $my_item->setAttribute('isvisible', 'true');
  10022. // Give a child element <title> to the <item> element.
  10023. $my_title = $xmldoc->createElement(
  10024. 'title',
  10025. htmlspecialchars(
  10026. api_utf8_encode($item->get_title()),
  10027. ENT_QUOTES,
  10028. 'UTF-8'
  10029. )
  10030. );
  10031. $my_item->appendChild($my_title);
  10032. $my_max_score = $xmldoc->createElement('max_score', $item->get_max());
  10033. $my_item->appendChild($my_max_score);
  10034. // Give a child element <adlcp:prerequisites> to the <item> element.
  10035. $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $item->get_prereq_string());
  10036. $my_prereqs->setAttribute('type', 'aicc_script');
  10037. $my_item->appendChild($my_prereqs);
  10038. // Give a child element <adlcp:masteryscore> to the <item> element.
  10039. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  10040. $my_item->appendChild($my_masteryscore);
  10041. // Attach this item to the organization element or hits parent if there is one.
  10042. if (!empty($item->parent) && $item->parent != 0) {
  10043. $children = $organization->childNodes;
  10044. $possible_parent = $this->get_scorm_xml_node($children, 'ITEM_'.$item->parent);
  10045. if ($possible_parent) {
  10046. if ($possible_parent->getAttribute('identifier') === 'ITEM_'.$item->parent) {
  10047. $possible_parent->appendChild($my_item);
  10048. }
  10049. }
  10050. } else {
  10051. $organization->appendChild($my_item);
  10052. }
  10053. // Get the path of the file(s) from the course directory root
  10054. //$my_file_path = $item->get_file_path('scorm/'.$this->path.'/');
  10055. $my_file_path = 'quiz_'.$item->get_id().'.html';
  10056. // Write the contents of the exported exercise into a (big) html file
  10057. // to later pack it into the exported SCORM. The file will be removed afterwards.
  10058. $scormExercise = new ScormExercise($exe, true);
  10059. $contents = $scormExercise->export();
  10060. $tmp_file_path = $archivePath.$temp_dir_short.'/'.$my_file_path;
  10061. $res = file_put_contents($tmp_file_path, $contents);
  10062. if ($res === false) {
  10063. error_log('Could not write into file '.$tmp_file_path.' '.__FILE__.' '.__LINE__, 0);
  10064. }
  10065. $files_cleanup[] = $tmp_file_path;
  10066. $my_xml_file_path = $my_file_path;
  10067. $my_sub_dir = dirname($my_file_path);
  10068. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  10069. $my_xml_sub_dir = $my_sub_dir;
  10070. // Give a <resource> child to the <resources> element.
  10071. $my_resource = $xmldoc->createElement('resource');
  10072. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  10073. $my_resource->setAttribute('type', 'webcontent');
  10074. $my_resource->setAttribute('href', $my_xml_file_path);
  10075. // adlcp:scormtype can be either 'sco' or 'asset'.
  10076. $my_resource->setAttribute('adlcp:scormtype', 'sco');
  10077. // xml:base is the base directory to find the files declared in this resource.
  10078. $my_resource->setAttribute('xml:base', '');
  10079. // Give a <file> child to the <resource> element.
  10080. $my_file = $xmldoc->createElement('file');
  10081. $my_file->setAttribute('href', $my_xml_file_path);
  10082. $my_resource->appendChild($my_file);
  10083. // Get included docs.
  10084. $inc_docs = $item->get_resources_from_source(null, $tmp_file_path);
  10085. // Dependency to other files - not yet supported.
  10086. $i = 1;
  10087. foreach ($inc_docs as $doc_info) {
  10088. if (count($doc_info) < 1 || empty($doc_info[0])) {
  10089. continue;
  10090. }
  10091. $my_dep = $xmldoc->createElement('resource');
  10092. $res_id = 'RESOURCE_'.$item->get_id().'_'.$i;
  10093. $my_dep->setAttribute('identifier', $res_id);
  10094. $my_dep->setAttribute('type', 'webcontent');
  10095. $my_dep->setAttribute('adlcp:scormtype', 'asset');
  10096. $my_dep_file = $xmldoc->createElement('file');
  10097. // Check type of URL.
  10098. if ($doc_info[1] == 'remote') {
  10099. // Remote file. Save url as is.
  10100. $my_dep_file->setAttribute('href', $doc_info[0]);
  10101. $my_dep->setAttribute('xml:base', '');
  10102. } elseif ($doc_info[1] == 'local') {
  10103. switch ($doc_info[2]) {
  10104. case 'url': // Local URL - save path as url for now, don't zip file.
  10105. // Save file but as local file (retrieve from URL).
  10106. $abs_path = api_get_path(SYS_PATH).
  10107. str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  10108. $current_dir = dirname($abs_path);
  10109. $current_dir = str_replace('\\', '/', $current_dir);
  10110. $file_path = realpath($abs_path);
  10111. $file_path = str_replace('\\', '/', $file_path);
  10112. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10113. $my_dep->setAttribute('xml:base', '');
  10114. if (strstr($file_path, $main_path) !== false) {
  10115. // The calculated real path is really inside the chamilo root path.
  10116. // Reduce file path to what's under the DocumentRoot.
  10117. $file_path = substr($file_path, strlen($root_path));
  10118. $zip_files_abs[] = $file_path;
  10119. $link_updates[$my_file_path][] = [
  10120. 'orig' => $doc_info[0],
  10121. 'dest' => 'document/'.$file_path,
  10122. ];
  10123. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10124. $my_dep->setAttribute('xml:base', '');
  10125. } elseif (empty($file_path)) {
  10126. $file_path = $_SERVER['DOCUMENT_ROOT'].$abs_path;
  10127. $file_path = str_replace('//', '/', $file_path);
  10128. if (file_exists($file_path)) {
  10129. $file_path = substr($file_path, strlen($current_dir));
  10130. // We get the relative path.
  10131. $zip_files[] = $my_sub_dir.'/'.$file_path;
  10132. $link_updates[$my_file_path][] = [
  10133. 'orig' => $doc_info[0],
  10134. 'dest' => 'document/'.$file_path,
  10135. ];
  10136. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10137. $my_dep->setAttribute('xml:base', '');
  10138. }
  10139. }
  10140. break;
  10141. case 'abs':
  10142. // Absolute path from DocumentRoot. Save file and leave path as is in the zip.
  10143. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  10144. $current_dir = str_replace('\\', '/', $current_dir);
  10145. $file_path = realpath($doc_info[0]);
  10146. $file_path = str_replace('\\', '/', $file_path);
  10147. $my_dep_file->setAttribute('href', $file_path);
  10148. $my_dep->setAttribute('xml:base', '');
  10149. if (strstr($file_path, $main_path) !== false) {
  10150. // The calculated real path is really inside the chamilo root path.
  10151. // Reduce file path to what's under the DocumentRoot.
  10152. $file_path = substr($file_path, strlen($root_path));
  10153. $zip_files_abs[] = $file_path;
  10154. $link_updates[$my_file_path][] = [
  10155. 'orig' => $doc_info[0],
  10156. 'dest' => $file_path,
  10157. ];
  10158. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10159. $my_dep->setAttribute('xml:base', '');
  10160. } elseif (empty($file_path)) {
  10161. $docSysPartPath = str_replace(
  10162. api_get_path(REL_COURSE_PATH),
  10163. '',
  10164. $doc_info[0]
  10165. );
  10166. $docSysPartPathNoCourseCode = str_replace(
  10167. $_course['directory'].'/',
  10168. '',
  10169. $docSysPartPath
  10170. );
  10171. $docSysPath = api_get_path(SYS_COURSE_PATH).$docSysPartPath;
  10172. if (file_exists($docSysPath)) {
  10173. $file_path = $docSysPartPathNoCourseCode;
  10174. $zip_files[] = $my_sub_dir.'/'.$file_path;
  10175. $link_updates[$my_file_path][] = [
  10176. 'orig' => $doc_info[0],
  10177. 'dest' => $file_path,
  10178. ];
  10179. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10180. $my_dep->setAttribute('xml:base', '');
  10181. }
  10182. }
  10183. break;
  10184. case 'rel':
  10185. // Path relative to the current document. Save xml:base as current document's
  10186. // directory and save file in zip as subdir.file_path
  10187. if (substr($doc_info[0], 0, 2) === '..') {
  10188. // Relative path going up.
  10189. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  10190. $current_dir = str_replace('\\', '/', $current_dir);
  10191. $file_path = realpath($current_dir.$doc_info[0]);
  10192. $file_path = str_replace('\\', '/', $file_path);
  10193. if (strstr($file_path, $main_path) !== false) {
  10194. // The calculated real path is really inside Chamilo's root path.
  10195. // Reduce file path to what's under the DocumentRoot.
  10196. $file_path = substr($file_path, strlen($root_path));
  10197. $file_path_dest = $file_path;
  10198. // File path is courses/CHAMILO/document/....
  10199. $info_file_path = explode('/', $file_path);
  10200. if ($info_file_path[0] == 'courses') {
  10201. // Add character "/" in file path.
  10202. $file_path_dest = 'document/'.$file_path;
  10203. }
  10204. $zip_files_abs[] = $file_path;
  10205. $link_updates[$my_file_path][] = [
  10206. 'orig' => $doc_info[0],
  10207. 'dest' => $file_path_dest,
  10208. ];
  10209. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10210. $my_dep->setAttribute('xml:base', '');
  10211. }
  10212. } else {
  10213. $zip_files[] = $my_sub_dir.'/'.$doc_info[0];
  10214. $my_dep_file->setAttribute('href', $doc_info[0]);
  10215. $my_dep->setAttribute('xml:base', $my_xml_sub_dir);
  10216. }
  10217. break;
  10218. default:
  10219. $my_dep_file->setAttribute('href', $doc_info[0]); // ../../courses/
  10220. $my_dep->setAttribute('xml:base', '');
  10221. break;
  10222. }
  10223. }
  10224. $my_dep->appendChild($my_dep_file);
  10225. $resources->appendChild($my_dep);
  10226. $dependency = $xmldoc->createElement('dependency');
  10227. $dependency->setAttribute('identifierref', $res_id);
  10228. $my_resource->appendChild($dependency);
  10229. $i++;
  10230. }
  10231. $resources->appendChild($my_resource);
  10232. $zip_files[] = $my_file_path;
  10233. break;
  10234. default:
  10235. // Get the path of the file(s) from the course directory root
  10236. $my_file_path = 'non_exportable.html';
  10237. //$my_xml_file_path = api_htmlentities(api_utf8_encode($my_file_path), ENT_COMPAT, 'UTF-8');
  10238. $my_xml_file_path = $my_file_path;
  10239. $my_sub_dir = dirname($my_file_path);
  10240. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  10241. //$my_xml_sub_dir = api_htmlentities(api_utf8_encode($my_sub_dir), ENT_COMPAT, 'UTF-8');
  10242. $my_xml_sub_dir = $my_sub_dir;
  10243. // Give a <resource> child to the <resources> element.
  10244. $my_resource = $xmldoc->createElement('resource');
  10245. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  10246. $my_resource->setAttribute('type', 'webcontent');
  10247. $my_resource->setAttribute('href', $folder_name.'/'.$my_xml_file_path);
  10248. // adlcp:scormtype can be either 'sco' or 'asset'.
  10249. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  10250. // xml:base is the base directory to find the files declared in this resource.
  10251. $my_resource->setAttribute('xml:base', '');
  10252. // Give a <file> child to the <resource> element.
  10253. $my_file = $xmldoc->createElement('file');
  10254. $my_file->setAttribute('href', 'document/'.$my_xml_file_path);
  10255. $my_resource->appendChild($my_file);
  10256. $resources->appendChild($my_resource);
  10257. break;
  10258. }
  10259. }
  10260. }
  10261. $organizations->appendChild($organization);
  10262. $root->appendChild($organizations);
  10263. $root->appendChild($resources);
  10264. $xmldoc->appendChild($root);
  10265. $copyAll = api_get_configuration_value('add_all_files_in_lp_export');
  10266. // then add the file to the zip, then destroy the file (this is done automatically).
  10267. // http://www.reload.ac.uk/scormplayer.html - once done, don't forget to close FS#138
  10268. foreach ($zip_files as $file_path) {
  10269. if (empty($file_path)) {
  10270. continue;
  10271. }
  10272. $filePath = $sys_course_path.$_course['path'].'/'.$file_path;
  10273. $dest_file = $archivePath.$temp_dir_short.'/'.$file_path;
  10274. if (!empty($path_to_remove) && !empty($path_to_replace)) {
  10275. $dest_file = str_replace($path_to_remove, $path_to_replace, $dest_file);
  10276. }
  10277. $this->create_path($dest_file);
  10278. @copy($filePath, $dest_file);
  10279. // Check if the file needs a link update.
  10280. if (in_array($file_path, array_keys($link_updates))) {
  10281. $string = file_get_contents($dest_file);
  10282. unlink($dest_file);
  10283. foreach ($link_updates[$file_path] as $old_new) {
  10284. // This is an ugly hack that allows .flv files to be found by the flv player that
  10285. // will be added in document/main/inc/lib/flv_player/flv_player.swf and that needs
  10286. // to find the flv to play in document/main/, so we replace main/ in the flv path by
  10287. // ../../.. to return from inc/lib/flv_player to the document/main path.
  10288. if (substr($old_new['dest'], -3) === 'flv' &&
  10289. substr($old_new['dest'], 0, 5) === 'main/'
  10290. ) {
  10291. $old_new['dest'] = str_replace('main/', '../../../', $old_new['dest']);
  10292. } elseif (substr($old_new['dest'], -3) === 'flv' &&
  10293. substr($old_new['dest'], 0, 6) === 'video/'
  10294. ) {
  10295. $old_new['dest'] = str_replace('video/', '../../../../video/', $old_new['dest']);
  10296. }
  10297. // Fix to avoid problems with default_course_document
  10298. if (strpos('main/default_course_document', $old_new['dest']) === false) {
  10299. $newDestination = $old_new['dest'];
  10300. if (isset($old_new['replace']) && !empty($old_new['replace'])) {
  10301. $newDestination = $old_new['replace'];
  10302. }
  10303. } else {
  10304. $newDestination = str_replace('document/', '', $old_new['dest']);
  10305. }
  10306. $string = str_replace($old_new['orig'], $newDestination, $string);
  10307. // Add files inside the HTMLs
  10308. $new_path = str_replace(api_get_path(REL_COURSE_PATH), '', $old_new['orig']);
  10309. $destinationFile = $archivePath.$temp_dir_short.'/'.$old_new['dest'];
  10310. if (file_exists($sys_course_path.$new_path) && is_file($sys_course_path.$new_path)) {
  10311. copy(
  10312. $sys_course_path.$new_path,
  10313. $destinationFile
  10314. );
  10315. }
  10316. }
  10317. file_put_contents($dest_file, $string);
  10318. }
  10319. if (file_exists($filePath) && $copyAll) {
  10320. $extension = $this->get_extension($filePath);
  10321. if (in_array($extension, ['html', 'html'])) {
  10322. $containerOrigin = dirname($filePath);
  10323. $containerDestination = dirname($dest_file);
  10324. $finder = new Finder();
  10325. $finder->files()->in($containerOrigin)
  10326. ->notName('*_DELETED_*')
  10327. ->exclude('share_folder')
  10328. ->exclude('chat_files')
  10329. ->exclude('certificates')
  10330. ;
  10331. if (is_dir($containerOrigin) &&
  10332. is_dir($containerDestination)
  10333. ) {
  10334. $fs = new Filesystem();
  10335. $fs->mirror(
  10336. $containerOrigin,
  10337. $containerDestination,
  10338. $finder
  10339. );
  10340. }
  10341. }
  10342. }
  10343. }
  10344. foreach ($zip_files_abs as $file_path) {
  10345. if (empty($file_path)) {
  10346. continue;
  10347. }
  10348. if (!is_file($main_path.$file_path) || !is_readable($main_path.$file_path)) {
  10349. continue;
  10350. }
  10351. $dest_file = $archivePath.$temp_dir_short.'/document/'.$file_path;
  10352. if (strstr($file_path, 'upload/users') !== false) {
  10353. $pos = strpos($file_path, 'my_files/');
  10354. if ($pos !== false) {
  10355. $onlyDirectory = str_replace(
  10356. 'upload/users/',
  10357. '',
  10358. substr($file_path, $pos, strlen($file_path))
  10359. );
  10360. $dest_file = $archivePath.$temp_dir_short.'/document/'.$onlyDirectory;
  10361. }
  10362. }
  10363. if (strstr($file_path, 'default_course_document/') !== false) {
  10364. $replace = str_replace('/main', '', $file_path);
  10365. $dest_file = $archivePath.$temp_dir_short.'/document/'.$replace;
  10366. }
  10367. if (empty($dest_file)) {
  10368. continue;
  10369. }
  10370. $this->create_path($dest_file);
  10371. copy($main_path.$file_path, $dest_file);
  10372. // Check if the file needs a link update.
  10373. if (in_array($file_path, array_keys($link_updates))) {
  10374. $string = file_get_contents($dest_file);
  10375. unlink($dest_file);
  10376. foreach ($link_updates[$file_path] as $old_new) {
  10377. // This is an ugly hack that allows .flv files to be found by the flv player that
  10378. // will be added in document/main/inc/lib/flv_player/flv_player.swf and that needs
  10379. // to find the flv to play in document/main/, so we replace main/ in the flv path by
  10380. // ../../.. to return from inc/lib/flv_player to the document/main path.
  10381. if (substr($old_new['dest'], -3) == 'flv' &&
  10382. substr($old_new['dest'], 0, 5) == 'main/'
  10383. ) {
  10384. $old_new['dest'] = str_replace('main/', '../../../', $old_new['dest']);
  10385. }
  10386. $string = str_replace($old_new['orig'], $old_new['dest'], $string);
  10387. }
  10388. file_put_contents($dest_file, $string);
  10389. }
  10390. }
  10391. if (is_array($links_to_create)) {
  10392. foreach ($links_to_create as $file => $link) {
  10393. $content = '<!DOCTYPE html><head>
  10394. <meta charset="'.api_get_language_isocode().'" />
  10395. <title>'.$link['title'].'</title>
  10396. </head>
  10397. <body dir="'.api_get_text_direction().'">
  10398. <div style="text-align:center">
  10399. <a href="'.$link['url'].'">'.$link['title'].'</a></div>
  10400. </body>
  10401. </html>';
  10402. file_put_contents($archivePath.$temp_dir_short.'/'.$file, $content);
  10403. }
  10404. }
  10405. // Add non exportable message explanation.
  10406. $lang_not_exportable = get_lang('ThisItemIsNotExportable');
  10407. $file_content = '<!DOCTYPE html><head>
  10408. <meta charset="'.api_get_language_isocode().'" />
  10409. <title>'.$lang_not_exportable.'</title>
  10410. <meta http-equiv="Content-Type" content="text/html; charset='.api_get_system_encoding().'" />
  10411. </head>
  10412. <body dir="'.api_get_text_direction().'">';
  10413. $file_content .=
  10414. <<<EOD
  10415. <style>
  10416. .error-message {
  10417. font-family: arial, verdana, helvetica, sans-serif;
  10418. border-width: 1px;
  10419. border-style: solid;
  10420. left: 50%;
  10421. margin: 10px auto;
  10422. min-height: 30px;
  10423. padding: 5px;
  10424. right: 50%;
  10425. width: 500px;
  10426. background-color: #FFD1D1;
  10427. border-color: #FF0000;
  10428. color: #000;
  10429. }
  10430. </style>
  10431. <body>
  10432. <div class="error-message">
  10433. $lang_not_exportable
  10434. </div>
  10435. </body>
  10436. </html>
  10437. EOD;
  10438. if (!is_dir($archivePath.$temp_dir_short.'/document')) {
  10439. @mkdir($archivePath.$temp_dir_short.'/document', api_get_permissions_for_new_directories());
  10440. }
  10441. file_put_contents($archivePath.$temp_dir_short.'/document/non_exportable.html', $file_content);
  10442. // Add the extra files that go along with a SCORM package.
  10443. $main_code_path = api_get_path(SYS_CODE_PATH).'lp/packaging/';
  10444. $fs = new Filesystem();
  10445. $fs->mirror($main_code_path, $archivePath.$temp_dir_short);
  10446. // Finalize the imsmanifest structure, add to the zip, then return the zip.
  10447. $manifest = @$xmldoc->saveXML();
  10448. $manifest = api_utf8_decode_xml($manifest); // The manifest gets the system encoding now.
  10449. file_put_contents($archivePath.'/'.$temp_dir_short.'/imsmanifest.xml', $manifest);
  10450. $zip_folder->add(
  10451. $archivePath.'/'.$temp_dir_short,
  10452. PCLZIP_OPT_REMOVE_PATH,
  10453. $archivePath.'/'.$temp_dir_short.'/'
  10454. );
  10455. // Clean possible temporary files.
  10456. foreach ($files_cleanup as $file) {
  10457. $res = unlink($file);
  10458. if ($res === false) {
  10459. error_log(
  10460. 'Could not delete temp file '.$file.' '.__FILE__.' '.__LINE__,
  10461. 0
  10462. );
  10463. }
  10464. }
  10465. $name = api_replace_dangerous_char($this->get_name()).'.zip';
  10466. DocumentManager::file_send_for_download($temp_zip_file, true, $name);
  10467. }
  10468. /**
  10469. * @param int $lp_id
  10470. *
  10471. * @return bool
  10472. */
  10473. public function scorm_export_to_pdf($lp_id)
  10474. {
  10475. $lp_id = (int) $lp_id;
  10476. $files_to_export = [];
  10477. $sessionId = api_get_session_id();
  10478. $course_data = api_get_course_info($this->cc);
  10479. if (!empty($course_data)) {
  10480. $scorm_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/scorm/'.$this->path;
  10481. $list = self::get_flat_ordered_items_list($lp_id);
  10482. if (!empty($list)) {
  10483. foreach ($list as $item_id) {
  10484. $item = $this->items[$item_id];
  10485. switch ($item->type) {
  10486. case 'document':
  10487. // Getting documents from a LP with chamilo documents
  10488. $file_data = DocumentManager::get_document_data_by_id($item->path, $this->cc);
  10489. // Try loading document from the base course.
  10490. if (empty($file_data) && !empty($sessionId)) {
  10491. $file_data = DocumentManager::get_document_data_by_id(
  10492. $item->path,
  10493. $this->cc,
  10494. false,
  10495. 0
  10496. );
  10497. }
  10498. $file_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/document'.$file_data['path'];
  10499. if (file_exists($file_path)) {
  10500. $files_to_export[] = [
  10501. 'title' => $item->get_title(),
  10502. 'path' => $file_path,
  10503. ];
  10504. }
  10505. break;
  10506. case 'asset': //commes from a scorm package generated by chamilo
  10507. case 'sco':
  10508. $file_path = $scorm_path.'/'.$item->path;
  10509. if (file_exists($file_path)) {
  10510. $files_to_export[] = [
  10511. 'title' => $item->get_title(),
  10512. 'path' => $file_path,
  10513. ];
  10514. }
  10515. break;
  10516. case 'dir':
  10517. $files_to_export[] = [
  10518. 'title' => $item->get_title(),
  10519. 'path' => null,
  10520. ];
  10521. break;
  10522. }
  10523. }
  10524. }
  10525. $pdf = new PDF();
  10526. $result = $pdf->html_to_pdf(
  10527. $files_to_export,
  10528. $this->name,
  10529. $this->cc,
  10530. true,
  10531. true,
  10532. true,
  10533. $this->get_name()
  10534. );
  10535. return $result;
  10536. }
  10537. return false;
  10538. }
  10539. /**
  10540. * Temp function to be moved in main_api or the best place around for this.
  10541. * Creates a file path if it doesn't exist.
  10542. *
  10543. * @param string $path
  10544. */
  10545. public function create_path($path)
  10546. {
  10547. $path_bits = explode('/', dirname($path));
  10548. // IS_WINDOWS_OS has been defined in main_api.lib.php
  10549. $path_built = IS_WINDOWS_OS ? '' : '/';
  10550. foreach ($path_bits as $bit) {
  10551. if (!empty($bit)) {
  10552. $new_path = $path_built.$bit;
  10553. if (is_dir($new_path)) {
  10554. $path_built = $new_path.'/';
  10555. } else {
  10556. mkdir($new_path, api_get_permissions_for_new_directories());
  10557. $path_built = $new_path.'/';
  10558. }
  10559. }
  10560. }
  10561. }
  10562. /**
  10563. * Delete the image relative to this learning path. No parameter. Only works on instanciated object.
  10564. *
  10565. * @return bool The results of the unlink function, or false if there was no image to start with
  10566. */
  10567. public function delete_lp_image()
  10568. {
  10569. $img = $this->get_preview_image();
  10570. if ($img != '') {
  10571. $del_file = $this->get_preview_image_path(null, 'sys');
  10572. if (isset($del_file) && file_exists($del_file)) {
  10573. $del_file_2 = $this->get_preview_image_path(64, 'sys');
  10574. if (file_exists($del_file_2)) {
  10575. unlink($del_file_2);
  10576. }
  10577. $this->set_preview_image('');
  10578. return @unlink($del_file);
  10579. }
  10580. }
  10581. return false;
  10582. }
  10583. /**
  10584. * Uploads an author image to the upload/learning_path/images directory.
  10585. *
  10586. * @param array The image array, coming from the $_FILES superglobal
  10587. *
  10588. * @return bool True on success, false on error
  10589. */
  10590. public function upload_image($image_array)
  10591. {
  10592. if (!empty($image_array['name'])) {
  10593. $upload_ok = process_uploaded_file($image_array);
  10594. $has_attachment = true;
  10595. }
  10596. if ($upload_ok && $has_attachment) {
  10597. $courseDir = api_get_course_path().'/upload/learning_path/images';
  10598. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  10599. $updir = $sys_course_path.$courseDir;
  10600. // Try to add an extension to the file if it hasn't one.
  10601. $new_file_name = add_ext_on_mime(stripslashes($image_array['name']), $image_array['type']);
  10602. if (filter_extension($new_file_name)) {
  10603. $file_extension = explode('.', $image_array['name']);
  10604. $file_extension = strtolower($file_extension[count($file_extension) - 1]);
  10605. $filename = uniqid('');
  10606. $new_file_name = $filename.'.'.$file_extension;
  10607. $new_path = $updir.'/'.$new_file_name;
  10608. // Resize the image.
  10609. $temp = new Image($image_array['tmp_name']);
  10610. $temp->resize(104);
  10611. $result = $temp->send_image($new_path);
  10612. // Storing the image filename.
  10613. if ($result) {
  10614. $this->set_preview_image($new_file_name);
  10615. //Resize to 64px to use on course homepage
  10616. $temp->resize(64);
  10617. $temp->send_image($updir.'/'.$filename.'.64.'.$file_extension);
  10618. return true;
  10619. }
  10620. }
  10621. }
  10622. return false;
  10623. }
  10624. /**
  10625. * @param int $lp_id
  10626. * @param string $status
  10627. */
  10628. public function set_autolaunch($lp_id, $status)
  10629. {
  10630. $course_id = api_get_course_int_id();
  10631. $lp_id = (int) $lp_id;
  10632. $status = (int) $status;
  10633. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  10634. // Setting everything to autolaunch = 0
  10635. $attributes['autolaunch'] = 0;
  10636. $where = [
  10637. 'session_id = ? AND c_id = ? ' => [
  10638. api_get_session_id(),
  10639. $course_id,
  10640. ],
  10641. ];
  10642. Database::update($lp_table, $attributes, $where);
  10643. if ($status == 1) {
  10644. //Setting my lp_id to autolaunch = 1
  10645. $attributes['autolaunch'] = 1;
  10646. $where = [
  10647. 'iid = ? AND session_id = ? AND c_id = ?' => [
  10648. $lp_id,
  10649. api_get_session_id(),
  10650. $course_id,
  10651. ],
  10652. ];
  10653. Database::update($lp_table, $attributes, $where);
  10654. }
  10655. }
  10656. /**
  10657. * Gets previous_item_id for the next element of the lp_item table.
  10658. *
  10659. * @author Isaac flores paz
  10660. *
  10661. * @return int Previous item ID
  10662. */
  10663. public function select_previous_item_id()
  10664. {
  10665. $course_id = api_get_course_int_id();
  10666. $table_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  10667. // Get the max order of the items
  10668. $sql = "SELECT max(display_order) AS display_order FROM $table_lp_item
  10669. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  10670. $rs_max_order = Database::query($sql);
  10671. $row_max_order = Database::fetch_object($rs_max_order);
  10672. $max_order = $row_max_order->display_order;
  10673. // Get the previous item ID
  10674. $sql = "SELECT iid as previous FROM $table_lp_item
  10675. WHERE
  10676. c_id = $course_id AND
  10677. lp_id = ".$this->lp_id." AND
  10678. display_order = '$max_order' ";
  10679. $rs_max = Database::query($sql);
  10680. $row_max = Database::fetch_object($rs_max);
  10681. // Return the previous item ID
  10682. return $row_max->previous;
  10683. }
  10684. /**
  10685. * Copies an LP.
  10686. */
  10687. public function copy()
  10688. {
  10689. // Course builder
  10690. $cb = new CourseBuilder();
  10691. //Setting tools that will be copied
  10692. $cb->set_tools_to_build(['learnpaths']);
  10693. //Setting elements that will be copied
  10694. $cb->set_tools_specific_id_list(
  10695. ['learnpaths' => [$this->lp_id]]
  10696. );
  10697. $course = $cb->build();
  10698. //Course restorer
  10699. $course_restorer = new CourseRestorer($course);
  10700. $course_restorer->set_add_text_in_items(true);
  10701. $course_restorer->set_tool_copy_settings(
  10702. ['learnpaths' => ['reset_dates' => true]]
  10703. );
  10704. $course_restorer->restore(
  10705. api_get_course_id(),
  10706. api_get_session_id(),
  10707. false,
  10708. false
  10709. );
  10710. }
  10711. /**
  10712. * Verify document size.
  10713. *
  10714. * @param string $s
  10715. *
  10716. * @return bool
  10717. */
  10718. public static function verify_document_size($s)
  10719. {
  10720. $post_max = ini_get('post_max_size');
  10721. if (substr($post_max, -1, 1) == 'M') {
  10722. $post_max = intval(substr($post_max, 0, -1)) * 1024 * 1024;
  10723. } elseif (substr($post_max, -1, 1) == 'G') {
  10724. $post_max = intval(substr($post_max, 0, -1)) * 1024 * 1024 * 1024;
  10725. }
  10726. $upl_max = ini_get('upload_max_filesize');
  10727. if (substr($upl_max, -1, 1) == 'M') {
  10728. $upl_max = intval(substr($upl_max, 0, -1)) * 1024 * 1024;
  10729. } elseif (substr($upl_max, -1, 1) == 'G') {
  10730. $upl_max = intval(substr($upl_max, 0, -1)) * 1024 * 1024 * 1024;
  10731. }
  10732. $documents_total_space = DocumentManager::documents_total_space();
  10733. $course_max_space = DocumentManager::get_course_quota();
  10734. $total_size = filesize($s) + $documents_total_space;
  10735. if (filesize($s) > $post_max || filesize($s) > $upl_max || $total_size > $course_max_space) {
  10736. return true;
  10737. }
  10738. return false;
  10739. }
  10740. /**
  10741. * Clear LP prerequisites.
  10742. */
  10743. public function clear_prerequisites()
  10744. {
  10745. $course_id = $this->get_course_int_id();
  10746. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  10747. $lp_id = $this->get_id();
  10748. // Cleaning prerequisites
  10749. $sql = "UPDATE $tbl_lp_item SET prerequisite = ''
  10750. WHERE c_id = $course_id AND lp_id = $lp_id";
  10751. Database::query($sql);
  10752. // Cleaning mastery score for exercises
  10753. $sql = "UPDATE $tbl_lp_item SET mastery_score = ''
  10754. WHERE c_id = $course_id AND lp_id = $lp_id AND item_type = 'quiz'";
  10755. Database::query($sql);
  10756. }
  10757. public function set_previous_step_as_prerequisite_for_all_items()
  10758. {
  10759. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  10760. $course_id = $this->get_course_int_id();
  10761. $lp_id = $this->get_id();
  10762. if (!empty($this->items)) {
  10763. $previous_item_id = null;
  10764. $previous_item_max = 0;
  10765. $previous_item_type = null;
  10766. $last_item_not_dir = null;
  10767. $last_item_not_dir_type = null;
  10768. $last_item_not_dir_max = null;
  10769. foreach ($this->ordered_items as $itemId) {
  10770. $item = $this->getItem($itemId);
  10771. // if there was a previous item... (otherwise jump to set it)
  10772. if (!empty($previous_item_id)) {
  10773. $current_item_id = $item->get_id(); //save current id
  10774. if ($item->get_type() != 'dir') {
  10775. // Current item is not a folder, so it qualifies to get a prerequisites
  10776. if ($last_item_not_dir_type == 'quiz') {
  10777. // if previous is quiz, mark its max score as default score to be achieved
  10778. $sql = "UPDATE $tbl_lp_item SET mastery_score = '$last_item_not_dir_max'
  10779. WHERE c_id = $course_id AND lp_id = $lp_id AND iid = $last_item_not_dir";
  10780. Database::query($sql);
  10781. }
  10782. // now simply update the prerequisite to set it to the last non-chapter item
  10783. $sql = "UPDATE $tbl_lp_item SET prerequisite = '$last_item_not_dir'
  10784. WHERE c_id = $course_id AND lp_id = $lp_id AND iid = $current_item_id";
  10785. Database::query($sql);
  10786. // record item as 'non-chapter' reference
  10787. $last_item_not_dir = $item->get_id();
  10788. $last_item_not_dir_type = $item->get_type();
  10789. $last_item_not_dir_max = $item->get_max();
  10790. }
  10791. } else {
  10792. if ($item->get_type() != 'dir') {
  10793. // Current item is not a folder (but it is the first item) so record as last "non-chapter" item
  10794. $last_item_not_dir = $item->get_id();
  10795. $last_item_not_dir_type = $item->get_type();
  10796. $last_item_not_dir_max = $item->get_max();
  10797. }
  10798. }
  10799. // Saving the item as "previous item" for the next loop
  10800. $previous_item_id = $item->get_id();
  10801. $previous_item_max = $item->get_max();
  10802. $previous_item_type = $item->get_type();
  10803. }
  10804. }
  10805. }
  10806. /**
  10807. * @param array $params
  10808. *
  10809. * @throws \Doctrine\ORM\OptimisticLockException
  10810. *
  10811. * @return int
  10812. */
  10813. public static function createCategory($params)
  10814. {
  10815. $em = Database::getManager();
  10816. $item = new CLpCategory();
  10817. $item->setName($params['name']);
  10818. $item->setCId($params['c_id']);
  10819. $em->persist($item);
  10820. $em->flush();
  10821. api_item_property_update(
  10822. api_get_course_info(),
  10823. TOOL_LEARNPATH_CATEGORY,
  10824. $item->getId(),
  10825. 'visible',
  10826. api_get_user_id()
  10827. );
  10828. return $item->getId();
  10829. }
  10830. /**
  10831. * @param array $params
  10832. *
  10833. * @throws \Doctrine\ORM\ORMException
  10834. * @throws \Doctrine\ORM\OptimisticLockException
  10835. * @throws \Doctrine\ORM\TransactionRequiredException
  10836. */
  10837. public static function updateCategory($params)
  10838. {
  10839. $em = Database::getManager();
  10840. /** @var CLpCategory $item */
  10841. $item = $em->find('ChamiloCourseBundle:CLpCategory', $params['id']);
  10842. if ($item) {
  10843. $item->setName($params['name']);
  10844. $em->merge($item);
  10845. $em->flush();
  10846. }
  10847. }
  10848. /**
  10849. * @param int $id
  10850. *
  10851. * @throws \Doctrine\ORM\ORMException
  10852. * @throws \Doctrine\ORM\OptimisticLockException
  10853. * @throws \Doctrine\ORM\TransactionRequiredException
  10854. */
  10855. public static function moveUpCategory($id)
  10856. {
  10857. $id = (int) $id;
  10858. $em = Database::getManager();
  10859. /** @var CLpCategory $item */
  10860. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  10861. if ($item) {
  10862. $position = $item->getPosition() - 1;
  10863. $item->setPosition($position);
  10864. $em->persist($item);
  10865. $em->flush();
  10866. }
  10867. }
  10868. /**
  10869. * @param int $id
  10870. *
  10871. * @throws \Doctrine\ORM\ORMException
  10872. * @throws \Doctrine\ORM\OptimisticLockException
  10873. * @throws \Doctrine\ORM\TransactionRequiredException
  10874. */
  10875. public static function moveDownCategory($id)
  10876. {
  10877. $id = (int) $id;
  10878. $em = Database::getManager();
  10879. /** @var CLpCategory $item */
  10880. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  10881. if ($item) {
  10882. $position = $item->getPosition() + 1;
  10883. $item->setPosition($position);
  10884. $em->persist($item);
  10885. $em->flush();
  10886. }
  10887. }
  10888. /**
  10889. * @param int $courseId
  10890. *
  10891. * @throws \Doctrine\ORM\Query\QueryException
  10892. *
  10893. * @return int|mixed
  10894. */
  10895. public static function getCountCategories($courseId)
  10896. {
  10897. if (empty($courseId)) {
  10898. return 0;
  10899. }
  10900. $em = Database::getManager();
  10901. $query = $em->createQuery('SELECT COUNT(u.id) FROM ChamiloCourseBundle:CLpCategory u WHERE u.cId = :id');
  10902. $query->setParameter('id', $courseId);
  10903. return $query->getSingleScalarResult();
  10904. }
  10905. /**
  10906. * @param int $courseId
  10907. *
  10908. * @return mixed
  10909. */
  10910. public static function getCategories($courseId)
  10911. {
  10912. $em = Database::getManager();
  10913. // Using doctrine extensions
  10914. /** @var SortableRepository $repo */
  10915. $repo = $em->getRepository('ChamiloCourseBundle:CLpCategory');
  10916. $items = $repo
  10917. ->getBySortableGroupsQuery(['cId' => $courseId])
  10918. ->getResult();
  10919. return $items;
  10920. }
  10921. /**
  10922. * @param int $id
  10923. *
  10924. * @throws \Doctrine\ORM\ORMException
  10925. * @throws \Doctrine\ORM\OptimisticLockException
  10926. * @throws \Doctrine\ORM\TransactionRequiredException
  10927. *
  10928. * @return CLpCategory
  10929. */
  10930. public static function getCategory($id)
  10931. {
  10932. $id = (int) $id;
  10933. $em = Database::getManager();
  10934. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  10935. return $item;
  10936. }
  10937. /**
  10938. * @param int $courseId
  10939. *
  10940. * @return array
  10941. */
  10942. public static function getCategoryByCourse($courseId)
  10943. {
  10944. $em = Database::getManager();
  10945. $items = $em->getRepository('ChamiloCourseBundle:CLpCategory')->findBy(
  10946. ['cId' => $courseId]
  10947. );
  10948. return $items;
  10949. }
  10950. /**
  10951. * @param int $id
  10952. *
  10953. * @throws \Doctrine\ORM\ORMException
  10954. * @throws \Doctrine\ORM\OptimisticLockException
  10955. * @throws \Doctrine\ORM\TransactionRequiredException
  10956. *
  10957. * @return mixed
  10958. */
  10959. public static function deleteCategory($id)
  10960. {
  10961. $em = Database::getManager();
  10962. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  10963. if ($item) {
  10964. $courseId = $item->getCId();
  10965. $query = $em->createQuery('SELECT u FROM ChamiloCourseBundle:CLp u WHERE u.cId = :id AND u.categoryId = :catId');
  10966. $query->setParameter('id', $courseId);
  10967. $query->setParameter('catId', $item->getId());
  10968. $lps = $query->getResult();
  10969. // Setting category = 0.
  10970. if ($lps) {
  10971. foreach ($lps as $lpItem) {
  10972. $lpItem->setCategoryId(0);
  10973. }
  10974. }
  10975. // Removing category.
  10976. $em->remove($item);
  10977. $em->flush();
  10978. $courseInfo = api_get_course_info_by_id($courseId);
  10979. $sessionId = api_get_session_id();
  10980. // Delete link tool
  10981. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  10982. $link = 'lp/lp_controller.php?cidReq='.$courseInfo['code'].'&id_session='.$sessionId.'&gidReq=0&gradebook=0&origin=&action=view_category&id='.$id;
  10983. // Delete tools
  10984. $sql = "DELETE FROM $tbl_tool
  10985. WHERE c_id = ".$courseId." AND (link LIKE '$link%' AND image='lp_category.gif')";
  10986. Database::query($sql);
  10987. return true;
  10988. }
  10989. return false;
  10990. }
  10991. /**
  10992. * @param int $courseId
  10993. * @param bool $addSelectOption
  10994. *
  10995. * @return mixed
  10996. */
  10997. public static function getCategoryFromCourseIntoSelect($courseId, $addSelectOption = false)
  10998. {
  10999. $items = self::getCategoryByCourse($courseId);
  11000. $cats = [];
  11001. if ($addSelectOption) {
  11002. $cats = [get_lang('SelectACategory')];
  11003. }
  11004. if (!empty($items)) {
  11005. foreach ($items as $cat) {
  11006. $cats[$cat->getId()] = $cat->getName();
  11007. }
  11008. }
  11009. return $cats;
  11010. }
  11011. /**
  11012. * @param string $courseCode
  11013. * @param int $lpId
  11014. * @param int $user_id
  11015. *
  11016. * @return learnpath
  11017. */
  11018. public static function getLpFromSession($courseCode, $lpId, $user_id)
  11019. {
  11020. $debug = 0;
  11021. $learnPath = null;
  11022. $lpObject = Session::read('lpobject');
  11023. if ($lpObject !== null) {
  11024. $learnPath = UnserializeApi::unserialize('lp', $lpObject);
  11025. if ($debug) {
  11026. error_log('getLpFromSession: unserialize');
  11027. error_log('------getLpFromSession------');
  11028. error_log('------unserialize------');
  11029. error_log("lp_view_session_id: ".$learnPath->lp_view_session_id);
  11030. error_log("api_get_sessionid: ".api_get_session_id());
  11031. }
  11032. }
  11033. if (!is_object($learnPath)) {
  11034. $learnPath = new learnpath($courseCode, $lpId, $user_id);
  11035. if ($debug) {
  11036. error_log('------getLpFromSession------');
  11037. error_log('getLpFromSession: create new learnpath');
  11038. error_log("create new LP with $courseCode - $lpId - $user_id");
  11039. error_log("lp_view_session_id: ".$learnPath->lp_view_session_id);
  11040. error_log("api_get_sessionid: ".api_get_session_id());
  11041. }
  11042. }
  11043. return $learnPath;
  11044. }
  11045. /**
  11046. * @param int $itemId
  11047. *
  11048. * @return learnpathItem|false
  11049. */
  11050. public function getItem($itemId)
  11051. {
  11052. if (isset($this->items[$itemId]) && is_object($this->items[$itemId])) {
  11053. return $this->items[$itemId];
  11054. }
  11055. return false;
  11056. }
  11057. /**
  11058. * @return int
  11059. */
  11060. public function getCurrentAttempt()
  11061. {
  11062. $attempt = $this->getItem($this->get_current_item_id());
  11063. if ($attempt) {
  11064. $attemptId = $attempt->get_attempt_id();
  11065. return $attemptId;
  11066. }
  11067. return 0;
  11068. }
  11069. /**
  11070. * @return int
  11071. */
  11072. public function getCategoryId()
  11073. {
  11074. return (int) $this->categoryId;
  11075. }
  11076. /**
  11077. * @param int $categoryId
  11078. *
  11079. * @return bool
  11080. */
  11081. public function setCategoryId($categoryId)
  11082. {
  11083. $this->categoryId = (int) $categoryId;
  11084. $table = Database::get_course_table(TABLE_LP_MAIN);
  11085. $lp_id = $this->get_id();
  11086. $sql = "UPDATE $table SET category_id = ".$this->categoryId."
  11087. WHERE iid = $lp_id";
  11088. Database::query($sql);
  11089. return true;
  11090. }
  11091. /**
  11092. * Get whether this is a learning path with the possibility to subscribe
  11093. * users or not.
  11094. *
  11095. * @return int
  11096. */
  11097. public function getSubscribeUsers()
  11098. {
  11099. return $this->subscribeUsers;
  11100. }
  11101. /**
  11102. * Set whether this is a learning path with the possibility to subscribe
  11103. * users or not.
  11104. *
  11105. * @param int $value (0 = false, 1 = true)
  11106. *
  11107. * @return bool
  11108. */
  11109. public function setSubscribeUsers($value)
  11110. {
  11111. $this->subscribeUsers = (int) $value;
  11112. $table = Database::get_course_table(TABLE_LP_MAIN);
  11113. $lp_id = $this->get_id();
  11114. $sql = "UPDATE $table SET subscribe_users = ".$this->subscribeUsers."
  11115. WHERE iid = $lp_id";
  11116. Database::query($sql);
  11117. return true;
  11118. }
  11119. /**
  11120. * Calculate the count of stars for a user in this LP
  11121. * This calculation is based on the following rules:
  11122. * - the student gets one star when he gets to 50% of the learning path
  11123. * - the student gets a second star when the average score of all tests inside the learning path >= 50%
  11124. * - the student gets a third star when the average score of all tests inside the learning path >= 80%
  11125. * - the student gets the final star when the score for the *last* test is >= 80%.
  11126. *
  11127. * @param int $sessionId Optional. The session ID
  11128. *
  11129. * @return int The count of stars
  11130. */
  11131. public function getCalculateStars($sessionId = 0)
  11132. {
  11133. $stars = 0;
  11134. $progress = self::getProgress(
  11135. $this->lp_id,
  11136. $this->user_id,
  11137. $this->course_int_id,
  11138. $sessionId
  11139. );
  11140. if ($progress >= 50) {
  11141. $stars++;
  11142. }
  11143. // Calculate stars chapters evaluation
  11144. $exercisesItems = $this->getExercisesItems();
  11145. if (!empty($exercisesItems)) {
  11146. $totalResult = 0;
  11147. foreach ($exercisesItems as $exerciseItem) {
  11148. $exerciseResultInfo = Event::getExerciseResultsByUser(
  11149. $this->user_id,
  11150. $exerciseItem->path,
  11151. $this->course_int_id,
  11152. $sessionId,
  11153. $this->lp_id,
  11154. $exerciseItem->db_id
  11155. );
  11156. $exerciseResultInfo = end($exerciseResultInfo);
  11157. if (!$exerciseResultInfo) {
  11158. continue;
  11159. }
  11160. if (!empty($exerciseResultInfo['exe_weighting'])) {
  11161. $exerciseResult = $exerciseResultInfo['exe_result'] * 100 / $exerciseResultInfo['exe_weighting'];
  11162. } else {
  11163. $exerciseResult = 0;
  11164. }
  11165. $totalResult += $exerciseResult;
  11166. }
  11167. $totalExerciseAverage = $totalResult / (count($exercisesItems) > 0 ? count($exercisesItems) : 1);
  11168. if ($totalExerciseAverage >= 50) {
  11169. $stars++;
  11170. }
  11171. if ($totalExerciseAverage >= 80) {
  11172. $stars++;
  11173. }
  11174. }
  11175. // Calculate star for final evaluation
  11176. $finalEvaluationItem = $this->getFinalEvaluationItem();
  11177. if (!empty($finalEvaluationItem)) {
  11178. $evaluationResultInfo = Event::getExerciseResultsByUser(
  11179. $this->user_id,
  11180. $finalEvaluationItem->path,
  11181. $this->course_int_id,
  11182. $sessionId,
  11183. $this->lp_id,
  11184. $finalEvaluationItem->db_id
  11185. );
  11186. $evaluationResultInfo = end($evaluationResultInfo);
  11187. if ($evaluationResultInfo) {
  11188. $evaluationResult = $evaluationResultInfo['exe_result'] * 100 / $evaluationResultInfo['exe_weighting'];
  11189. if ($evaluationResult >= 80) {
  11190. $stars++;
  11191. }
  11192. }
  11193. }
  11194. return $stars;
  11195. }
  11196. /**
  11197. * Get the items of exercise type.
  11198. *
  11199. * @return array The items. Otherwise return false
  11200. */
  11201. public function getExercisesItems()
  11202. {
  11203. $exercises = [];
  11204. foreach ($this->items as $item) {
  11205. if ($item->type != 'quiz') {
  11206. continue;
  11207. }
  11208. $exercises[] = $item;
  11209. }
  11210. array_pop($exercises);
  11211. return $exercises;
  11212. }
  11213. /**
  11214. * Get the item of exercise type (evaluation type).
  11215. *
  11216. * @return array The final evaluation. Otherwise return false
  11217. */
  11218. public function getFinalEvaluationItem()
  11219. {
  11220. $exercises = [];
  11221. foreach ($this->items as $item) {
  11222. if ($item->type != 'quiz') {
  11223. continue;
  11224. }
  11225. $exercises[] = $item;
  11226. }
  11227. return array_pop($exercises);
  11228. }
  11229. /**
  11230. * Calculate the total points achieved for the current user in this learning path.
  11231. *
  11232. * @param int $sessionId Optional. The session Id
  11233. *
  11234. * @return int
  11235. */
  11236. public function getCalculateScore($sessionId = 0)
  11237. {
  11238. // Calculate stars chapters evaluation
  11239. $exercisesItems = $this->getExercisesItems();
  11240. $finalEvaluationItem = $this->getFinalEvaluationItem();
  11241. $totalExercisesResult = 0;
  11242. $totalEvaluationResult = 0;
  11243. if ($exercisesItems !== false) {
  11244. foreach ($exercisesItems as $exerciseItem) {
  11245. $exerciseResultInfo = Event::getExerciseResultsByUser(
  11246. $this->user_id,
  11247. $exerciseItem->path,
  11248. $this->course_int_id,
  11249. $sessionId,
  11250. $this->lp_id,
  11251. $exerciseItem->db_id
  11252. );
  11253. $exerciseResultInfo = end($exerciseResultInfo);
  11254. if (!$exerciseResultInfo) {
  11255. continue;
  11256. }
  11257. $totalExercisesResult += $exerciseResultInfo['exe_result'];
  11258. }
  11259. }
  11260. if (!empty($finalEvaluationItem)) {
  11261. $evaluationResultInfo = Event::getExerciseResultsByUser(
  11262. $this->user_id,
  11263. $finalEvaluationItem->path,
  11264. $this->course_int_id,
  11265. $sessionId,
  11266. $this->lp_id,
  11267. $finalEvaluationItem->db_id
  11268. );
  11269. $evaluationResultInfo = end($evaluationResultInfo);
  11270. if ($evaluationResultInfo) {
  11271. $totalEvaluationResult += $evaluationResultInfo['exe_result'];
  11272. }
  11273. }
  11274. return $totalExercisesResult + $totalEvaluationResult;
  11275. }
  11276. /**
  11277. * Check if URL is not allowed to be show in a iframe.
  11278. *
  11279. * @param string $src
  11280. *
  11281. * @return string
  11282. */
  11283. public function fixBlockedLinks($src)
  11284. {
  11285. $urlInfo = parse_url($src);
  11286. $platformProtocol = 'https';
  11287. if (strpos(api_get_path(WEB_CODE_PATH), 'https') === false) {
  11288. $platformProtocol = 'http';
  11289. }
  11290. $protocolFixApplied = false;
  11291. //Scheme validation to avoid "Notices" when the lesson doesn't contain a valid scheme
  11292. $scheme = isset($urlInfo['scheme']) ? $urlInfo['scheme'] : null;
  11293. $host = isset($urlInfo['host']) ? $urlInfo['host'] : null;
  11294. if ($platformProtocol != $scheme) {
  11295. Session::write('x_frame_source', $src);
  11296. $src = 'blank.php?error=x_frames_options';
  11297. $protocolFixApplied = true;
  11298. }
  11299. if ($protocolFixApplied == false) {
  11300. if (strpos(api_get_path(WEB_PATH), $host) === false) {
  11301. // Check X-Frame-Options
  11302. $ch = curl_init();
  11303. $options = [
  11304. CURLOPT_URL => $src,
  11305. CURLOPT_RETURNTRANSFER => true,
  11306. CURLOPT_HEADER => true,
  11307. CURLOPT_FOLLOWLOCATION => true,
  11308. CURLOPT_ENCODING => "",
  11309. CURLOPT_AUTOREFERER => true,
  11310. CURLOPT_CONNECTTIMEOUT => 120,
  11311. CURLOPT_TIMEOUT => 120,
  11312. CURLOPT_MAXREDIRS => 10,
  11313. ];
  11314. $proxySettings = api_get_configuration_value('proxy_settings');
  11315. if (!empty($proxySettings) &&
  11316. isset($proxySettings['curl_setopt_array'])
  11317. ) {
  11318. $options[CURLOPT_PROXY] = $proxySettings['curl_setopt_array']['CURLOPT_PROXY'];
  11319. $options[CURLOPT_PROXYPORT] = $proxySettings['curl_setopt_array']['CURLOPT_PROXYPORT'];
  11320. }
  11321. curl_setopt_array($ch, $options);
  11322. $response = curl_exec($ch);
  11323. $httpCode = curl_getinfo($ch);
  11324. $headers = substr($response, 0, $httpCode['header_size']);
  11325. $error = false;
  11326. if (stripos($headers, 'X-Frame-Options: DENY') > -1
  11327. //|| stripos($headers, 'X-Frame-Options: SAMEORIGIN') > -1
  11328. ) {
  11329. $error = true;
  11330. }
  11331. if ($error) {
  11332. Session::write('x_frame_source', $src);
  11333. $src = 'blank.php?error=x_frames_options';
  11334. }
  11335. }
  11336. }
  11337. return $src;
  11338. }
  11339. /**
  11340. * Check if this LP has a created forum in the basis course.
  11341. *
  11342. * @return bool
  11343. */
  11344. public function lpHasForum()
  11345. {
  11346. $forumTable = Database::get_course_table(TABLE_FORUM);
  11347. $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  11348. $fakeFrom = "
  11349. $forumTable f
  11350. INNER JOIN $itemProperty ip
  11351. ON (f.forum_id = ip.ref AND f.c_id = ip.c_id)
  11352. ";
  11353. $resultData = Database::select(
  11354. 'COUNT(f.iid) AS qty',
  11355. $fakeFrom,
  11356. [
  11357. 'where' => [
  11358. 'ip.visibility != ? AND ' => 2,
  11359. 'ip.tool = ? AND ' => TOOL_FORUM,
  11360. 'f.c_id = ? AND ' => intval($this->course_int_id),
  11361. 'f.lp_id = ?' => intval($this->lp_id),
  11362. ],
  11363. ],
  11364. 'first'
  11365. );
  11366. return $resultData['qty'] > 0;
  11367. }
  11368. /**
  11369. * Get the forum for this learning path.
  11370. *
  11371. * @param int $sessionId
  11372. *
  11373. * @return bool
  11374. */
  11375. public function getForum($sessionId = 0)
  11376. {
  11377. $forumTable = Database::get_course_table(TABLE_FORUM);
  11378. $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  11379. $fakeFrom = "$forumTable f
  11380. INNER JOIN $itemProperty ip ";
  11381. if ($this->lp_session_id == 0) {
  11382. $fakeFrom .= "
  11383. ON (
  11384. f.forum_id = ip.ref AND f.c_id = ip.c_id AND (
  11385. f.session_id = ip.session_id OR ip.session_id IS NULL
  11386. )
  11387. )
  11388. ";
  11389. } else {
  11390. $fakeFrom .= "
  11391. ON (
  11392. f.forum_id = ip.ref AND f.c_id = ip.c_id AND f.session_id = ip.session_id
  11393. )
  11394. ";
  11395. }
  11396. $resultData = Database::select(
  11397. 'f.*',
  11398. $fakeFrom,
  11399. [
  11400. 'where' => [
  11401. 'ip.visibility != ? AND ' => 2,
  11402. 'ip.tool = ? AND ' => TOOL_FORUM,
  11403. 'f.session_id = ? AND ' => $sessionId,
  11404. 'f.c_id = ? AND ' => intval($this->course_int_id),
  11405. 'f.lp_id = ?' => intval($this->lp_id),
  11406. ],
  11407. ],
  11408. 'first'
  11409. );
  11410. if (empty($resultData)) {
  11411. return false;
  11412. }
  11413. return $resultData;
  11414. }
  11415. /**
  11416. * Create a forum for this learning path.
  11417. *
  11418. * @param int $forumCategoryId
  11419. *
  11420. * @return int The forum ID if was created. Otherwise return false
  11421. */
  11422. public function createForum($forumCategoryId)
  11423. {
  11424. require_once api_get_path(SYS_CODE_PATH).'/forum/forumfunction.inc.php';
  11425. $forumId = store_forum(
  11426. [
  11427. 'lp_id' => $this->lp_id,
  11428. 'forum_title' => $this->name,
  11429. 'forum_comment' => null,
  11430. 'forum_category' => (int) $forumCategoryId,
  11431. 'students_can_edit_group' => ['students_can_edit' => 0],
  11432. 'allow_new_threads_group' => ['allow_new_threads' => 0],
  11433. 'default_view_type_group' => ['default_view_type' => 'flat'],
  11434. 'group_forum' => 0,
  11435. 'public_private_group_forum_group' => ['public_private_group_forum' => 'public'],
  11436. ],
  11437. [],
  11438. true
  11439. );
  11440. return $forumId;
  11441. }
  11442. /**
  11443. * Get the LP Final Item form.
  11444. *
  11445. * @throws Exception
  11446. * @throws HTML_QuickForm_Error
  11447. *
  11448. * @return string
  11449. */
  11450. public function getFinalItemForm()
  11451. {
  11452. $finalItem = $this->getFinalItem();
  11453. $title = '';
  11454. if ($finalItem) {
  11455. $title = $finalItem->get_title();
  11456. $buttonText = get_lang('Save');
  11457. $content = $this->getSavedFinalItem();
  11458. } else {
  11459. $buttonText = get_lang('LPCreateDocument');
  11460. $content = $this->getFinalItemTemplate();
  11461. }
  11462. $courseInfo = api_get_course_info();
  11463. $result = $this->generate_lp_folder($courseInfo);
  11464. $relative_path = api_substr($result['dir'], 1, strlen($result['dir']));
  11465. $relative_prefix = '../../';
  11466. $editorConfig = [
  11467. 'ToolbarSet' => 'LearningPathDocuments',
  11468. 'Width' => '100%',
  11469. 'Height' => '500',
  11470. 'FullPage' => true,
  11471. 'CreateDocumentDir' => $relative_prefix,
  11472. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/',
  11473. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/'.$relative_path,
  11474. ];
  11475. $url = api_get_self().'?'.api_get_cidreq().'&'.http_build_query([
  11476. 'type' => 'document',
  11477. 'lp_id' => $this->lp_id,
  11478. ]);
  11479. $form = new FormValidator('final_item', 'POST', $url);
  11480. $form->addText('title', get_lang('Title'));
  11481. $form->addButtonSave($buttonText);
  11482. $form->addHtml(
  11483. Display::return_message(
  11484. 'Variables :</br></br> <b>((certificate))</b> </br> <b>((skill))</b>',
  11485. 'normal',
  11486. false
  11487. )
  11488. );
  11489. $renderer = $form->defaultRenderer();
  11490. $renderer->setElementTemplate('&nbsp;{label}{element}', 'content_lp_certificate');
  11491. $form->addHtmlEditor(
  11492. 'content_lp_certificate',
  11493. null,
  11494. true,
  11495. false,
  11496. $editorConfig,
  11497. true
  11498. );
  11499. $form->addHidden('action', 'add_final_item');
  11500. $form->addHidden('path', Session::read('pathItem'));
  11501. $form->addHidden('previous', $this->get_last());
  11502. $form->setDefaults(
  11503. ['title' => $title, 'content_lp_certificate' => $content]
  11504. );
  11505. if ($form->validate()) {
  11506. $values = $form->exportValues();
  11507. $lastItemId = $this->getLastInFirstLevel();
  11508. if (!$finalItem) {
  11509. $documentId = $this->create_document(
  11510. $this->course_info,
  11511. $values['content_lp_certificate'],
  11512. $values['title']
  11513. );
  11514. $this->add_item(
  11515. 0,
  11516. $lastItemId,
  11517. 'final_item',
  11518. $documentId,
  11519. $values['title'],
  11520. ''
  11521. );
  11522. Display::addFlash(
  11523. Display::return_message(get_lang('Added'))
  11524. );
  11525. } else {
  11526. $this->edit_document($this->course_info);
  11527. }
  11528. }
  11529. return $form->returnForm();
  11530. }
  11531. /**
  11532. * Check if the current lp item is first, both, last or none from lp list.
  11533. *
  11534. * @param int $currentItemId
  11535. *
  11536. * @return string
  11537. */
  11538. public function isFirstOrLastItem($currentItemId)
  11539. {
  11540. $lpItemId = [];
  11541. $typeListNotToVerify = self::getChapterTypes();
  11542. // Using get_toc() function instead $this->items because returns the correct order of the items
  11543. foreach ($this->get_toc() as $item) {
  11544. if (!in_array($item['type'], $typeListNotToVerify)) {
  11545. $lpItemId[] = $item['id'];
  11546. }
  11547. }
  11548. $lastLpItemIndex = count($lpItemId) - 1;
  11549. $position = array_search($currentItemId, $lpItemId);
  11550. switch ($position) {
  11551. case 0:
  11552. if (!$lastLpItemIndex) {
  11553. $answer = 'both';
  11554. break;
  11555. }
  11556. $answer = 'first';
  11557. break;
  11558. case $lastLpItemIndex:
  11559. $answer = 'last';
  11560. break;
  11561. default:
  11562. $answer = 'none';
  11563. }
  11564. return $answer;
  11565. }
  11566. /**
  11567. * Get whether this is a learning path with the accumulated SCORM time or not.
  11568. *
  11569. * @return int
  11570. */
  11571. public function getAccumulateScormTime()
  11572. {
  11573. return $this->accumulateScormTime;
  11574. }
  11575. /**
  11576. * Set whether this is a learning path with the accumulated SCORM time or not.
  11577. *
  11578. * @param int $value (0 = false, 1 = true)
  11579. *
  11580. * @return bool Always returns true
  11581. */
  11582. public function setAccumulateScormTime($value)
  11583. {
  11584. $this->accumulateScormTime = (int) $value;
  11585. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  11586. $lp_id = $this->get_id();
  11587. $sql = "UPDATE $lp_table
  11588. SET accumulate_scorm_time = ".$this->accumulateScormTime."
  11589. WHERE iid = $lp_id";
  11590. Database::query($sql);
  11591. return true;
  11592. }
  11593. /**
  11594. * Returns an HTML-formatted link to a resource, to incorporate directly into
  11595. * the new learning path tool.
  11596. *
  11597. * The function is a big switch on tool type.
  11598. * In each case, we query the corresponding table for information and build the link
  11599. * with that information.
  11600. *
  11601. * @author Yannick Warnier <ywarnier@beeznest.org> - rebranding based on
  11602. * previous work (display_addedresource_link_in_learnpath())
  11603. *
  11604. * @param int $course_id Course code
  11605. * @param int $learningPathId The learning path ID (in lp table)
  11606. * @param int $id_in_path the unique index in the items table
  11607. * @param int $lpViewId
  11608. *
  11609. * @return string
  11610. */
  11611. public static function rl_get_resource_link_for_learnpath(
  11612. $course_id,
  11613. $learningPathId,
  11614. $id_in_path,
  11615. $lpViewId
  11616. ) {
  11617. $session_id = api_get_session_id();
  11618. $course_info = api_get_course_info_by_id($course_id);
  11619. $learningPathId = (int) $learningPathId;
  11620. $id_in_path = (int) $id_in_path;
  11621. $lpViewId = (int) $lpViewId;
  11622. $em = Database::getManager();
  11623. $lpItemRepo = $em->getRepository('ChamiloCourseBundle:CLpItem');
  11624. /** @var CLpItem $rowItem */
  11625. $rowItem = $lpItemRepo->findOneBy([
  11626. 'cId' => $course_id,
  11627. 'lpId' => $learningPathId,
  11628. 'iid' => $id_in_path,
  11629. ]);
  11630. if (!$rowItem) {
  11631. // Try one more time with "id"
  11632. /** @var CLpItem $rowItem */
  11633. $rowItem = $lpItemRepo->findOneBy([
  11634. 'cId' => $course_id,
  11635. 'lpId' => $learningPathId,
  11636. 'id' => $id_in_path,
  11637. ]);
  11638. if (!$rowItem) {
  11639. return -1;
  11640. }
  11641. }
  11642. $course_code = $course_info['code'];
  11643. $type = $rowItem->getItemType();
  11644. $id = empty($rowItem->getPath()) ? '0' : $rowItem->getPath();
  11645. $main_dir_path = api_get_path(WEB_CODE_PATH);
  11646. $main_course_path = api_get_path(WEB_COURSE_PATH).$course_info['directory'].'/';
  11647. $link = '';
  11648. $extraParams = api_get_cidreq(true, true, 'learnpath').'&session_id='.$session_id;
  11649. switch ($type) {
  11650. case 'dir':
  11651. return $main_dir_path.'lp/blank.php';
  11652. case TOOL_CALENDAR_EVENT:
  11653. return $main_dir_path.'calendar/agenda.php?agenda_id='.$id.'&'.$extraParams;
  11654. case TOOL_ANNOUNCEMENT:
  11655. return $main_dir_path.'announcements/announcements.php?ann_id='.$id.'&'.$extraParams;
  11656. case TOOL_LINK:
  11657. $linkInfo = Link::getLinkInfo($id);
  11658. if (isset($linkInfo['url'])) {
  11659. return $linkInfo['url'];
  11660. }
  11661. return '';
  11662. case TOOL_QUIZ:
  11663. if (empty($id)) {
  11664. return '';
  11665. }
  11666. // Get the lp_item_view with the highest view_count.
  11667. $learnpathItemViewResult = $em
  11668. ->getRepository('ChamiloCourseBundle:CLpItemView')
  11669. ->findBy(
  11670. ['cId' => $course_id, 'lpItemId' => $rowItem->getId(), 'lpViewId' => $lpViewId],
  11671. ['viewCount' => 'DESC'],
  11672. 1
  11673. );
  11674. /** @var CLpItemView $learnpathItemViewData */
  11675. $learnpathItemViewData = current($learnpathItemViewResult);
  11676. $learnpathItemViewId = $learnpathItemViewData ? $learnpathItemViewData->getId() : 0;
  11677. return $main_dir_path.'exercise/overview.php?'.$extraParams.'&'
  11678. .http_build_query([
  11679. 'lp_init' => 1,
  11680. 'learnpath_item_view_id' => $learnpathItemViewId,
  11681. 'learnpath_id' => $learningPathId,
  11682. 'learnpath_item_id' => $id_in_path,
  11683. 'exerciseId' => $id,
  11684. ]);
  11685. case TOOL_HOTPOTATOES: //lowercase because of strtolower above
  11686. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  11687. $result = Database::query("SELECT * FROM ".$TBL_DOCUMENT." WHERE c_id = $course_id AND iid=$id");
  11688. $myrow = Database::fetch_array($result);
  11689. $path = $myrow['path'];
  11690. return $main_dir_path.'exercise/showinframes.php?file='.$path.'&cid='.$course_code.'&uid='
  11691. .api_get_user_id().'&learnpath_id='.$learningPathId.'&learnpath_item_id='.$id_in_path
  11692. .'&lp_view_id='.$lpViewId.'&'.$extraParams;
  11693. case TOOL_FORUM:
  11694. return $main_dir_path.'forum/viewforum.php?forum='.$id.'&lp=true&'.$extraParams;
  11695. case TOOL_THREAD:
  11696. // forum post
  11697. $tbl_topics = Database::get_course_table(TABLE_FORUM_THREAD);
  11698. if (empty($id)) {
  11699. return '';
  11700. }
  11701. $sql = "SELECT * FROM $tbl_topics WHERE c_id = $course_id AND thread_id=$id";
  11702. $result = Database::query($sql);
  11703. $myrow = Database::fetch_array($result);
  11704. return $main_dir_path.'forum/viewthread.php?thread='.$id.'&forum='.$myrow['forum_id'].'&lp=true&'
  11705. .$extraParams;
  11706. case TOOL_POST:
  11707. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  11708. $result = Database::query("SELECT * FROM $tbl_post WHERE c_id = $course_id AND post_id=$id");
  11709. $myrow = Database::fetch_array($result);
  11710. return $main_dir_path.'forum/viewthread.php?post='.$id.'&thread='.$myrow['thread_id'].'&forum='
  11711. .$myrow['forum_id'].'&lp=true&'.$extraParams;
  11712. case TOOL_READOUT_TEXT:
  11713. return api_get_path(WEB_CODE_PATH).
  11714. 'lp/readout_text.php?&id='.$id.'&lp_id='.$learningPathId.'&'.$extraParams;
  11715. case TOOL_DOCUMENT:
  11716. $repo = $em->getRepository('ChamiloCourseBundle:CDocument');
  11717. $document = $repo->findOneBy(['cId' => $course_id, 'iid' => $id]);
  11718. if (empty($document)) {
  11719. // Try with normal id
  11720. $document = $repo->findOneBy(['cId' => $course_id, 'id' => $id]);
  11721. if (empty($document)) {
  11722. return '';
  11723. }
  11724. }
  11725. $documentPathInfo = pathinfo($document->getPath());
  11726. $mediaSupportedFiles = ['mp3', 'mp4', 'ogv', 'flv', 'm4v'];
  11727. $extension = isset($documentPathInfo['extension']) ? $documentPathInfo['extension'] : '';
  11728. $showDirectUrl = !in_array($extension, $mediaSupportedFiles);
  11729. $openmethod = 2;
  11730. $officedoc = false;
  11731. Session::write('openmethod', $openmethod);
  11732. Session::write('officedoc', $officedoc);
  11733. if ($showDirectUrl) {
  11734. $file = $main_course_path.'document'.$document->getPath().'?'.$extraParams;
  11735. if (api_get_configuration_value('allow_pdf_viewerjs_in_lp')) {
  11736. if (Link::isPdfLink($file)) {
  11737. $pdfUrl = api_get_path(WEB_LIBRARY_PATH).'javascript/ViewerJS/index.html#'.$file;
  11738. return $pdfUrl;
  11739. }
  11740. }
  11741. return $file;
  11742. }
  11743. return api_get_path(WEB_CODE_PATH).'document/showinframes.php?id='.$id.'&'.$extraParams;
  11744. case TOOL_LP_FINAL_ITEM:
  11745. return api_get_path(WEB_CODE_PATH).'lp/lp_final_item.php?&id='.$id.'&lp_id='.$learningPathId.'&'
  11746. .$extraParams;
  11747. case 'assignments':
  11748. return $main_dir_path.'work/work.php?'.$extraParams;
  11749. case TOOL_DROPBOX:
  11750. return $main_dir_path.'dropbox/index.php?'.$extraParams;
  11751. case 'introduction_text': //DEPRECATED
  11752. return '';
  11753. case TOOL_COURSE_DESCRIPTION:
  11754. return $main_dir_path.'course_description?'.$extraParams;
  11755. case TOOL_GROUP:
  11756. return $main_dir_path.'group/group.php?'.$extraParams;
  11757. case TOOL_USER:
  11758. return $main_dir_path.'user/user.php?'.$extraParams;
  11759. case TOOL_STUDENTPUBLICATION:
  11760. if (!empty($rowItem->getPath())) {
  11761. return $main_dir_path.'work/work_list.php?id='.$rowItem->getPath().'&'.$extraParams;
  11762. }
  11763. return $main_dir_path.'work/work.php?'.api_get_cidreq().'&id='.$rowItem->getPath().'&'.$extraParams;
  11764. }
  11765. return $link;
  11766. }
  11767. /**
  11768. * Gets the name of a resource (generally used in learnpath when no name is provided).
  11769. *
  11770. * @author Yannick Warnier <ywarnier@beeznest.org>
  11771. *
  11772. * @param string $course_code Course code
  11773. * @param int $learningPathId
  11774. * @param int $id_in_path The resource ID
  11775. *
  11776. * @return string
  11777. */
  11778. public static function rl_get_resource_name($course_code, $learningPathId, $id_in_path)
  11779. {
  11780. $_course = api_get_course_info($course_code);
  11781. if (empty($_course)) {
  11782. return '';
  11783. }
  11784. $course_id = $_course['real_id'];
  11785. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  11786. $learningPathId = (int) $learningPathId;
  11787. $id_in_path = (int) $id_in_path;
  11788. $sql = "SELECT item_type, title, ref
  11789. FROM $tbl_lp_item
  11790. WHERE c_id = $course_id AND lp_id = $learningPathId AND iid = $id_in_path";
  11791. $res_item = Database::query($sql);
  11792. if (Database::num_rows($res_item) < 1) {
  11793. return '';
  11794. }
  11795. $row_item = Database::fetch_array($res_item);
  11796. $type = strtolower($row_item['item_type']);
  11797. $id = $row_item['ref'];
  11798. $output = '';
  11799. switch ($type) {
  11800. case TOOL_CALENDAR_EVENT:
  11801. $TABLEAGENDA = Database::get_course_table(TABLE_AGENDA);
  11802. $result = Database::query("SELECT * FROM $TABLEAGENDA WHERE c_id = $course_id AND id=$id");
  11803. $myrow = Database::fetch_array($result);
  11804. $output = $myrow['title'];
  11805. break;
  11806. case TOOL_ANNOUNCEMENT:
  11807. $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
  11808. $result = Database::query("SELECT * FROM $tbl_announcement WHERE c_id = $course_id AND id=$id");
  11809. $myrow = Database::fetch_array($result);
  11810. $output = $myrow['title'];
  11811. break;
  11812. case TOOL_LINK:
  11813. // Doesn't take $target into account.
  11814. $TABLETOOLLINK = Database::get_course_table(TABLE_LINK);
  11815. $result = Database::query("SELECT * FROM $TABLETOOLLINK WHERE c_id = $course_id AND id=$id");
  11816. $myrow = Database::fetch_array($result);
  11817. $output = $myrow['title'];
  11818. break;
  11819. case TOOL_QUIZ:
  11820. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  11821. $result = Database::query("SELECT * FROM $TBL_EXERCICES WHERE c_id = $course_id AND id = $id");
  11822. $myrow = Database::fetch_array($result);
  11823. $output = $myrow['title'];
  11824. break;
  11825. case TOOL_FORUM:
  11826. $TBL_FORUMS = Database::get_course_table(TABLE_FORUM);
  11827. $result = Database::query("SELECT * FROM $TBL_FORUMS WHERE c_id = $course_id AND forum_id = $id");
  11828. $myrow = Database::fetch_array($result);
  11829. $output = $myrow['forum_name'];
  11830. break;
  11831. case TOOL_THREAD:
  11832. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  11833. // Grabbing the title of the post.
  11834. $sql_title = "SELECT * FROM $tbl_post WHERE c_id = $course_id AND post_id=".$id;
  11835. $result_title = Database::query($sql_title);
  11836. $myrow_title = Database::fetch_array($result_title);
  11837. $output = $myrow_title['post_title'];
  11838. break;
  11839. case TOOL_POST:
  11840. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  11841. $sql = "SELECT * FROM $tbl_post p WHERE c_id = $course_id AND p.post_id = $id";
  11842. $result = Database::query($sql);
  11843. $post = Database::fetch_array($result);
  11844. $output = $post['post_title'];
  11845. break;
  11846. case 'dir':
  11847. case TOOL_DOCUMENT:
  11848. $title = $row_item['title'];
  11849. $output = '-';
  11850. if (!empty($title)) {
  11851. $output = $title;
  11852. }
  11853. break;
  11854. case 'hotpotatoes':
  11855. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  11856. $result = Database::query("SELECT * FROM $tbl_doc WHERE c_id = $course_id AND iid = $id");
  11857. $myrow = Database::fetch_array($result);
  11858. $pathname = explode('/', $myrow['path']); // Making a correct name for the link.
  11859. $last = count($pathname) - 1; // Making a correct name for the link.
  11860. $filename = $pathname[$last]; // Making a correct name for the link.
  11861. $myrow['path'] = rawurlencode($myrow['path']);
  11862. $output = $filename;
  11863. break;
  11864. }
  11865. return stripslashes($output);
  11866. }
  11867. /**
  11868. * Get the parent names for the current item.
  11869. *
  11870. * @param int $newItemId Optional. The item ID
  11871. *
  11872. * @return array
  11873. */
  11874. public function getCurrentItemParentNames($newItemId = 0)
  11875. {
  11876. $newItemId = $newItemId ?: $this->get_current_item_id();
  11877. $return = [];
  11878. $item = $this->getItem($newItemId);
  11879. $parent = $this->getItem($item->get_parent());
  11880. while ($parent) {
  11881. $return[] = $parent->get_title();
  11882. $parent = $this->getItem($parent->get_parent());
  11883. }
  11884. return array_reverse($return);
  11885. }
  11886. /**
  11887. * Reads and process "lp_subscription_settings" setting.
  11888. *
  11889. * @return array
  11890. */
  11891. public static function getSubscriptionSettings()
  11892. {
  11893. $subscriptionSettings = api_get_configuration_value('lp_subscription_settings');
  11894. if (empty($subscriptionSettings)) {
  11895. // By default allow both settings
  11896. $subscriptionSettings = [
  11897. 'allow_add_users_to_lp' => true,
  11898. 'allow_add_users_to_lp_category' => true,
  11899. ];
  11900. } else {
  11901. $subscriptionSettings = $subscriptionSettings['options'];
  11902. }
  11903. return $subscriptionSettings;
  11904. }
  11905. /**
  11906. * Exports a LP to a courseBuilder zip file. It adds the documents related to the LP.
  11907. */
  11908. public function exportToCourseBuildFormat()
  11909. {
  11910. if (!api_is_allowed_to_edit()) {
  11911. return false;
  11912. }
  11913. $courseBuilder = new CourseBuilder();
  11914. $itemList = [];
  11915. /** @var learnpathItem $item */
  11916. foreach ($this->items as $item) {
  11917. $itemList[$item->get_type()][] = $item->get_path();
  11918. }
  11919. if (empty($itemList)) {
  11920. return false;
  11921. }
  11922. if (isset($itemList['document'])) {
  11923. // Get parents
  11924. foreach ($itemList['document'] as $documentId) {
  11925. $documentInfo = DocumentManager::get_document_data_by_id($documentId, api_get_course_id(), true);
  11926. if (!empty($documentInfo['parents'])) {
  11927. foreach ($documentInfo['parents'] as $parentInfo) {
  11928. if (in_array($parentInfo['iid'], $itemList['document'])) {
  11929. continue;
  11930. }
  11931. $itemList['document'][] = $parentInfo['iid'];
  11932. }
  11933. }
  11934. }
  11935. $courseInfo = api_get_course_info();
  11936. foreach ($itemList['document'] as $documentId) {
  11937. $documentInfo = DocumentManager::get_document_data_by_id($documentId, api_get_course_id());
  11938. $items = DocumentManager::get_resources_from_source_html(
  11939. $documentInfo['absolute_path'],
  11940. true,
  11941. TOOL_DOCUMENT
  11942. );
  11943. if (!empty($items)) {
  11944. foreach ($items as $item) {
  11945. // Get information about source url
  11946. $url = $item[0]; // url
  11947. $scope = $item[1]; // scope (local, remote)
  11948. $type = $item[2]; // type (rel, abs, url)
  11949. $origParseUrl = parse_url($url);
  11950. $realOrigPath = isset($origParseUrl['path']) ? $origParseUrl['path'] : null;
  11951. if ($scope == 'local') {
  11952. if ($type == 'abs' || $type == 'rel') {
  11953. $documentFile = strstr($realOrigPath, 'document');
  11954. if (strpos($realOrigPath, $documentFile) !== false) {
  11955. $documentFile = str_replace('document', '', $documentFile);
  11956. $itemDocumentId = DocumentManager::get_document_id($courseInfo, $documentFile);
  11957. // Document found! Add it to the list
  11958. if ($itemDocumentId) {
  11959. $itemList['document'][] = $itemDocumentId;
  11960. }
  11961. }
  11962. }
  11963. }
  11964. }
  11965. }
  11966. }
  11967. $courseBuilder->build_documents(
  11968. api_get_session_id(),
  11969. $this->get_course_int_id(),
  11970. true,
  11971. $itemList['document']
  11972. );
  11973. }
  11974. if (isset($itemList['quiz'])) {
  11975. $courseBuilder->build_quizzes(
  11976. api_get_session_id(),
  11977. $this->get_course_int_id(),
  11978. true,
  11979. $itemList['quiz']
  11980. );
  11981. }
  11982. require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
  11983. /*if (!empty($itemList['thread'])) {
  11984. $postList = [];
  11985. foreach ($itemList['thread'] as $postId) {
  11986. $post = get_post_information($postId);
  11987. if ($post) {
  11988. if (!isset($itemList['forum'])) {
  11989. $itemList['forum'] = [];
  11990. }
  11991. $itemList['forum'][] = $post['forum_id'];
  11992. $postList[] = $postId;
  11993. }
  11994. }
  11995. if (!empty($postList)) {
  11996. $courseBuilder->build_forum_posts(
  11997. $this->get_course_int_id(),
  11998. null,
  11999. null,
  12000. $postList
  12001. );
  12002. }
  12003. }*/
  12004. if (!empty($itemList['thread'])) {
  12005. $threadList = [];
  12006. $em = Database::getManager();
  12007. $repo = $em->getRepository('ChamiloCourseBundle:CForumThread');
  12008. foreach ($itemList['thread'] as $threadId) {
  12009. /** @var \Chamilo\CourseBundle\Entity\CForumThread $thread */
  12010. $thread = $repo->find($threadId);
  12011. if ($thread) {
  12012. $itemList['forum'][] = $thread->getForumId();
  12013. $threadList[] = $thread->getIid();
  12014. }
  12015. }
  12016. if (!empty($threadList)) {
  12017. $courseBuilder->build_forum_topics(
  12018. api_get_session_id(),
  12019. $this->get_course_int_id(),
  12020. null,
  12021. $threadList
  12022. );
  12023. }
  12024. }
  12025. $forumCategoryList = [];
  12026. if (isset($itemList['forum'])) {
  12027. foreach ($itemList['forum'] as $forumId) {
  12028. $forumInfo = get_forums($forumId);
  12029. $forumCategoryList[] = $forumInfo['forum_category'];
  12030. }
  12031. }
  12032. if (!empty($forumCategoryList)) {
  12033. $courseBuilder->build_forum_category(
  12034. api_get_session_id(),
  12035. $this->get_course_int_id(),
  12036. true,
  12037. $forumCategoryList
  12038. );
  12039. }
  12040. if (!empty($itemList['forum'])) {
  12041. $courseBuilder->build_forums(
  12042. api_get_session_id(),
  12043. $this->get_course_int_id(),
  12044. true,
  12045. $itemList['forum']
  12046. );
  12047. }
  12048. if (isset($itemList['link'])) {
  12049. $courseBuilder->build_links(
  12050. api_get_session_id(),
  12051. $this->get_course_int_id(),
  12052. true,
  12053. $itemList['link']
  12054. );
  12055. }
  12056. if (!empty($itemList['student_publication'])) {
  12057. $courseBuilder->build_works(
  12058. api_get_session_id(),
  12059. $this->get_course_int_id(),
  12060. true,
  12061. $itemList['student_publication']
  12062. );
  12063. }
  12064. $courseBuilder->build_learnpaths(
  12065. api_get_session_id(),
  12066. $this->get_course_int_id(),
  12067. true,
  12068. [$this->get_id()],
  12069. false
  12070. );
  12071. $courseBuilder->restoreDocumentsFromList();
  12072. $zipFile = CourseArchiver::createBackup($courseBuilder->course);
  12073. $zipPath = CourseArchiver::getBackupDir().$zipFile;
  12074. $result = DocumentManager::file_send_for_download(
  12075. $zipPath,
  12076. true,
  12077. $this->get_name().'.zip'
  12078. );
  12079. if ($result) {
  12080. api_not_allowed();
  12081. }
  12082. return true;
  12083. }
  12084. /**
  12085. * Get whether this is a learning path with the accumulated work time or not.
  12086. *
  12087. * @return int
  12088. */
  12089. public function getAccumulateWorkTime()
  12090. {
  12091. return (int) $this->accumulateWorkTime;
  12092. }
  12093. /**
  12094. * Get whether this is a learning path with the accumulated work time or not.
  12095. *
  12096. * @return int
  12097. */
  12098. public function getAccumulateWorkTimeTotalCourse()
  12099. {
  12100. $table = Database::get_course_table(TABLE_LP_MAIN);
  12101. $sql = "SELECT SUM(accumulate_work_time) AS total
  12102. FROM $table
  12103. WHERE c_id = ".$this->course_int_id;
  12104. $result = Database::query($sql);
  12105. $row = Database::fetch_array($result);
  12106. return (int) $row['total'];
  12107. }
  12108. /**
  12109. * Set whether this is a learning path with the accumulated work time or not.
  12110. *
  12111. * @param int $value (0 = false, 1 = true)
  12112. *
  12113. * @return bool
  12114. */
  12115. public function setAccumulateWorkTime($value)
  12116. {
  12117. if (!api_get_configuration_value('lp_minimum_time')) {
  12118. return false;
  12119. }
  12120. $this->accumulateWorkTime = (int) $value;
  12121. $table = Database::get_course_table(TABLE_LP_MAIN);
  12122. $lp_id = $this->get_id();
  12123. $sql = "UPDATE $table SET accumulate_work_time = ".$this->accumulateWorkTime."
  12124. WHERE c_id = ".$this->course_int_id." AND id = $lp_id";
  12125. Database::query($sql);
  12126. return true;
  12127. }
  12128. /**
  12129. * @param int $lpId
  12130. * @param int $courseId
  12131. *
  12132. * @return mixed
  12133. */
  12134. public static function getAccumulateWorkTimePrerequisite($lpId, $courseId)
  12135. {
  12136. $lpId = (int) $lpId;
  12137. $courseId = (int) $courseId;
  12138. $table = Database::get_course_table(TABLE_LP_MAIN);
  12139. $sql = "SELECT accumulate_work_time
  12140. FROM $table
  12141. WHERE c_id = $courseId AND id = $lpId";
  12142. $result = Database::query($sql);
  12143. $row = Database::fetch_array($result);
  12144. return $row['accumulate_work_time'];
  12145. }
  12146. /**
  12147. * @param int $courseId
  12148. *
  12149. * @return int
  12150. */
  12151. public static function getAccumulateWorkTimeTotal($courseId)
  12152. {
  12153. $table = Database::get_course_table(TABLE_LP_MAIN);
  12154. $courseId = (int) $courseId;
  12155. $sql = "SELECT SUM(accumulate_work_time) AS total
  12156. FROM $table
  12157. WHERE c_id = $courseId";
  12158. $result = Database::query($sql);
  12159. $row = Database::fetch_array($result);
  12160. return (int) $row['total'];
  12161. }
  12162. /**
  12163. * In order to use the lp icon option you need to create the "lp_icon" LP extra field
  12164. * and put the images in.
  12165. *
  12166. * @return array
  12167. */
  12168. public static function getIconSelect()
  12169. {
  12170. $theme = api_get_visual_theme();
  12171. $path = api_get_path(SYS_PUBLIC_PATH).'css/themes/'.$theme.'/lp_icons/';
  12172. $icons = ['' => get_lang('SelectAnOption')];
  12173. if (is_dir($path)) {
  12174. $finder = new Finder();
  12175. $finder->files()->in($path);
  12176. $allowedExtensions = ['jpeg', 'jpg', 'png'];
  12177. /** @var SplFileInfo $file */
  12178. foreach ($finder as $file) {
  12179. if (in_array(strtolower($file->getExtension()), $allowedExtensions)) {
  12180. $icons[$file->getFilename()] = $file->getFilename();
  12181. }
  12182. }
  12183. }
  12184. return $icons;
  12185. }
  12186. /**
  12187. * @param int $lpId
  12188. *
  12189. * @return string
  12190. */
  12191. public static function getSelectedIcon($lpId)
  12192. {
  12193. $extraFieldValue = new ExtraFieldValue('lp');
  12194. $lpIcon = $extraFieldValue->get_values_by_handler_and_field_variable($lpId, 'lp_icon');
  12195. $icon = '';
  12196. if (!empty($lpIcon) && isset($lpIcon['value'])) {
  12197. $icon = $lpIcon['value'];
  12198. }
  12199. return $icon;
  12200. }
  12201. /**
  12202. * @param int $lpId
  12203. *
  12204. * @return string
  12205. */
  12206. public static function getSelectedIconHtml($lpId)
  12207. {
  12208. $icon = self::getSelectedIcon($lpId);
  12209. if (empty($icon)) {
  12210. return '';
  12211. }
  12212. $theme = api_get_visual_theme();
  12213. $path = api_get_path(WEB_PUBLIC_PATH).'css/themes/'.$theme.'/lp_icons/'.$icon;
  12214. return Display::img($path);
  12215. }
  12216. /**
  12217. * @param string $value
  12218. *
  12219. * @return string
  12220. */
  12221. public function cleanItemTitle($value)
  12222. {
  12223. $value = Security::remove_XSS(strip_tags($value));
  12224. return $value;
  12225. }
  12226. /**
  12227. * @param FormValidator $form
  12228. */
  12229. public function setItemTitle(FormValidator $form)
  12230. {
  12231. if (api_get_configuration_value('save_titles_as_html')) {
  12232. $form->addHtmlEditor(
  12233. 'title',
  12234. get_lang('Title'),
  12235. true,
  12236. false,
  12237. ['ToolbarSet' => 'TitleAsHtml']
  12238. );
  12239. } else {
  12240. $form->addText('title', get_lang('Title'), true, ['id' => 'idTitle', 'class' => 'learnpath_item_form']);
  12241. $form->applyFilter('title', 'trim');
  12242. $form->applyFilter('title', 'html_filter');
  12243. }
  12244. }
  12245. /**
  12246. * @return array
  12247. */
  12248. public function getItemsForForm($addParentCondition = false)
  12249. {
  12250. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  12251. $course_id = api_get_course_int_id();
  12252. $sql = "SELECT * FROM $tbl_lp_item
  12253. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  12254. if ($addParentCondition) {
  12255. $sql .= ' AND parent_item_id = 0 ';
  12256. }
  12257. $sql .= ' ORDER BY display_order ASC';
  12258. $result = Database::query($sql);
  12259. $arrLP = [];
  12260. while ($row = Database::fetch_array($result)) {
  12261. $arrLP[] = [
  12262. 'iid' => $row['iid'],
  12263. 'id' => $row['iid'],
  12264. 'item_type' => $row['item_type'],
  12265. 'title' => $this->cleanItemTitle($row['title']),
  12266. 'title_raw' => $row['title'],
  12267. 'path' => $row['path'],
  12268. 'description' => Security::remove_XSS($row['description']),
  12269. 'parent_item_id' => $row['parent_item_id'],
  12270. 'previous_item_id' => $row['previous_item_id'],
  12271. 'next_item_id' => $row['next_item_id'],
  12272. 'display_order' => $row['display_order'],
  12273. 'max_score' => $row['max_score'],
  12274. 'min_score' => $row['min_score'],
  12275. 'mastery_score' => $row['mastery_score'],
  12276. 'prerequisite' => $row['prerequisite'],
  12277. 'max_time_allowed' => $row['max_time_allowed'],
  12278. 'prerequisite_min_score' => $row['prerequisite_min_score'],
  12279. 'prerequisite_max_score' => $row['prerequisite_max_score'],
  12280. ];
  12281. }
  12282. return $arrLP;
  12283. }
  12284. /**
  12285. * Get the depth level of LP item.
  12286. *
  12287. * @param array $items
  12288. * @param int $currentItemId
  12289. *
  12290. * @return int
  12291. */
  12292. private static function get_level_for_item($items, $currentItemId)
  12293. {
  12294. $parentItemId = 0;
  12295. if (isset($items[$currentItemId])) {
  12296. $parentItemId = $items[$currentItemId]->parent;
  12297. }
  12298. if ($parentItemId == 0) {
  12299. return 0;
  12300. } else {
  12301. return self::get_level_for_item($items, $parentItemId) + 1;
  12302. }
  12303. }
  12304. /**
  12305. * Generate the link for a learnpath category as course tool.
  12306. *
  12307. * @param int $categoryId
  12308. *
  12309. * @return string
  12310. */
  12311. private static function getCategoryLinkForTool($categoryId)
  12312. {
  12313. $categoryId = (int) $categoryId;
  12314. $link = 'lp/lp_controller.php?'.api_get_cidreq().'&'
  12315. .http_build_query(
  12316. [
  12317. 'action' => 'view_category',
  12318. 'id' => $categoryId,
  12319. ]
  12320. );
  12321. return $link;
  12322. }
  12323. /**
  12324. * Return the scorm item type object with spaces replaced with _
  12325. * The return result is use to build a css classname like scorm_type_$return.
  12326. *
  12327. * @param $in_type
  12328. *
  12329. * @return mixed
  12330. */
  12331. private static function format_scorm_type_item($in_type)
  12332. {
  12333. return str_replace(' ', '_', $in_type);
  12334. }
  12335. /**
  12336. * Check and obtain the lp final item if exist.
  12337. *
  12338. * @return learnpathItem
  12339. */
  12340. private function getFinalItem()
  12341. {
  12342. if (empty($this->items)) {
  12343. return null;
  12344. }
  12345. foreach ($this->items as $item) {
  12346. if ($item->type !== 'final_item') {
  12347. continue;
  12348. }
  12349. return $item;
  12350. }
  12351. }
  12352. /**
  12353. * Get the LP Final Item Template.
  12354. *
  12355. * @return string
  12356. */
  12357. private function getFinalItemTemplate()
  12358. {
  12359. return file_get_contents(api_get_path(SYS_CODE_PATH).'lp/final_item_template/template.html');
  12360. }
  12361. /**
  12362. * Get the LP Final Item Url.
  12363. *
  12364. * @return string
  12365. */
  12366. private function getSavedFinalItem()
  12367. {
  12368. $finalItem = $this->getFinalItem();
  12369. $doc = DocumentManager::get_document_data_by_id(
  12370. $finalItem->path,
  12371. $this->cc
  12372. );
  12373. if ($doc && file_exists($doc['absolute_path'])) {
  12374. return file_get_contents($doc['absolute_path']);
  12375. }
  12376. return '';
  12377. }
  12378. }