learnpath.class.php 533 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CoreBundle\Entity\Repository\CourseRepository;
  4. use Chamilo\CoreBundle\Entity\Repository\ItemPropertyRepository;
  5. use Chamilo\CourseBundle\Component\CourseCopy\CourseArchiver;
  6. use Chamilo\CourseBundle\Component\CourseCopy\CourseBuilder;
  7. use Chamilo\CourseBundle\Component\CourseCopy\CourseRestorer;
  8. use Chamilo\CourseBundle\Entity\CDocument;
  9. use Chamilo\CourseBundle\Entity\CItemProperty;
  10. use Chamilo\CourseBundle\Entity\CLp;
  11. use Chamilo\CourseBundle\Entity\CLpCategory;
  12. use Chamilo\CourseBundle\Entity\CLpItem;
  13. use Chamilo\CourseBundle\Entity\CLpItemView;
  14. use Chamilo\CourseBundle\Entity\CTool;
  15. use Chamilo\UserBundle\Entity\User;
  16. use ChamiloSession as Session;
  17. use Gedmo\Sortable\Entity\Repository\SortableRepository;
  18. use Symfony\Component\Filesystem\Filesystem;
  19. use Symfony\Component\Finder\Finder;
  20. /**
  21. * Class learnpath
  22. * This class defines the parent attributes and methods for Chamilo learnpaths
  23. * and SCORM learnpaths. It is used by the scorm class.
  24. *
  25. * @todo decouple class
  26. *
  27. * @package chamilo.learnpath
  28. *
  29. * @author Yannick Warnier <ywarnier@beeznest.org>
  30. * @author Julio Montoya <gugli100@gmail.com> Several improvements and fixes
  31. */
  32. class learnpath
  33. {
  34. const MAX_LP_ITEM_TITLE_LENGTH = 32;
  35. public $attempt = 0; // The number for the current ID view.
  36. public $cc; // Course (code) this learnpath is located in. @todo change name for something more comprensible ...
  37. public $current; // Id of the current item the user is viewing.
  38. public $current_score; // The score of the current item.
  39. public $current_time_start; // The time the user loaded this resource (this does not mean he can see it yet).
  40. public $current_time_stop; // The time the user closed this resource.
  41. public $default_status = 'not attempted';
  42. public $encoding = 'UTF-8';
  43. public $error = '';
  44. public $force_commit = false; // For SCORM only- if true will send a scorm LMSCommit() request on each LMSSetValue()
  45. public $index; // The index of the active learnpath_item in $ordered_items array.
  46. public $items = [];
  47. public $last; // item_id of last item viewed in the learning path.
  48. public $last_item_seen = 0; // In case we have already come in this lp, reuse the last item seen if authorized.
  49. public $license; // Which license this course has been given - not used yet on 20060522.
  50. public $lp_id; // DB iid for this learnpath.
  51. public $lp_view_id; // DB ID for lp_view
  52. public $maker; // Which maker has conceived the content (ENI, Articulate, ...).
  53. public $message = '';
  54. public $mode = 'embedded'; // Holds the video display mode (fullscreen or embedded).
  55. public $name; // Learnpath name (they generally have one).
  56. public $ordered_items = []; // List of the learnpath items in the order they are to be read.
  57. public $path = ''; // Path inside the scorm directory (if scorm).
  58. public $theme; // The current theme of the learning path.
  59. public $preview_image; // The current image of the learning path.
  60. public $accumulateScormTime; // Flag to decide whether to accumulate SCORM time or not
  61. public $accumulateWorkTime; // The min time of learnpath
  62. // Tells if all the items of the learnpath can be tried again. Defaults to "no" (=1).
  63. public $prevent_reinit = 1;
  64. // Describes the mode of progress bar display.
  65. public $seriousgame_mode = 0;
  66. public $progress_bar_mode = '%';
  67. // Percentage progress as saved in the db.
  68. public $progress_db = 0;
  69. public $proximity; // Wether the content is distant or local or unknown.
  70. public $refs_list = []; //list of items by ref => db_id. Used only for prerequisites match.
  71. // !!!This array (refs_list) is built differently depending on the nature of the LP.
  72. // If SCORM, uses ref, if Chamilo, uses id to keep a unique value.
  73. public $type; //type of learnpath. Could be 'chamilo', 'scorm', 'scorm2004', 'aicc', ...
  74. // TODO: Check if this type variable is useful here (instead of just in the controller script).
  75. public $user_id; //ID of the user that is viewing/using the course
  76. public $update_queue = [];
  77. public $scorm_debug = 0;
  78. public $arrMenu = []; // Array for the menu items.
  79. public $debug = 0; // Logging level.
  80. public $lp_session_id = 0;
  81. public $lp_view_session_id = 0; // The specific view might be bound to a session.
  82. public $prerequisite = 0;
  83. public $use_max_score = 1; // 1 or 0
  84. public $subscribeUsers = 0; // Subscribe users or not
  85. public $created_on = '';
  86. public $modified_on = '';
  87. public $publicated_on = '';
  88. public $expired_on = '';
  89. public $ref = null;
  90. public $course_int_id;
  91. public $course_info = [];
  92. public $categoryId;
  93. /**
  94. * Constructor.
  95. * Needs a database handler, a course code and a learnpath id from the database.
  96. * Also builds the list of items into $this->items.
  97. *
  98. * @param string $course Course code
  99. * @param int $lp_id c_lp.iid
  100. * @param int $user_id
  101. */
  102. public function __construct($course, $lp_id, $user_id)
  103. {
  104. $debug = $this->debug;
  105. $this->encoding = api_get_system_encoding();
  106. if ($debug) {
  107. error_log('In learnpath::__construct('.$course.','.$lp_id.','.$user_id.')');
  108. }
  109. if (empty($course)) {
  110. $course = api_get_course_id();
  111. }
  112. $course_info = api_get_course_info($course);
  113. if (!empty($course_info)) {
  114. $this->cc = $course_info['code'];
  115. $this->course_info = $course_info;
  116. $course_id = $course_info['real_id'];
  117. } else {
  118. $this->error = 'Course code does not exist in database.';
  119. }
  120. $lp_id = (int) $lp_id;
  121. $course_id = (int) $course_id;
  122. $this->set_course_int_id($course_id);
  123. // Check learnpath ID.
  124. if (empty($lp_id) || empty($course_id)) {
  125. $this->error = "Parameter is empty: LpId:'$lp_id', courseId: '$lp_id'";
  126. } else {
  127. // TODO: Make it flexible to use any course_code (still using env course code here).
  128. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  129. $sql = "SELECT * FROM $lp_table
  130. WHERE iid = $lp_id";
  131. if ($debug) {
  132. error_log('learnpath::__construct() '.__LINE__.' - Querying lp: '.$sql, 0);
  133. }
  134. $res = Database::query($sql);
  135. if (Database::num_rows($res) > 0) {
  136. $this->lp_id = $lp_id;
  137. $row = Database::fetch_array($res);
  138. $this->type = $row['lp_type'];
  139. $this->name = stripslashes($row['name']);
  140. $this->proximity = $row['content_local'];
  141. $this->theme = $row['theme'];
  142. $this->maker = $row['content_maker'];
  143. $this->prevent_reinit = $row['prevent_reinit'];
  144. $this->seriousgame_mode = $row['seriousgame_mode'];
  145. $this->license = $row['content_license'];
  146. $this->scorm_debug = $row['debug'];
  147. $this->js_lib = $row['js_lib'];
  148. $this->path = $row['path'];
  149. $this->preview_image = $row['preview_image'];
  150. $this->author = $row['author'];
  151. $this->hide_toc_frame = $row['hide_toc_frame'];
  152. $this->lp_session_id = $row['session_id'];
  153. $this->use_max_score = $row['use_max_score'];
  154. $this->subscribeUsers = $row['subscribe_users'];
  155. $this->created_on = $row['created_on'];
  156. $this->modified_on = $row['modified_on'];
  157. $this->ref = $row['ref'];
  158. $this->categoryId = $row['category_id'];
  159. $this->accumulateScormTime = isset($row['accumulate_scorm_time']) ? $row['accumulate_scorm_time'] : 'true';
  160. $this->accumulateWorkTime = isset($row['accumulate_work_time']) ? $row['accumulate_work_time'] : 0;
  161. if (!empty($row['publicated_on'])) {
  162. $this->publicated_on = $row['publicated_on'];
  163. }
  164. if (!empty($row['expired_on'])) {
  165. $this->expired_on = $row['expired_on'];
  166. }
  167. if ($this->type == 2) {
  168. if ($row['force_commit'] == 1) {
  169. $this->force_commit = true;
  170. }
  171. }
  172. $this->mode = $row['default_view_mod'];
  173. // Check user ID.
  174. if (empty($user_id)) {
  175. $this->error = 'User ID is empty';
  176. } else {
  177. $userInfo = api_get_user_info($user_id);
  178. if (!empty($userInfo)) {
  179. $this->user_id = $userInfo['user_id'];
  180. } else {
  181. $this->error = 'User ID does not exist in database #'.$user_id;
  182. }
  183. }
  184. // End of variables checking.
  185. $session_id = api_get_session_id();
  186. // Get the session condition for learning paths of the base + session.
  187. $session = api_get_session_condition($session_id);
  188. // Now get the latest attempt from this user on this LP, if available, otherwise create a new one.
  189. $lp_table = Database::get_course_table(TABLE_LP_VIEW);
  190. // Selecting by view_count descending allows to get the highest view_count first.
  191. $sql = "SELECT * FROM $lp_table
  192. WHERE
  193. c_id = $course_id AND
  194. lp_id = $lp_id AND
  195. user_id = $user_id
  196. $session
  197. ORDER BY view_count DESC";
  198. $res = Database::query($sql);
  199. if ($debug) {
  200. error_log('learnpath::__construct() '.__LINE__.' - querying lp_view: '.$sql, 0);
  201. }
  202. if (Database::num_rows($res) > 0) {
  203. if ($debug) {
  204. error_log('learnpath::__construct() '.__LINE__.' - Found previous view');
  205. }
  206. $row = Database::fetch_array($res);
  207. $this->attempt = $row['view_count'];
  208. $this->lp_view_id = $row['id'];
  209. $this->last_item_seen = $row['last_item'];
  210. $this->progress_db = $row['progress'];
  211. $this->lp_view_session_id = $row['session_id'];
  212. } elseif (!api_is_invitee()) {
  213. if ($debug) {
  214. error_log('learnpath::__construct() '.__LINE__.' - NOT Found previous view');
  215. }
  216. $this->attempt = 1;
  217. $params = [
  218. 'c_id' => $course_id,
  219. 'lp_id' => $lp_id,
  220. 'user_id' => $user_id,
  221. 'view_count' => 1,
  222. 'session_id' => $session_id,
  223. 'last_item' => 0,
  224. ];
  225. $this->last_item_seen = 0;
  226. $this->lp_view_session_id = $session_id;
  227. $this->lp_view_id = Database::insert($lp_table, $params);
  228. if (!empty($this->lp_view_id)) {
  229. $sql = "UPDATE $lp_table SET id = iid
  230. WHERE iid = ".$this->lp_view_id;
  231. Database::query($sql);
  232. }
  233. }
  234. // Initialise items.
  235. $lp_item_table = Database::get_course_table(TABLE_LP_ITEM);
  236. $sql = "SELECT * FROM $lp_item_table
  237. WHERE c_id = $course_id AND lp_id = '".$this->lp_id."'
  238. ORDER BY parent_item_id, display_order";
  239. $res = Database::query($sql);
  240. if ($debug) {
  241. error_log('learnpath::__construct() '.__LINE__.' - query lp items: '.$sql);
  242. error_log('-- Start while--');
  243. }
  244. $lp_item_id_list = [];
  245. while ($row = Database::fetch_array($res)) {
  246. $lp_item_id_list[] = $row['iid'];
  247. switch ($this->type) {
  248. case 3: //aicc
  249. $oItem = new aiccItem('db', $row['iid'], $course_id);
  250. if (is_object($oItem)) {
  251. $my_item_id = $oItem->get_id();
  252. $oItem->set_lp_view($this->lp_view_id, $course_id);
  253. $oItem->set_prevent_reinit($this->prevent_reinit);
  254. // Don't use reference here as the next loop will make the pointed object change.
  255. $this->items[$my_item_id] = $oItem;
  256. $this->refs_list[$oItem->ref] = $my_item_id;
  257. if ($debug) {
  258. error_log(
  259. 'learnpath::__construct() - '.
  260. 'aicc object with id '.$my_item_id.
  261. ' set in items[]',
  262. 0
  263. );
  264. }
  265. }
  266. break;
  267. case 2:
  268. $oItem = new scormItem('db', $row['iid'], $course_id);
  269. if (is_object($oItem)) {
  270. $my_item_id = $oItem->get_id();
  271. $oItem->set_lp_view($this->lp_view_id, $course_id);
  272. $oItem->set_prevent_reinit($this->prevent_reinit);
  273. // Don't use reference here as the next loop will make the pointed object change.
  274. $this->items[$my_item_id] = $oItem;
  275. $this->refs_list[$oItem->ref] = $my_item_id;
  276. if ($debug) {
  277. error_log('object with id '.$my_item_id.' set in items[]');
  278. }
  279. }
  280. break;
  281. case 1:
  282. default:
  283. if ($debug) {
  284. error_log('learnpath::__construct() '.__LINE__.' - calling learnpathItem');
  285. }
  286. $oItem = new learnpathItem($row['iid'], $user_id, $course_id, $row);
  287. if ($debug) {
  288. error_log('learnpath::__construct() '.__LINE__.' - end calling learnpathItem');
  289. }
  290. if (is_object($oItem)) {
  291. $my_item_id = $oItem->get_id();
  292. // Moved down to when we are sure the item_view exists.
  293. //$oItem->set_lp_view($this->lp_view_id);
  294. $oItem->set_prevent_reinit($this->prevent_reinit);
  295. // Don't use reference here as the next loop will make the pointed object change.
  296. $this->items[$my_item_id] = $oItem;
  297. $this->refs_list[$my_item_id] = $my_item_id;
  298. if ($debug) {
  299. error_log(
  300. 'learnpath::__construct() '.__LINE__.
  301. ' - object with id '.$my_item_id.' set in items[]'
  302. );
  303. }
  304. }
  305. break;
  306. }
  307. // Setting the object level with variable $this->items[$i][parent]
  308. foreach ($this->items as $itemLPObject) {
  309. $level = self::get_level_for_item(
  310. $this->items,
  311. $itemLPObject->db_id
  312. );
  313. $itemLPObject->level = $level;
  314. }
  315. // Setting the view in the item object.
  316. if (is_object($this->items[$row['iid']])) {
  317. $this->items[$row['iid']]->set_lp_view($this->lp_view_id, $course_id);
  318. if ($this->items[$row['iid']]->get_type() == TOOL_HOTPOTATOES) {
  319. $this->items[$row['iid']]->current_start_time = 0;
  320. $this->items[$row['iid']]->current_stop_time = 0;
  321. }
  322. }
  323. }
  324. if ($debug) {
  325. error_log('learnpath::__construct() '.__LINE__.' ----- end while ----');
  326. }
  327. if (!empty($lp_item_id_list)) {
  328. $lp_item_id_list_to_string = implode("','", $lp_item_id_list);
  329. if (!empty($lp_item_id_list_to_string)) {
  330. // Get last viewing vars.
  331. $itemViewTable = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  332. // This query should only return one or zero result.
  333. $sql = "SELECT lp_item_id, status
  334. FROM $itemViewTable
  335. WHERE
  336. c_id = $course_id AND
  337. lp_view_id = ".$this->lp_view_id." AND
  338. lp_item_id IN ('".$lp_item_id_list_to_string."')
  339. ORDER BY view_count DESC ";
  340. if ($debug) {
  341. error_log(
  342. 'learnpath::__construct() - Selecting item_views: '.$sql,
  343. 0
  344. );
  345. }
  346. $status_list = [];
  347. $res = Database::query($sql);
  348. while ($row = Database:: fetch_array($res)) {
  349. $status_list[$row['lp_item_id']] = $row['status'];
  350. }
  351. foreach ($lp_item_id_list as $item_id) {
  352. if (isset($status_list[$item_id])) {
  353. $status = $status_list[$item_id];
  354. if (is_object($this->items[$item_id])) {
  355. $this->items[$item_id]->set_status($status);
  356. if (empty($status)) {
  357. $this->items[$item_id]->set_status(
  358. $this->default_status
  359. );
  360. }
  361. }
  362. } else {
  363. if (!api_is_invitee()) {
  364. if (is_object($this->items[$item_id])) {
  365. $this->items[$item_id]->set_status(
  366. $this->default_status
  367. );
  368. }
  369. if (!empty($this->lp_view_id)) {
  370. // Add that row to the lp_item_view table so that
  371. // we have something to show in the stats page.
  372. $params = [
  373. 'c_id' => $course_id,
  374. 'lp_item_id' => $item_id,
  375. 'lp_view_id' => $this->lp_view_id,
  376. 'view_count' => 1,
  377. 'status' => 'not attempted',
  378. 'start_time' => time(),
  379. 'total_time' => 0,
  380. 'score' => 0,
  381. ];
  382. $insertId = Database::insert($itemViewTable, $params);
  383. if ($insertId) {
  384. $sql = "UPDATE $itemViewTable SET id = iid
  385. WHERE iid = $insertId";
  386. Database::query($sql);
  387. }
  388. $this->items[$item_id]->set_lp_view(
  389. $this->lp_view_id,
  390. $course_id
  391. );
  392. }
  393. }
  394. }
  395. }
  396. }
  397. }
  398. $this->ordered_items = self::get_flat_ordered_items_list(
  399. $this->get_id(),
  400. 0,
  401. $course_id
  402. );
  403. $this->max_ordered_items = 0;
  404. foreach ($this->ordered_items as $index => $dummy) {
  405. if ($index > $this->max_ordered_items && !empty($dummy)) {
  406. $this->max_ordered_items = $index;
  407. }
  408. }
  409. // TODO: Define the current item better.
  410. $this->first();
  411. if ($debug) {
  412. error_log('lp_view_session_id '.$this->lp_view_session_id);
  413. error_log('End of learnpath constructor for learnpath '.$this->get_id());
  414. }
  415. } else {
  416. $this->error = 'Learnpath ID does not exist in database ('.$sql.')';
  417. }
  418. }
  419. }
  420. /**
  421. * @return string
  422. */
  423. public function getCourseCode()
  424. {
  425. return $this->cc;
  426. }
  427. /**
  428. * @return int
  429. */
  430. public function get_course_int_id()
  431. {
  432. return isset($this->course_int_id) ? $this->course_int_id : api_get_course_int_id();
  433. }
  434. /**
  435. * @param $course_id
  436. *
  437. * @return int
  438. */
  439. public function set_course_int_id($course_id)
  440. {
  441. return $this->course_int_id = (int) $course_id;
  442. }
  443. /**
  444. * Function rewritten based on old_add_item() from Yannick Warnier.
  445. * Due the fact that users can decide where the item should come, I had to overlook this function and
  446. * I found it better to rewrite it. Old function is still available.
  447. * Added also the possibility to add a description.
  448. *
  449. * @param int $parent
  450. * @param int $previous
  451. * @param string $type
  452. * @param int $id resource ID (ref)
  453. * @param string $title
  454. * @param string $description
  455. * @param int $prerequisites
  456. * @param int $max_time_allowed
  457. * @param int $userId
  458. *
  459. * @return int
  460. */
  461. public function add_item(
  462. $parent,
  463. $previous,
  464. $type = 'dir',
  465. $id,
  466. $title,
  467. $description,
  468. $prerequisites = 0,
  469. $max_time_allowed = 0,
  470. $userId = 0
  471. ) {
  472. $course_id = $this->course_info['real_id'];
  473. if ($this->debug > 0) {
  474. error_log('In learnpath::add_item('.$parent.','.$previous.','.$type.','.$id.','.$title.')');
  475. }
  476. if (empty($course_id)) {
  477. // Sometimes Oogie doesn't catch the course info but sets $this->cc
  478. $this->course_info = api_get_course_info($this->cc);
  479. $course_id = $this->course_info['real_id'];
  480. }
  481. $userId = empty($userId) ? api_get_user_id() : $userId;
  482. $sessionId = api_get_session_id();
  483. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  484. $_course = $this->course_info;
  485. $parent = (int) $parent;
  486. $previous = (int) $previous;
  487. $id = (int) $id;
  488. $max_time_allowed = htmlentities($max_time_allowed);
  489. if (empty($max_time_allowed)) {
  490. $max_time_allowed = 0;
  491. }
  492. $sql = "SELECT COUNT(iid) AS num
  493. FROM $tbl_lp_item
  494. WHERE
  495. c_id = $course_id AND
  496. lp_id = ".$this->get_id()." AND
  497. parent_item_id = ".$parent;
  498. $res_count = Database::query($sql);
  499. $row = Database::fetch_array($res_count);
  500. $num = $row['num'];
  501. $tmp_previous = 0;
  502. $display_order = 0;
  503. $next = 0;
  504. if ($num > 0) {
  505. if (empty($previous)) {
  506. $sql = "SELECT iid, next_item_id, display_order
  507. FROM $tbl_lp_item
  508. WHERE
  509. c_id = $course_id AND
  510. lp_id = ".$this->get_id()." AND
  511. parent_item_id = $parent AND
  512. previous_item_id = 0 OR
  513. previous_item_id = $parent";
  514. $result = Database::query($sql);
  515. $row = Database::fetch_array($result);
  516. if ($row) {
  517. $next = $row['iid'];
  518. }
  519. } else {
  520. $previous = (int) $previous;
  521. $sql = "SELECT iid, previous_item_id, next_item_id, display_order
  522. FROM $tbl_lp_item
  523. WHERE
  524. c_id = $course_id AND
  525. lp_id = ".$this->get_id()." AND
  526. id = $previous";
  527. $result = Database::query($sql);
  528. $row = Database::fetch_array($result);
  529. if ($row) {
  530. $tmp_previous = $row['iid'];
  531. $next = $row['next_item_id'];
  532. $display_order = $row['display_order'];
  533. }
  534. }
  535. }
  536. $id = (int) $id;
  537. $typeCleaned = Database::escape_string($type);
  538. $max_score = 100;
  539. if ($type === 'quiz') {
  540. $sql = 'SELECT SUM(ponderation)
  541. FROM '.Database::get_course_table(TABLE_QUIZ_QUESTION).' as quiz_question
  542. INNER JOIN '.Database::get_course_table(TABLE_QUIZ_TEST_QUESTION).' as quiz_rel_question
  543. ON
  544. quiz_question.id = quiz_rel_question.question_id AND
  545. quiz_question.c_id = quiz_rel_question.c_id
  546. WHERE
  547. quiz_rel_question.exercice_id = '.$id." AND
  548. quiz_question.c_id = $course_id AND
  549. quiz_rel_question.c_id = $course_id ";
  550. $rsQuiz = Database::query($sql);
  551. $max_score = Database::result($rsQuiz, 0, 0);
  552. // Disabling the exercise if we add it inside a LP
  553. $exercise = new Exercise($course_id);
  554. $exercise->read($id);
  555. $exercise->disable();
  556. $exercise->save();
  557. }
  558. $params = [
  559. 'c_id' => $course_id,
  560. 'lp_id' => $this->get_id(),
  561. 'item_type' => $typeCleaned,
  562. 'ref' => '',
  563. 'title' => $title,
  564. 'description' => $description,
  565. 'path' => $id,
  566. 'max_score' => $max_score,
  567. 'parent_item_id' => $parent,
  568. 'previous_item_id' => $previous,
  569. 'next_item_id' => (int) $next,
  570. 'display_order' => $display_order + 1,
  571. 'prerequisite' => $prerequisites,
  572. 'max_time_allowed' => $max_time_allowed,
  573. 'min_score' => 0,
  574. 'launch_data' => '',
  575. ];
  576. if ($prerequisites != 0) {
  577. $params['prerequisite'] = $prerequisites;
  578. }
  579. $new_item_id = Database::insert($tbl_lp_item, $params);
  580. if ($new_item_id) {
  581. if ($this->debug > 2) {
  582. error_log('Inserting dir/chapter: '.$new_item_id, 0);
  583. }
  584. $sql = "UPDATE $tbl_lp_item SET id = iid WHERE iid = $new_item_id";
  585. Database::query($sql);
  586. if (!empty($next)) {
  587. $sql = "UPDATE $tbl_lp_item
  588. SET previous_item_id = $new_item_id
  589. WHERE c_id = $course_id AND id = $next AND item_type != '".TOOL_LP_FINAL_ITEM."'";
  590. Database::query($sql);
  591. }
  592. // Update the item that should be before the new item.
  593. if (!empty($tmp_previous)) {
  594. $sql = "UPDATE $tbl_lp_item
  595. SET next_item_id = $new_item_id
  596. WHERE c_id = $course_id AND id = $tmp_previous";
  597. Database::query($sql);
  598. }
  599. // Update all the items after the new item.
  600. $sql = "UPDATE $tbl_lp_item
  601. SET display_order = display_order + 1
  602. WHERE
  603. c_id = $course_id AND
  604. lp_id = ".$this->get_id()." AND
  605. iid <> $new_item_id AND
  606. parent_item_id = $parent AND
  607. display_order > $display_order";
  608. Database::query($sql);
  609. // Update the item that should come after the new item.
  610. $sql = "UPDATE $tbl_lp_item
  611. SET ref = $new_item_id
  612. WHERE c_id = $course_id AND iid = $new_item_id";
  613. Database::query($sql);
  614. $sql = "UPDATE $tbl_lp_item
  615. SET previous_item_id = ".$this->getLastInFirstLevel()."
  616. WHERE c_id = $course_id AND lp_id = {$this->lp_id} AND item_type = '".TOOL_LP_FINAL_ITEM."'";
  617. Database::query($sql);
  618. // Upload audio.
  619. if (!empty($_FILES['mp3']['name'])) {
  620. // Create the audio folder if it does not exist yet.
  621. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  622. if (!is_dir($filepath.'audio')) {
  623. mkdir(
  624. $filepath.'audio',
  625. api_get_permissions_for_new_directories()
  626. );
  627. $audio_id = add_document(
  628. $_course,
  629. '/audio',
  630. 'folder',
  631. 0,
  632. 'audio',
  633. '',
  634. 0,
  635. true,
  636. null,
  637. $sessionId,
  638. $userId
  639. );
  640. api_item_property_update(
  641. $_course,
  642. TOOL_DOCUMENT,
  643. $audio_id,
  644. 'FolderCreated',
  645. $userId,
  646. null,
  647. null,
  648. null,
  649. null,
  650. $sessionId
  651. );
  652. api_item_property_update(
  653. $_course,
  654. TOOL_DOCUMENT,
  655. $audio_id,
  656. 'invisible',
  657. $userId,
  658. null,
  659. null,
  660. null,
  661. null,
  662. $sessionId
  663. );
  664. }
  665. $file_path = handle_uploaded_document(
  666. $_course,
  667. $_FILES['mp3'],
  668. api_get_path(SYS_COURSE_PATH).$_course['path'].'/document',
  669. '/audio',
  670. $userId,
  671. '',
  672. '',
  673. '',
  674. '',
  675. false
  676. );
  677. // Getting the filename only.
  678. $file_components = explode('/', $file_path);
  679. $file = $file_components[count($file_components) - 1];
  680. // Store the mp3 file in the lp_item table.
  681. $sql = "UPDATE $tbl_lp_item SET
  682. audio = '".Database::escape_string($file)."'
  683. WHERE iid = '".intval($new_item_id)."'";
  684. Database::query($sql);
  685. }
  686. }
  687. return $new_item_id;
  688. }
  689. /**
  690. * Static admin function allowing addition of a learnpath to a course.
  691. *
  692. * @param string $courseCode
  693. * @param string $name
  694. * @param string $description
  695. * @param string $learnpath
  696. * @param string $origin
  697. * @param string $zipname Zip file containing the learnpath or directory containing the learnpath
  698. * @param string $publicated_on
  699. * @param string $expired_on
  700. * @param int $categoryId
  701. * @param int $userId
  702. *
  703. * @return int The new learnpath ID on success, 0 on failure
  704. */
  705. public static function add_lp(
  706. $courseCode,
  707. $name,
  708. $description = '',
  709. $learnpath = 'guess',
  710. $origin = 'zip',
  711. $zipname = '',
  712. $publicated_on = '',
  713. $expired_on = '',
  714. $categoryId = 0,
  715. $userId = 0
  716. ) {
  717. global $charset;
  718. if (!empty($courseCode)) {
  719. $courseInfo = api_get_course_info($courseCode);
  720. $course_id = $courseInfo['real_id'];
  721. } else {
  722. $course_id = api_get_course_int_id();
  723. $courseInfo = api_get_course_info();
  724. }
  725. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  726. // Check course code exists.
  727. // Check lp_name doesn't exist, otherwise append something.
  728. $i = 0;
  729. $name = Database::escape_string($name);
  730. $categoryId = (int) $categoryId;
  731. // Session id.
  732. $session_id = api_get_session_id();
  733. $userId = empty($userId) ? api_get_user_id() : $userId;
  734. $check_name = "SELECT * FROM $tbl_lp
  735. WHERE c_id = $course_id AND name = '$name'";
  736. $res_name = Database::query($check_name);
  737. if (empty($publicated_on)) {
  738. $publicated_on = null;
  739. } else {
  740. $publicated_on = Database::escape_string(api_get_utc_datetime($publicated_on));
  741. }
  742. if (empty($expired_on)) {
  743. $expired_on = null;
  744. } else {
  745. $expired_on = Database::escape_string(api_get_utc_datetime($expired_on));
  746. }
  747. while (Database::num_rows($res_name)) {
  748. // There is already one such name, update the current one a bit.
  749. $i++;
  750. $name = $name.' - '.$i;
  751. $check_name = "SELECT * FROM $tbl_lp
  752. WHERE c_id = $course_id AND name = '$name'";
  753. $res_name = Database::query($check_name);
  754. }
  755. // New name does not exist yet; keep it.
  756. // Escape description.
  757. // Kevin: added htmlentities().
  758. $description = Database::escape_string(api_htmlentities($description, ENT_QUOTES, $charset));
  759. $type = 1;
  760. switch ($learnpath) {
  761. case 'guess':
  762. break;
  763. case 'dokeos':
  764. case 'chamilo':
  765. $type = 1;
  766. break;
  767. case 'aicc':
  768. break;
  769. }
  770. switch ($origin) {
  771. case 'zip':
  772. // Check zip name string. If empty, we are currently creating a new Chamilo learnpath.
  773. break;
  774. case 'manual':
  775. default:
  776. $get_max = "SELECT MAX(display_order)
  777. FROM $tbl_lp WHERE c_id = $course_id";
  778. $res_max = Database::query($get_max);
  779. if (Database::num_rows($res_max) < 1) {
  780. $dsp = 1;
  781. } else {
  782. $row = Database::fetch_array($res_max);
  783. $dsp = $row[0] + 1;
  784. }
  785. $params = [
  786. 'c_id' => $course_id,
  787. 'lp_type' => $type,
  788. 'name' => $name,
  789. 'description' => $description,
  790. 'path' => '',
  791. 'default_view_mod' => 'embedded',
  792. 'default_encoding' => 'UTF-8',
  793. 'display_order' => $dsp,
  794. 'content_maker' => 'Chamilo',
  795. 'content_local' => 'local',
  796. 'js_lib' => '',
  797. 'session_id' => $session_id,
  798. 'created_on' => api_get_utc_datetime(),
  799. 'modified_on' => api_get_utc_datetime(),
  800. 'publicated_on' => $publicated_on,
  801. 'expired_on' => $expired_on,
  802. 'category_id' => $categoryId,
  803. 'force_commit' => 0,
  804. 'content_license' => '',
  805. 'debug' => 0,
  806. 'theme' => '',
  807. 'preview_image' => '',
  808. 'author' => '',
  809. 'prerequisite' => 0,
  810. 'hide_toc_frame' => 0,
  811. 'seriousgame_mode' => 0,
  812. 'autolaunch' => 0,
  813. 'max_attempts' => 0,
  814. 'subscribe_users' => 0,
  815. 'accumulate_scorm_time' => 1,
  816. ];
  817. $id = Database::insert($tbl_lp, $params);
  818. if ($id > 0) {
  819. $sql = "UPDATE $tbl_lp SET id = iid WHERE iid = $id";
  820. Database::query($sql);
  821. // Insert into item_property.
  822. api_item_property_update(
  823. $courseInfo,
  824. TOOL_LEARNPATH,
  825. $id,
  826. 'LearnpathAdded',
  827. $userId
  828. );
  829. api_set_default_visibility(
  830. $id,
  831. TOOL_LEARNPATH,
  832. 0,
  833. $courseInfo,
  834. $session_id,
  835. $userId
  836. );
  837. return $id;
  838. }
  839. break;
  840. }
  841. }
  842. /**
  843. * Auto completes the parents of an item in case it's been completed or passed.
  844. *
  845. * @param int $item Optional ID of the item from which to look for parents
  846. */
  847. public function autocomplete_parents($item)
  848. {
  849. $debug = $this->debug;
  850. if ($debug) {
  851. error_log('Learnpath::autocomplete_parents()');
  852. }
  853. if (empty($item)) {
  854. $item = $this->current;
  855. }
  856. $currentItem = $this->getItem($item);
  857. if ($currentItem) {
  858. $parent_id = $currentItem->get_parent();
  859. $parent = $this->getItem($parent_id);
  860. if ($parent) {
  861. // if $item points to an object and there is a parent.
  862. if ($debug) {
  863. error_log(
  864. 'Autocompleting parent of item '.$item.' '.
  865. $currentItem->get_title().'" (item '.$parent_id.' "'.$parent->get_title().'") ',
  866. 0
  867. );
  868. }
  869. // New experiment including failed and browsed in completed status.
  870. //$current_status = $currentItem->get_status();
  871. //if ($currentItem->is_done() || $current_status == 'browsed' || $current_status == 'failed') {
  872. // Fixes chapter auto complete
  873. if (true) {
  874. // If the current item is completed or passes or succeeded.
  875. $updateParentStatus = true;
  876. if ($debug) {
  877. error_log('Status of current item is alright');
  878. }
  879. foreach ($parent->get_children() as $childItemId) {
  880. $childItem = $this->getItem($childItemId);
  881. // If children was not set try to get the info
  882. if (empty($childItem->db_item_view_id)) {
  883. $childItem->set_lp_view($this->lp_view_id, $this->course_int_id);
  884. }
  885. // Check all his brothers (parent's children) for completion status.
  886. if ($childItemId != $item) {
  887. if ($debug) {
  888. error_log(
  889. 'Looking at brother #'.$childItemId.' "'.$childItem->get_title().'", status is '.$childItem->get_status(),
  890. 0
  891. );
  892. }
  893. // Trying completing parents of failed and browsed items as well.
  894. if ($childItem->status_is(
  895. [
  896. 'completed',
  897. 'passed',
  898. 'succeeded',
  899. 'browsed',
  900. 'failed',
  901. ]
  902. )
  903. ) {
  904. // Keep completion status to true.
  905. continue;
  906. } else {
  907. if ($debug > 2) {
  908. error_log(
  909. '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,
  910. 0
  911. );
  912. }
  913. $updateParentStatus = false;
  914. break;
  915. }
  916. }
  917. }
  918. if ($updateParentStatus) {
  919. // If all the children were completed:
  920. $parent->set_status('completed');
  921. $parent->save(false, $this->prerequisites_match($parent->get_id()));
  922. // Force the status to "completed"
  923. //$this->update_queue[$parent->get_id()] = $parent->get_status();
  924. $this->update_queue[$parent->get_id()] = 'completed';
  925. if ($debug) {
  926. error_log(
  927. 'Added parent #'.$parent->get_id().' "'.$parent->get_title().'" to update queue status: completed '.
  928. print_r($this->update_queue, 1),
  929. 0
  930. );
  931. }
  932. // Recursive call.
  933. $this->autocomplete_parents($parent->get_id());
  934. }
  935. }
  936. } else {
  937. if ($debug) {
  938. error_log("Parent #$parent_id does not exists");
  939. }
  940. }
  941. } else {
  942. if ($debug) {
  943. error_log("#$item is an item that doesn't have parents");
  944. }
  945. }
  946. }
  947. /**
  948. * Closes the current resource.
  949. *
  950. * Stops the timer
  951. * Saves into the database if required
  952. * Clears the current resource data from this object
  953. *
  954. * @return bool True on success, false on failure
  955. */
  956. public function close()
  957. {
  958. if ($this->debug > 0) {
  959. error_log('In learnpath::close()', 0);
  960. }
  961. if (empty($this->lp_id)) {
  962. $this->error = 'Trying to close this learnpath but no ID is set';
  963. return false;
  964. }
  965. $this->current_time_stop = time();
  966. $this->ordered_items = [];
  967. $this->index = 0;
  968. unset($this->lp_id);
  969. //unset other stuff
  970. return true;
  971. }
  972. /**
  973. * Static admin function allowing removal of a learnpath.
  974. *
  975. * @param array $courseInfo
  976. * @param int $id Learnpath ID
  977. * @param string $delete Whether to delete data or keep it (default: 'keep', others: 'remove')
  978. *
  979. * @return bool True on success, false on failure (might change that to return number of elements deleted)
  980. */
  981. public function delete($courseInfo = null, $id = null, $delete = 'keep')
  982. {
  983. $course_id = api_get_course_int_id();
  984. if (!empty($courseInfo)) {
  985. $course_id = isset($courseInfo['real_id']) ? $courseInfo['real_id'] : $course_id;
  986. }
  987. // TODO: Implement a way of getting this to work when the current object is not set.
  988. // In clear: implement this in the item class as well (abstract class) and use the given ID in queries.
  989. // If an ID is specifically given and the current LP is not the same, prevent delete.
  990. if (!empty($id) && ($id != $this->lp_id)) {
  991. return false;
  992. }
  993. $lp = Database::get_course_table(TABLE_LP_MAIN);
  994. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  995. $lp_view = Database::get_course_table(TABLE_LP_VIEW);
  996. $lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  997. // Delete lp item id.
  998. foreach ($this->items as $lpItemId => $dummy) {
  999. $sql = "DELETE FROM $lp_item_view
  1000. WHERE c_id = $course_id AND lp_item_id = '".$lpItemId."'";
  1001. Database::query($sql);
  1002. }
  1003. // Proposed by Christophe (nickname: clefevre)
  1004. $sql = "DELETE FROM $lp_item
  1005. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  1006. Database::query($sql);
  1007. $sql = "DELETE FROM $lp_view
  1008. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  1009. Database::query($sql);
  1010. self::toggle_publish($this->lp_id, 'i');
  1011. if ($this->type == 2 || $this->type == 3) {
  1012. // This is a scorm learning path, delete the files as well.
  1013. $sql = "SELECT path FROM $lp
  1014. WHERE iid = ".$this->lp_id;
  1015. $res = Database::query($sql);
  1016. if (Database::num_rows($res) > 0) {
  1017. $row = Database::fetch_array($res);
  1018. $path = $row['path'];
  1019. $sql = "SELECT id FROM $lp
  1020. WHERE
  1021. c_id = $course_id AND
  1022. path = '$path' AND
  1023. iid != ".$this->lp_id;
  1024. $res = Database::query($sql);
  1025. if (Database::num_rows($res) > 0) {
  1026. // Another learning path uses this directory, so don't delete it.
  1027. if ($this->debug > 2) {
  1028. error_log('In learnpath::delete(), found other LP using path '.$path.', keeping directory', 0);
  1029. }
  1030. } else {
  1031. // No other LP uses that directory, delete it.
  1032. $course_rel_dir = api_get_course_path().'/scorm/'; // scorm dir web path starting from /courses
  1033. // The absolute system path for this course.
  1034. $course_scorm_dir = api_get_path(SYS_COURSE_PATH).$course_rel_dir;
  1035. if ($delete == 'remove' && is_dir($course_scorm_dir.$path) && !empty($course_scorm_dir)) {
  1036. if ($this->debug > 2) {
  1037. error_log('In learnpath::delete(), found SCORM, deleting directory: '.$course_scorm_dir.$path, 0);
  1038. }
  1039. // Proposed by Christophe (clefevre).
  1040. if (strcmp(substr($path, -2), "/.") == 0) {
  1041. $path = substr($path, 0, -1); // Remove "." at the end.
  1042. }
  1043. //exec('rm -rf ' . $course_scorm_dir . $path); // See Bug #5208, this is not OS-portable way.
  1044. rmdirr($course_scorm_dir.$path);
  1045. }
  1046. }
  1047. }
  1048. }
  1049. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  1050. $link = 'lp/lp_controller.php?action=view&lp_id='.$this->lp_id;
  1051. // Delete tools
  1052. $sql = "DELETE FROM $tbl_tool
  1053. WHERE c_id = $course_id AND (link LIKE '$link%' AND image='scormbuilder.gif')";
  1054. Database::query($sql);
  1055. $sql = "DELETE FROM $lp
  1056. WHERE iid = ".$this->lp_id;
  1057. Database::query($sql);
  1058. // Updates the display order of all lps.
  1059. $this->update_display_order();
  1060. api_item_property_update(
  1061. api_get_course_info(),
  1062. TOOL_LEARNPATH,
  1063. $this->lp_id,
  1064. 'delete',
  1065. api_get_user_id()
  1066. );
  1067. $link_info = GradebookUtils::isResourceInCourseGradebook(
  1068. api_get_course_id(),
  1069. 4,
  1070. $id,
  1071. api_get_session_id()
  1072. );
  1073. if ($link_info !== false) {
  1074. GradebookUtils::remove_resource_from_course_gradebook($link_info['id']);
  1075. }
  1076. if (api_get_setting('search_enabled') == 'true') {
  1077. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  1078. delete_all_values_for_item($this->cc, TOOL_LEARNPATH, $this->lp_id);
  1079. }
  1080. }
  1081. /**
  1082. * Removes all the children of one item - dangerous!
  1083. *
  1084. * @param int $id Element ID of which children have to be removed
  1085. *
  1086. * @return int Total number of children removed
  1087. */
  1088. public function delete_children_items($id)
  1089. {
  1090. $course_id = $this->course_info['real_id'];
  1091. if ($this->debug > 0) {
  1092. error_log('In learnpath::delete_children_items('.$id.')', 0);
  1093. }
  1094. $num = 0;
  1095. if (empty($id) || $id != strval(intval($id))) {
  1096. return false;
  1097. }
  1098. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1099. $sql = "SELECT * FROM $lp_item
  1100. WHERE c_id = ".$course_id." AND parent_item_id = $id";
  1101. $res = Database::query($sql);
  1102. while ($row = Database::fetch_array($res)) {
  1103. $num += $this->delete_children_items($row['iid']);
  1104. $sql = "DELETE FROM $lp_item
  1105. WHERE c_id = ".$course_id." AND iid = ".$row['iid'];
  1106. Database::query($sql);
  1107. $num++;
  1108. }
  1109. return $num;
  1110. }
  1111. /**
  1112. * Removes an item from the current learnpath.
  1113. *
  1114. * @param int $id Elem ID (0 if first)
  1115. *
  1116. * @return int Number of elements moved
  1117. *
  1118. * @todo implement resource removal
  1119. */
  1120. public function delete_item($id)
  1121. {
  1122. $course_id = api_get_course_int_id();
  1123. if ($this->debug > 0) {
  1124. error_log('In learnpath::delete_item()', 0);
  1125. }
  1126. // TODO: Implement the resource removal.
  1127. if (empty($id) || $id != strval(intval($id))) {
  1128. return false;
  1129. }
  1130. // First select item to get previous, next, and display order.
  1131. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1132. $sql_sel = "SELECT * FROM $lp_item WHERE iid = $id";
  1133. $res_sel = Database::query($sql_sel);
  1134. if (Database::num_rows($res_sel) < 1) {
  1135. return false;
  1136. }
  1137. $row = Database::fetch_array($res_sel);
  1138. $previous = $row['previous_item_id'];
  1139. $next = $row['next_item_id'];
  1140. $display = $row['display_order'];
  1141. $parent = $row['parent_item_id'];
  1142. $lp = $row['lp_id'];
  1143. // Delete children items.
  1144. $num = $this->delete_children_items($id);
  1145. if ($this->debug > 2) {
  1146. error_log('learnpath::delete_item() - deleted '.$num.' children of element '.$id, 0);
  1147. }
  1148. // Now delete the item.
  1149. $sql_del = "DELETE FROM $lp_item WHERE iid = $id";
  1150. if ($this->debug > 2) {
  1151. error_log('Deleting item: '.$sql_del, 0);
  1152. }
  1153. Database::query($sql_del);
  1154. // Now update surrounding items.
  1155. $sql_upd = "UPDATE $lp_item SET next_item_id = $next
  1156. WHERE iid = $previous";
  1157. Database::query($sql_upd);
  1158. $sql_upd = "UPDATE $lp_item SET previous_item_id = $previous
  1159. WHERE iid = $next AND item_type != '".TOOL_LP_FINAL_ITEM."'";
  1160. Database::query($sql_upd);
  1161. // Now update all following items with new display order.
  1162. $sql_all = "UPDATE $lp_item SET display_order = display_order-1
  1163. WHERE
  1164. c_id = $course_id AND
  1165. lp_id = $lp AND
  1166. parent_item_id = $parent AND
  1167. display_order > $display";
  1168. Database::query($sql_all);
  1169. //Removing prerequisites since the item will not longer exist
  1170. $sql_all = "UPDATE $lp_item SET prerequisite = ''
  1171. WHERE c_id = $course_id AND prerequisite = $id";
  1172. Database::query($sql_all);
  1173. $sql = "UPDATE $lp_item
  1174. SET previous_item_id = ".$this->getLastInFirstLevel()."
  1175. WHERE c_id = $course_id AND lp_id = {$this->lp_id} AND item_type = '".TOOL_LP_FINAL_ITEM."'";
  1176. Database::query($sql);
  1177. // Remove from search engine if enabled.
  1178. if (api_get_setting('search_enabled') === 'true') {
  1179. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  1180. $sql = 'SELECT * FROM %s
  1181. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
  1182. LIMIT 1';
  1183. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp, $id);
  1184. $res = Database::query($sql);
  1185. if (Database::num_rows($res) > 0) {
  1186. $row2 = Database::fetch_array($res);
  1187. $di = new ChamiloIndexer();
  1188. $di->remove_document($row2['search_did']);
  1189. }
  1190. $sql = 'DELETE FROM %s
  1191. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
  1192. LIMIT 1';
  1193. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp, $id);
  1194. Database::query($sql);
  1195. }
  1196. }
  1197. /**
  1198. * Updates an item's content in place.
  1199. *
  1200. * @param int $id Element ID
  1201. * @param int $parent Parent item ID
  1202. * @param int $previous Previous item ID
  1203. * @param string $title Item title
  1204. * @param string $description Item description
  1205. * @param string $prerequisites Prerequisites (optional)
  1206. * @param array $audio The array resulting of the $_FILES[mp3] element
  1207. * @param int $max_time_allowed
  1208. * @param string $url
  1209. *
  1210. * @return bool True on success, false on error
  1211. */
  1212. public function edit_item(
  1213. $id,
  1214. $parent,
  1215. $previous,
  1216. $title,
  1217. $description,
  1218. $prerequisites = '0',
  1219. $audio = [],
  1220. $max_time_allowed = 0,
  1221. $url = ''
  1222. ) {
  1223. $course_id = api_get_course_int_id();
  1224. $_course = api_get_course_info();
  1225. if ($this->debug > 0) {
  1226. error_log('In learnpath::edit_item()', 0);
  1227. }
  1228. if (empty($max_time_allowed)) {
  1229. $max_time_allowed = 0;
  1230. }
  1231. if (empty($id) || ($id != strval(intval($id))) || empty($title)) {
  1232. return false;
  1233. }
  1234. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1235. $sql = "SELECT * FROM $tbl_lp_item
  1236. WHERE iid = $id";
  1237. $res_select = Database::query($sql);
  1238. $row_select = Database::fetch_array($res_select);
  1239. $audio_update_sql = '';
  1240. if (is_array($audio) && !empty($audio['tmp_name']) && $audio['error'] === 0) {
  1241. // Create the audio folder if it does not exist yet.
  1242. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  1243. if (!is_dir($filepath.'audio')) {
  1244. mkdir($filepath.'audio', api_get_permissions_for_new_directories());
  1245. $audio_id = add_document(
  1246. $_course,
  1247. '/audio',
  1248. 'folder',
  1249. 0,
  1250. 'audio'
  1251. );
  1252. api_item_property_update(
  1253. $_course,
  1254. TOOL_DOCUMENT,
  1255. $audio_id,
  1256. 'FolderCreated',
  1257. api_get_user_id(),
  1258. null,
  1259. null,
  1260. null,
  1261. null,
  1262. api_get_session_id()
  1263. );
  1264. api_item_property_update(
  1265. $_course,
  1266. TOOL_DOCUMENT,
  1267. $audio_id,
  1268. 'invisible',
  1269. api_get_user_id(),
  1270. null,
  1271. null,
  1272. null,
  1273. null,
  1274. api_get_session_id()
  1275. );
  1276. }
  1277. // Upload file in documents.
  1278. $pi = pathinfo($audio['name']);
  1279. if ($pi['extension'] == 'mp3') {
  1280. $c_det = api_get_course_info($this->cc);
  1281. $bp = api_get_path(SYS_COURSE_PATH).$c_det['path'].'/document';
  1282. $path = handle_uploaded_document(
  1283. $c_det,
  1284. $audio,
  1285. $bp,
  1286. '/audio',
  1287. api_get_user_id(),
  1288. 0,
  1289. null,
  1290. 0,
  1291. 'rename',
  1292. false,
  1293. 0
  1294. );
  1295. $path = substr($path, 7);
  1296. // Update reference in lp_item - audio path is the path from inside de document/audio/ dir.
  1297. $audio_update_sql = ", audio = '".Database::escape_string($path)."' ";
  1298. }
  1299. }
  1300. $same_parent = $row_select['parent_item_id'] == $parent ? true : false;
  1301. $same_previous = $row_select['previous_item_id'] == $previous ? true : false;
  1302. // TODO: htmlspecialchars to be checked for encoding related problems.
  1303. if ($same_parent && $same_previous) {
  1304. // Only update title and description.
  1305. $sql = "UPDATE $tbl_lp_item
  1306. SET title = '".Database::escape_string($title)."',
  1307. prerequisite = '".$prerequisites."',
  1308. description = '".Database::escape_string($description)."'
  1309. ".$audio_update_sql.",
  1310. max_time_allowed = '".Database::escape_string($max_time_allowed)."'
  1311. WHERE iid = $id";
  1312. Database::query($sql);
  1313. } else {
  1314. $old_parent = $row_select['parent_item_id'];
  1315. $old_previous = $row_select['previous_item_id'];
  1316. $old_next = $row_select['next_item_id'];
  1317. $old_order = $row_select['display_order'];
  1318. $old_prerequisite = $row_select['prerequisite'];
  1319. $old_max_time_allowed = $row_select['max_time_allowed'];
  1320. /* BEGIN -- virtually remove the current item id */
  1321. /* for the next and previous item it is like the current item doesn't exist anymore */
  1322. if ($old_previous != 0) {
  1323. // Next
  1324. $sql = "UPDATE $tbl_lp_item
  1325. SET next_item_id = $old_next
  1326. WHERE iid = $old_previous";
  1327. Database::query($sql);
  1328. }
  1329. if (!empty($old_next)) {
  1330. // Previous
  1331. $sql = "UPDATE $tbl_lp_item
  1332. SET previous_item_id = $old_previous
  1333. WHERE iid = $old_next";
  1334. Database::query($sql);
  1335. }
  1336. // display_order - 1 for every item with a display_order
  1337. // bigger then the display_order of the current item.
  1338. $sql = "UPDATE $tbl_lp_item
  1339. SET display_order = display_order - 1
  1340. WHERE
  1341. c_id = $course_id AND
  1342. display_order > $old_order AND
  1343. lp_id = ".$this->lp_id." AND
  1344. parent_item_id = $old_parent";
  1345. Database::query($sql);
  1346. /* END -- virtually remove the current item id */
  1347. /* BEGIN -- update the current item id to his new location */
  1348. if ($previous == 0) {
  1349. // Select the data of the item that should come after the current item.
  1350. $sql = "SELECT id, display_order
  1351. FROM $tbl_lp_item
  1352. WHERE
  1353. c_id = $course_id AND
  1354. lp_id = ".$this->lp_id." AND
  1355. parent_item_id = $parent AND
  1356. previous_item_id = $previous";
  1357. $res_select_old = Database::query($sql);
  1358. $row_select_old = Database::fetch_array($res_select_old);
  1359. // If the new parent didn't have children before.
  1360. if (Database::num_rows($res_select_old) == 0) {
  1361. $new_next = 0;
  1362. $new_order = 1;
  1363. } else {
  1364. $new_next = $row_select_old['id'];
  1365. $new_order = $row_select_old['display_order'];
  1366. }
  1367. } else {
  1368. // Select the data of the item that should come before the current item.
  1369. $sql = "SELECT next_item_id, display_order
  1370. FROM $tbl_lp_item
  1371. WHERE iid = $previous";
  1372. $res_select_old = Database::query($sql);
  1373. $row_select_old = Database::fetch_array($res_select_old);
  1374. $new_next = $row_select_old['next_item_id'];
  1375. $new_order = $row_select_old['display_order'] + 1;
  1376. }
  1377. // TODO: htmlspecialchars to be checked for encoding related problems.
  1378. // Update the current item with the new data.
  1379. $sql = "UPDATE $tbl_lp_item
  1380. SET
  1381. title = '".Database::escape_string($title)."',
  1382. description = '".Database::escape_string($description)."',
  1383. parent_item_id = $parent,
  1384. previous_item_id = $previous,
  1385. next_item_id = $new_next,
  1386. display_order = $new_order
  1387. $audio_update_sql
  1388. WHERE iid = $id";
  1389. Database::query($sql);
  1390. if ($previous != 0) {
  1391. // Update the previous item's next_item_id.
  1392. $sql = "UPDATE $tbl_lp_item
  1393. SET next_item_id = $id
  1394. WHERE iid = $previous";
  1395. Database::query($sql);
  1396. }
  1397. if (!empty($new_next)) {
  1398. // Update the next item's previous_item_id.
  1399. $sql = "UPDATE $tbl_lp_item
  1400. SET previous_item_id = $id
  1401. WHERE iid = $new_next";
  1402. Database::query($sql);
  1403. }
  1404. if ($old_prerequisite != $prerequisites) {
  1405. $sql = "UPDATE $tbl_lp_item
  1406. SET prerequisite = '$prerequisites'
  1407. WHERE iid = $id";
  1408. Database::query($sql);
  1409. }
  1410. if ($old_max_time_allowed != $max_time_allowed) {
  1411. // update max time allowed
  1412. $sql = "UPDATE $tbl_lp_item
  1413. SET max_time_allowed = $max_time_allowed
  1414. WHERE iid = $id";
  1415. Database::query($sql);
  1416. }
  1417. // Update all the items with the same or a bigger display_order than the current item.
  1418. $sql = "UPDATE $tbl_lp_item
  1419. SET display_order = display_order + 1
  1420. WHERE
  1421. c_id = $course_id AND
  1422. lp_id = ".$this->get_id()." AND
  1423. iid <> $id AND
  1424. parent_item_id = $parent AND
  1425. display_order >= $new_order";
  1426. Database::query($sql);
  1427. }
  1428. if ($row_select['item_type'] == 'link') {
  1429. $link = new Link();
  1430. $linkId = $row_select['path'];
  1431. $link->updateLink($linkId, $url);
  1432. }
  1433. }
  1434. /**
  1435. * Updates an item's prereq in place.
  1436. *
  1437. * @param int $id Element ID
  1438. * @param string $prerequisite_id Prerequisite Element ID
  1439. * @param int $minScore Prerequisite min score
  1440. * @param int $maxScore Prerequisite max score
  1441. *
  1442. * @return bool True on success, false on error
  1443. */
  1444. public function edit_item_prereq(
  1445. $id,
  1446. $prerequisite_id,
  1447. $minScore = 0,
  1448. $maxScore = 100
  1449. ) {
  1450. if ($this->debug > 0) {
  1451. error_log('In learnpath::edit_item_prereq('.$id.','.$prerequisite_id.','.$minScore.','.$maxScore.')', 0);
  1452. }
  1453. $id = (int) $id;
  1454. $prerequisite_id = (int) $prerequisite_id;
  1455. if (empty($id)) {
  1456. return false;
  1457. }
  1458. if (empty($minScore) || $minScore < 0) {
  1459. $minScore = 0;
  1460. }
  1461. if (empty($maxScore) || $maxScore < 0) {
  1462. $maxScore = 100;
  1463. }
  1464. $minScore = floatval($minScore);
  1465. $maxScore = floatval($maxScore);
  1466. if (empty($prerequisite_id)) {
  1467. $prerequisite_id = 'NULL';
  1468. $minScore = 0;
  1469. $maxScore = 100;
  1470. }
  1471. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1472. $sql = " UPDATE $tbl_lp_item
  1473. SET
  1474. prerequisite = $prerequisite_id ,
  1475. prerequisite_min_score = $minScore ,
  1476. prerequisite_max_score = $maxScore
  1477. WHERE iid = $id";
  1478. Database::query($sql);
  1479. return true;
  1480. }
  1481. /**
  1482. * Gets all the chapters belonging to the same parent as the item/chapter given
  1483. * Can also be called as abstract method.
  1484. *
  1485. * @param int $id Item ID
  1486. *
  1487. * @return array A list of all the "brother items" (or an empty array on failure)
  1488. */
  1489. public function getSiblingDirectories($id)
  1490. {
  1491. $course_id = api_get_course_int_id();
  1492. if ($this->debug > 0) {
  1493. error_log('In learnpath::getSiblingDirectories()', 0);
  1494. }
  1495. if (empty($id) || $id != strval(intval($id))) {
  1496. return [];
  1497. }
  1498. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1499. $sql_parent = "SELECT * FROM $lp_item
  1500. WHERE iid = $id AND item_type='dir'";
  1501. $res_parent = Database::query($sql_parent);
  1502. if (Database::num_rows($res_parent) > 0) {
  1503. $row_parent = Database::fetch_array($res_parent);
  1504. $parent = $row_parent['parent_item_id'];
  1505. $sql = "SELECT * FROM $lp_item
  1506. WHERE
  1507. parent_item_id = $parent AND
  1508. iid = $id AND
  1509. item_type='dir'
  1510. ORDER BY display_order";
  1511. $res_bros = Database::query($sql);
  1512. $list = [];
  1513. while ($row_bro = Database::fetch_array($res_bros)) {
  1514. $list[] = $row_bro;
  1515. }
  1516. return $list;
  1517. }
  1518. return [];
  1519. }
  1520. /**
  1521. * Gets all the items belonging to the same parent as the item given
  1522. * Can also be called as abstract method.
  1523. *
  1524. * @param int $id Item ID
  1525. *
  1526. * @return array A list of all the "brother items" (or an empty array on failure)
  1527. */
  1528. public function get_brother_items($id)
  1529. {
  1530. $course_id = api_get_course_int_id();
  1531. if ($this->debug > 0) {
  1532. error_log('In learnpath::get_brother_items('.$id.')', 0);
  1533. }
  1534. if (empty($id) || $id != strval(intval($id))) {
  1535. return [];
  1536. }
  1537. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1538. $sql_parent = "SELECT * FROM $lp_item
  1539. WHERE iid = $id";
  1540. $res_parent = Database::query($sql_parent);
  1541. if (Database::num_rows($res_parent) > 0) {
  1542. $row_parent = Database::fetch_array($res_parent);
  1543. $parent = $row_parent['parent_item_id'];
  1544. $sql = "SELECT * FROM $lp_item
  1545. WHERE c_id = $course_id AND parent_item_id = $parent
  1546. ORDER BY display_order";
  1547. $res_bros = Database::query($sql);
  1548. $list = [];
  1549. while ($row_bro = Database::fetch_array($res_bros)) {
  1550. $list[] = $row_bro;
  1551. }
  1552. return $list;
  1553. }
  1554. return [];
  1555. }
  1556. /**
  1557. * Get the specific prefix index terms of this learning path.
  1558. *
  1559. * @param string $prefix
  1560. *
  1561. * @return array Array of terms
  1562. */
  1563. public function get_common_index_terms_by_prefix($prefix)
  1564. {
  1565. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  1566. $terms = get_specific_field_values_list_by_prefix(
  1567. $prefix,
  1568. $this->cc,
  1569. TOOL_LEARNPATH,
  1570. $this->lp_id
  1571. );
  1572. $prefix_terms = [];
  1573. if (!empty($terms)) {
  1574. foreach ($terms as $term) {
  1575. $prefix_terms[] = $term['value'];
  1576. }
  1577. }
  1578. return $prefix_terms;
  1579. }
  1580. /**
  1581. * Gets the number of items currently completed.
  1582. *
  1583. * @param bool $failedStatusException flag to determine the failed status is not considered progressed
  1584. *
  1585. * @return int The number of items currently completed
  1586. */
  1587. public function get_complete_items_count($failedStatusException = false)
  1588. {
  1589. if ($this->debug > 0) {
  1590. error_log('In learnpath::get_complete_items_count()', 0);
  1591. }
  1592. $i = 0;
  1593. $completedStatusList = [
  1594. 'completed',
  1595. 'passed',
  1596. 'succeeded',
  1597. 'browsed',
  1598. ];
  1599. if (!$failedStatusException) {
  1600. $completedStatusList[] = 'failed';
  1601. }
  1602. foreach ($this->items as $id => $dummy) {
  1603. // Trying failed and browsed considered "progressed" as well.
  1604. if ($this->items[$id]->status_is($completedStatusList) &&
  1605. $this->items[$id]->get_type() != 'dir'
  1606. ) {
  1607. $i++;
  1608. }
  1609. }
  1610. return $i;
  1611. }
  1612. /**
  1613. * Gets the current item ID.
  1614. *
  1615. * @return int The current learnpath item id
  1616. */
  1617. public function get_current_item_id()
  1618. {
  1619. $current = 0;
  1620. if ($this->debug > 0) {
  1621. error_log('In learnpath::get_current_item_id()', 0);
  1622. }
  1623. if (!empty($this->current)) {
  1624. $current = $this->current;
  1625. }
  1626. if ($this->debug > 2) {
  1627. error_log('In learnpath::get_current_item_id() - Returning '.$current, 0);
  1628. }
  1629. return $current;
  1630. }
  1631. /**
  1632. * Force to get the first learnpath item id.
  1633. *
  1634. * @return int The current learnpath item id
  1635. */
  1636. public function get_first_item_id()
  1637. {
  1638. $current = 0;
  1639. if (is_array($this->ordered_items)) {
  1640. $current = $this->ordered_items[0];
  1641. }
  1642. return $current;
  1643. }
  1644. /**
  1645. * Gets the total number of items available for viewing in this SCORM.
  1646. *
  1647. * @return int The total number of items
  1648. */
  1649. public function get_total_items_count()
  1650. {
  1651. if ($this->debug > 0) {
  1652. error_log('In learnpath::get_total_items_count()', 0);
  1653. }
  1654. return count($this->items);
  1655. }
  1656. /**
  1657. * Gets the total number of items available for viewing in this SCORM but without chapters.
  1658. *
  1659. * @return int The total no-chapters number of items
  1660. */
  1661. public function getTotalItemsCountWithoutDirs()
  1662. {
  1663. if ($this->debug > 0) {
  1664. error_log('In learnpath::getTotalItemsCountWithoutDirs()', 0);
  1665. }
  1666. $total = 0;
  1667. $typeListNotToCount = self::getChapterTypes();
  1668. foreach ($this->items as $temp2) {
  1669. if (!in_array($temp2->get_type(), $typeListNotToCount)) {
  1670. $total++;
  1671. }
  1672. }
  1673. return $total;
  1674. }
  1675. /**
  1676. * Sets the first element URL.
  1677. */
  1678. public function first()
  1679. {
  1680. if ($this->debug > 0) {
  1681. error_log('In learnpath::first()', 0);
  1682. error_log('$this->last_item_seen '.$this->last_item_seen);
  1683. }
  1684. // Test if the last_item_seen exists and is not a dir.
  1685. if (count($this->ordered_items) == 0) {
  1686. $this->index = 0;
  1687. }
  1688. if (!empty($this->last_item_seen) &&
  1689. !empty($this->items[$this->last_item_seen]) &&
  1690. $this->items[$this->last_item_seen]->get_type() != 'dir'
  1691. //with this change (below) the LP will NOT go to the next item, it will take lp item we left
  1692. //&& !$this->items[$this->last_item_seen]->is_done()
  1693. ) {
  1694. if ($this->debug > 2) {
  1695. error_log(
  1696. 'In learnpath::first() - Last item seen is '.$this->last_item_seen.' of type '.
  1697. $this->items[$this->last_item_seen]->get_type()
  1698. );
  1699. }
  1700. $index = -1;
  1701. foreach ($this->ordered_items as $myindex => $item_id) {
  1702. if ($item_id == $this->last_item_seen) {
  1703. $index = $myindex;
  1704. break;
  1705. }
  1706. }
  1707. if ($index == -1) {
  1708. // Index hasn't changed, so item not found - panic (this shouldn't happen).
  1709. if ($this->debug > 2) {
  1710. error_log('Last item ('.$this->last_item_seen.') was found in items but not in ordered_items, panic!', 0);
  1711. }
  1712. return false;
  1713. } else {
  1714. $this->last = $this->last_item_seen;
  1715. $this->current = $this->last_item_seen;
  1716. $this->index = $index;
  1717. }
  1718. } else {
  1719. if ($this->debug > 2) {
  1720. error_log('In learnpath::first() - No last item seen', 0);
  1721. }
  1722. $index = 0;
  1723. // Loop through all ordered items and stop at the first item that is
  1724. // not a directory *and* that has not been completed yet.
  1725. while (!empty($this->ordered_items[$index]) &&
  1726. is_a($this->items[$this->ordered_items[$index]], 'learnpathItem') &&
  1727. (
  1728. $this->items[$this->ordered_items[$index]]->get_type() == 'dir' ||
  1729. $this->items[$this->ordered_items[$index]]->is_done() === true
  1730. ) && $index < $this->max_ordered_items) {
  1731. $index++;
  1732. }
  1733. $this->last = $this->current;
  1734. // current is
  1735. $this->current = isset($this->ordered_items[$index]) ? $this->ordered_items[$index] : null;
  1736. $this->index = $index;
  1737. if ($this->debug > 2) {
  1738. error_log('$index '.$index);
  1739. error_log('In learnpath::first() - No last item seen');
  1740. error_log('New last = '.$this->last.'('.$this->ordered_items[$index].')');
  1741. }
  1742. }
  1743. if ($this->debug > 2) {
  1744. error_log('In learnpath::first() - First item is '.$this->get_current_item_id());
  1745. }
  1746. }
  1747. /**
  1748. * Gets the information about an item in a format usable as JavaScript to update
  1749. * the JS API by just printing this content into the <head> section of the message frame.
  1750. *
  1751. * @param int $item_id
  1752. *
  1753. * @return string
  1754. */
  1755. public function get_js_info($item_id = 0)
  1756. {
  1757. if ($this->debug > 0) {
  1758. error_log('In learnpath::get_js_info('.$item_id.')', 0);
  1759. }
  1760. $info = '';
  1761. $item_id = intval($item_id);
  1762. if (!empty($item_id) && is_object($this->items[$item_id])) {
  1763. //if item is defined, return values from DB
  1764. $oItem = $this->items[$item_id];
  1765. $info .= '<script language="javascript">';
  1766. $info .= "top.set_score(".$oItem->get_score().");\n";
  1767. $info .= "top.set_max(".$oItem->get_max().");\n";
  1768. $info .= "top.set_min(".$oItem->get_min().");\n";
  1769. $info .= "top.set_lesson_status('".$oItem->get_status()."');";
  1770. $info .= "top.set_session_time('".$oItem->get_scorm_time('js')."');";
  1771. $info .= "top.set_suspend_data('".$oItem->get_suspend_data()."');";
  1772. $info .= "top.set_saved_lesson_status('".$oItem->get_status()."');";
  1773. $info .= "top.set_flag_synchronized();";
  1774. $info .= '</script>';
  1775. if ($this->debug > 2) {
  1776. error_log('in learnpath::get_js_info('.$item_id.') - returning: '.$info, 0);
  1777. }
  1778. return $info;
  1779. } else {
  1780. // If item_id is empty, just update to default SCORM data.
  1781. $info .= '<script language="javascript">';
  1782. $info .= "top.set_score(".learnpathItem::get_score().");\n";
  1783. $info .= "top.set_max(".learnpathItem::get_max().");\n";
  1784. $info .= "top.set_min(".learnpathItem::get_min().");\n";
  1785. $info .= "top.set_lesson_status('".learnpathItem::get_status()."');";
  1786. $info .= "top.set_session_time('".learnpathItem::getScormTimeFromParameter('js')."');";
  1787. $info .= "top.set_suspend_data('".learnpathItem::get_suspend_data()."');";
  1788. $info .= "top.set_saved_lesson_status('".learnpathItem::get_status()."');";
  1789. $info .= "top.set_flag_synchronized();";
  1790. $info .= '</script>';
  1791. if ($this->debug > 2) {
  1792. error_log('in learnpath::get_js_info('.$item_id.') - returning: '.$info, 0);
  1793. }
  1794. return $info;
  1795. }
  1796. }
  1797. /**
  1798. * Gets the js library from the database.
  1799. *
  1800. * @return string The name of the javascript library to be used
  1801. */
  1802. public function get_js_lib()
  1803. {
  1804. $lib = '';
  1805. if (!empty($this->js_lib)) {
  1806. $lib = $this->js_lib;
  1807. }
  1808. return $lib;
  1809. }
  1810. /**
  1811. * Gets the learnpath database ID.
  1812. *
  1813. * @return int Learnpath ID in the lp table
  1814. */
  1815. public function get_id()
  1816. {
  1817. if (!empty($this->lp_id)) {
  1818. return $this->lp_id;
  1819. } else {
  1820. return 0;
  1821. }
  1822. }
  1823. /**
  1824. * Gets the last element URL.
  1825. *
  1826. * @return string URL to load into the viewer
  1827. */
  1828. public function get_last()
  1829. {
  1830. if ($this->debug > 0) {
  1831. error_log('In learnpath::get_last()', 0);
  1832. }
  1833. //This is just in case the lesson doesn't cointain a valid scheme, just to avoid "Notices"
  1834. if (count($this->ordered_items) > 0) {
  1835. $this->index = count($this->ordered_items) - 1;
  1836. return $this->ordered_items[$this->index];
  1837. }
  1838. return false;
  1839. }
  1840. /**
  1841. * Get the last element in the first level.
  1842. * Unlike learnpath::get_last this function doesn't consider the subsection' elements.
  1843. *
  1844. * @return mixed
  1845. */
  1846. public function getLastInFirstLevel()
  1847. {
  1848. try {
  1849. $lastId = Database::getManager()
  1850. ->createQuery('SELECT i.iid FROM ChamiloCourseBundle:CLpItem i
  1851. WHERE i.lpId = :lp AND i.parentItemId = 0 AND i.itemType != :type ORDER BY i.displayOrder DESC')
  1852. ->setMaxResults(1)
  1853. ->setParameters(['lp' => $this->lp_id, 'type' => TOOL_LP_FINAL_ITEM])
  1854. ->getSingleScalarResult();
  1855. return $lastId;
  1856. } catch (Exception $exception) {
  1857. return 0;
  1858. }
  1859. }
  1860. /**
  1861. * Gets the navigation bar for the learnpath display screen.
  1862. *
  1863. * @return string The HTML string to use as a navigation bar
  1864. */
  1865. public function get_navigation_bar($idBar = null, $display = null)
  1866. {
  1867. if ($this->debug > 0) {
  1868. error_log('In learnpath::get_navigation_bar()', 0);
  1869. }
  1870. if (empty($idBar)) {
  1871. $idBar = 'control-top';
  1872. }
  1873. $lpId = $this->lp_id;
  1874. $mycurrentitemid = $this->get_current_item_id();
  1875. $reportingText = get_lang('Reporting');
  1876. $previousText = get_lang('ScormPrevious');
  1877. $nextText = get_lang('ScormNext');
  1878. $fullScreenText = get_lang('ScormExitFullScreen');
  1879. $settings = api_get_configuration_value('lp_view_settings');
  1880. $display = isset($settings['display']) ? $settings['display'] : false;
  1881. $reportingIcon = '
  1882. <a class="icon-toolbar"
  1883. id="stats_link"
  1884. href="lp_controller.php?action=stats&'.api_get_cidreq(true).'&lp_id='.$lpId.'"
  1885. onclick="window.parent.API.save_asset(); return true;"
  1886. target="content_name" title="'.$reportingText.'">
  1887. <span class="fa fa-info"></span><span class="sr-only">'.$reportingText.'</span>
  1888. </a>';
  1889. if (!empty($display)) {
  1890. $showReporting = isset($display['show_reporting_icon']) ? $display['show_reporting_icon'] : true;
  1891. if ($showReporting == false) {
  1892. $reportingIcon = '';
  1893. }
  1894. }
  1895. $hideArrows = false;
  1896. if (isset($settings['display']) && isset($settings['display']['hide_lp_arrow_navigation'])) {
  1897. $hideArrows = $settings['display']['hide_lp_arrow_navigation'];
  1898. }
  1899. $previousIcon = '';
  1900. $nextIcon = '';
  1901. if ($hideArrows === false) {
  1902. $previousIcon = '
  1903. <a class="icon-toolbar" id="scorm-previous" href="#"
  1904. onclick="switch_item('.$mycurrentitemid.',\'previous\');return false;" title="'.$previousText.'">
  1905. <span class="fa fa-chevron-left"></span><span class="sr-only">'.$previousText.'</span>
  1906. </a>';
  1907. $nextIcon = '
  1908. <a class="icon-toolbar" id="scorm-next" href="#"
  1909. onclick="switch_item('.$mycurrentitemid.',\'next\');return false;" title="'.$nextText.'">
  1910. <span class="fa fa-chevron-right"></span><span class="sr-only">'.$nextText.'</span>
  1911. </a>';
  1912. }
  1913. if ($this->mode === 'fullscreen') {
  1914. $navbar = '
  1915. <span id="'.$idBar.'" class="buttons">
  1916. '.$reportingIcon.'
  1917. '.$previousIcon.'
  1918. '.$nextIcon.'
  1919. <a class="icon-toolbar" id="view-embedded"
  1920. href="lp_controller.php?action=mode&mode=embedded" target="_top" title="'.$fullScreenText.'">
  1921. <span class="fa fa-columns"></span><span class="sr-only">'.$fullScreenText.'</span>
  1922. </a>
  1923. </span>';
  1924. } else {
  1925. $navbar = '
  1926. <span id="'.$idBar.'" class="buttons text-right">
  1927. '.$reportingIcon.'
  1928. '.$previousIcon.'
  1929. '.$nextIcon.'
  1930. </span>';
  1931. }
  1932. return $navbar;
  1933. }
  1934. /**
  1935. * Gets the next resource in queue (url).
  1936. *
  1937. * @return string URL to load into the viewer
  1938. */
  1939. public function get_next_index()
  1940. {
  1941. if ($this->debug > 0) {
  1942. error_log('In learnpath::get_next_index()', 0);
  1943. }
  1944. // TODO
  1945. $index = $this->index;
  1946. $index++;
  1947. if ($this->debug > 2) {
  1948. error_log('Now looking at ordered_items['.($index).'] - type is '.$this->items[$this->ordered_items[$index]]->type, 0);
  1949. }
  1950. while (
  1951. !empty($this->ordered_items[$index]) && ($this->items[$this->ordered_items[$index]]->get_type() == 'dir') &&
  1952. $index < $this->max_ordered_items
  1953. ) {
  1954. $index++;
  1955. if ($index == $this->max_ordered_items) {
  1956. if ($this->items[$this->ordered_items[$index]]->get_type() == 'dir') {
  1957. return $this->index;
  1958. } else {
  1959. return $index;
  1960. }
  1961. }
  1962. }
  1963. if (empty($this->ordered_items[$index])) {
  1964. return $this->index;
  1965. }
  1966. if ($this->debug > 2) {
  1967. error_log('index is now '.$index, 0);
  1968. }
  1969. return $index;
  1970. }
  1971. /**
  1972. * Gets item_id for the next element.
  1973. *
  1974. * @return int Next item (DB) ID
  1975. */
  1976. public function get_next_item_id()
  1977. {
  1978. if ($this->debug > 0) {
  1979. error_log('In learnpath::get_next_item_id()', 0);
  1980. }
  1981. $new_index = $this->get_next_index();
  1982. if (!empty($new_index)) {
  1983. if (isset($this->ordered_items[$new_index])) {
  1984. if ($this->debug > 2) {
  1985. error_log('In learnpath::get_next_index() - Returning '.$this->ordered_items[$new_index], 0);
  1986. }
  1987. return $this->ordered_items[$new_index];
  1988. }
  1989. }
  1990. if ($this->debug > 2) {
  1991. error_log('In learnpath::get_next_index() - Problem - Returning 0', 0);
  1992. }
  1993. return 0;
  1994. }
  1995. /**
  1996. * Returns the package type ('scorm','aicc','scorm2004','dokeos','ppt'...).
  1997. *
  1998. * Generally, the package provided is in the form of a zip file, so the function
  1999. * has been written to test a zip file. If not a zip, the function will return the
  2000. * default return value: ''
  2001. *
  2002. * @param string $file_path the path to the file
  2003. * @param string $file_name the original name of the file
  2004. *
  2005. * @return string 'scorm','aicc','scorm2004','dokeos' or '' if the package cannot be recognized
  2006. */
  2007. public static function get_package_type($file_path, $file_name)
  2008. {
  2009. // Get name of the zip file without the extension.
  2010. $file_info = pathinfo($file_name);
  2011. $extension = $file_info['extension']; // Extension only.
  2012. if (!empty($_POST['ppt2lp']) && !in_array(strtolower($extension), [
  2013. 'dll',
  2014. 'exe',
  2015. ])) {
  2016. return 'oogie';
  2017. }
  2018. if (!empty($_POST['woogie']) && !in_array(strtolower($extension), [
  2019. 'dll',
  2020. 'exe',
  2021. ])) {
  2022. return 'woogie';
  2023. }
  2024. $zipFile = new PclZip($file_path);
  2025. // Check the zip content (real size and file extension).
  2026. $zipContentArray = $zipFile->listContent();
  2027. $package_type = '';
  2028. $manifest = '';
  2029. $aicc_match_crs = 0;
  2030. $aicc_match_au = 0;
  2031. $aicc_match_des = 0;
  2032. $aicc_match_cst = 0;
  2033. // The following loop should be stopped as soon as we found the right imsmanifest.xml (how to recognize it?).
  2034. if (is_array($zipContentArray) && count($zipContentArray) > 0) {
  2035. foreach ($zipContentArray as $thisContent) {
  2036. if (preg_match('~.(php.*|phtml)$~i', $thisContent['filename'])) {
  2037. // New behaviour: Don't do anything. These files will be removed in scorm::import_package.
  2038. } elseif (stristr($thisContent['filename'], 'imsmanifest.xml') !== false) {
  2039. $manifest = $thisContent['filename']; // Just the relative directory inside scorm/
  2040. $package_type = 'scorm';
  2041. break; // Exit the foreach loop.
  2042. } elseif (
  2043. preg_match('/aicc\//i', $thisContent['filename']) ||
  2044. in_array(
  2045. strtolower(pathinfo($thisContent['filename'], PATHINFO_EXTENSION)),
  2046. ['crs', 'au', 'des', 'cst']
  2047. )
  2048. ) {
  2049. $ext = strtolower(pathinfo($thisContent['filename'], PATHINFO_EXTENSION));
  2050. switch ($ext) {
  2051. case 'crs':
  2052. $aicc_match_crs = 1;
  2053. break;
  2054. case 'au':
  2055. $aicc_match_au = 1;
  2056. break;
  2057. case 'des':
  2058. $aicc_match_des = 1;
  2059. break;
  2060. case 'cst':
  2061. $aicc_match_cst = 1;
  2062. break;
  2063. default:
  2064. break;
  2065. }
  2066. //break; // Don't exit the loop, because if we find an imsmanifest afterwards, we want it, not the AICC.
  2067. } else {
  2068. $package_type = '';
  2069. }
  2070. }
  2071. }
  2072. if (empty($package_type) && 4 == ($aicc_match_crs + $aicc_match_au + $aicc_match_des + $aicc_match_cst)) {
  2073. // If found an aicc directory... (!= false means it cannot be false (error) or 0 (no match)).
  2074. $package_type = 'aicc';
  2075. }
  2076. // Try with chamilo course builder
  2077. if (empty($package_type)) {
  2078. $package_type = 'chamilo';
  2079. }
  2080. return $package_type;
  2081. }
  2082. /**
  2083. * Gets the previous resource in queue (url). Also initialises time values for this viewing.
  2084. *
  2085. * @return string URL to load into the viewer
  2086. */
  2087. public function get_previous_index()
  2088. {
  2089. if ($this->debug > 0) {
  2090. error_log('In learnpath::get_previous_index()', 0);
  2091. }
  2092. $index = $this->index;
  2093. if (isset($this->ordered_items[$index - 1])) {
  2094. $index--;
  2095. while (isset($this->ordered_items[$index]) &&
  2096. ($this->items[$this->ordered_items[$index]]->get_type() == 'dir')
  2097. ) {
  2098. $index--;
  2099. if ($index < 0) {
  2100. return $this->index;
  2101. }
  2102. }
  2103. } else {
  2104. if ($this->debug > 2) {
  2105. error_log('get_previous_index() - there was no previous index available, reusing '.$index, 0);
  2106. }
  2107. // There is no previous item.
  2108. }
  2109. return $index;
  2110. }
  2111. /**
  2112. * Gets item_id for the next element.
  2113. *
  2114. * @return int Previous item (DB) ID
  2115. */
  2116. public function get_previous_item_id()
  2117. {
  2118. if ($this->debug > 0) {
  2119. error_log('In learnpath::get_previous_item_id()', 0);
  2120. }
  2121. $new_index = $this->get_previous_index();
  2122. return $this->ordered_items[$new_index];
  2123. }
  2124. /**
  2125. * Returns the HTML necessary to print a mediaplayer block inside a page.
  2126. *
  2127. * @param int $lpItemId
  2128. * @param string $autostart
  2129. *
  2130. * @return string The mediaplayer HTML
  2131. */
  2132. public function get_mediaplayer($lpItemId, $autostart = 'true')
  2133. {
  2134. $course_id = api_get_course_int_id();
  2135. $_course = api_get_course_info();
  2136. if (empty($_course)) {
  2137. return '';
  2138. }
  2139. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  2140. $tbl_lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  2141. $lpItemId = (int) $lpItemId;
  2142. /** @var learnpathItem $item */
  2143. $item = isset($this->items[$lpItemId]) ? $this->items[$lpItemId] : null;
  2144. $itemViewId = 0;
  2145. if ($item) {
  2146. $itemViewId = (int) $item->db_item_view_id;
  2147. }
  2148. // Getting all the information about the item.
  2149. $sql = "SELECT lpi.audio, lpi.item_type, lp_view.status
  2150. FROM $tbl_lp_item as lpi
  2151. INNER JOIN $tbl_lp_item_view as lp_view
  2152. ON (lpi.iid = lp_view.lp_item_id)
  2153. WHERE
  2154. lp_view.iid = $itemViewId AND
  2155. lpi.iid = $lpItemId AND
  2156. lp_view.c_id = $course_id";
  2157. $result = Database::query($sql);
  2158. $row = Database::fetch_assoc($result);
  2159. $output = '';
  2160. if (!empty($row['audio'])) {
  2161. $list = $_SESSION['oLP']->get_toc();
  2162. switch ($row['item_type']) {
  2163. case 'quiz':
  2164. $type_quiz = false;
  2165. foreach ($list as $toc) {
  2166. if ($toc['id'] == $_SESSION['oLP']->current) {
  2167. $type_quiz = true;
  2168. }
  2169. }
  2170. if ($type_quiz) {
  2171. if ($_SESSION['oLP']->prevent_reinit == 1) {
  2172. $autostart_audio = $row['status'] === 'completed' ? 'false' : 'true';
  2173. } else {
  2174. $autostart_audio = $autostart;
  2175. }
  2176. }
  2177. break;
  2178. case TOOL_READOUT_TEXT:;
  2179. $autostart_audio = 'false';
  2180. break;
  2181. default:
  2182. $autostart_audio = 'true';
  2183. }
  2184. $courseInfo = api_get_course_info();
  2185. $audio = $row['audio'];
  2186. $file = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/audio/'.$audio;
  2187. $url = api_get_path(WEB_COURSE_PATH).$courseInfo['path'].'/document/audio/'.$audio.'?'.api_get_cidreq();
  2188. if (!file_exists($file)) {
  2189. $lpPathInfo = $_SESSION['oLP']->generate_lp_folder(api_get_course_info());
  2190. $file = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.$lpPathInfo['dir'].$audio;
  2191. $url = api_get_path(WEB_COURSE_PATH).$_course['path'].'/document'.$lpPathInfo['dir'].$audio.'?'.api_get_cidreq();
  2192. }
  2193. $player = Display::getMediaPlayer(
  2194. $file,
  2195. [
  2196. 'id' => 'lp_audio_media_player',
  2197. 'url' => $url,
  2198. 'autoplay' => $autostart_audio,
  2199. 'width' => '100%',
  2200. ]
  2201. );
  2202. // The mp3 player.
  2203. $output = '<div id="container">';
  2204. $output .= $player;
  2205. $output .= '</div>';
  2206. }
  2207. return $output;
  2208. }
  2209. /**
  2210. * @param int $studentId
  2211. * @param int $prerequisite
  2212. * @param array $courseInfo
  2213. * @param int $sessionId
  2214. *
  2215. * @return bool
  2216. */
  2217. public static function isBlockedByPrerequisite(
  2218. $studentId,
  2219. $prerequisite,
  2220. $courseInfo,
  2221. $sessionId
  2222. ) {
  2223. if (empty($courseInfo)) {
  2224. return false;
  2225. }
  2226. $courseId = $courseInfo['real_id'];
  2227. $allow = api_get_configuration_value('allow_teachers_to_access_blocked_lp_by_prerequisite');
  2228. if ($allow) {
  2229. if (api_is_allowed_to_edit() ||
  2230. api_is_platform_admin(true) ||
  2231. api_is_drh() ||
  2232. api_is_coach($sessionId, $courseId, false)
  2233. ) {
  2234. return false;
  2235. }
  2236. }
  2237. $isBlocked = false;
  2238. if (!empty($prerequisite)) {
  2239. $progress = self::getProgress(
  2240. $prerequisite,
  2241. $studentId,
  2242. $courseId,
  2243. $sessionId
  2244. );
  2245. if ($progress < 100) {
  2246. $isBlocked = true;
  2247. }
  2248. if (Tracking::minimunTimeAvailable($sessionId, $courseId)) {
  2249. // Block if it does not exceed minimum time
  2250. // Minimum time (in minutes) to pass the learning path
  2251. $accumulateWorkTime = self::getAccumulateWorkTimePrerequisite($prerequisite, $courseId);
  2252. if ($accumulateWorkTime > 0) {
  2253. // Total time in course (sum of times in learning paths from course)
  2254. $accumulateWorkTimeTotal = self::getAccumulateWorkTimeTotal($courseId);
  2255. // Connect with the plugin_licences_course_session table
  2256. // which indicates what percentage of the time applies
  2257. // Minimum connection percentage
  2258. $perc = 100;
  2259. // Time from the course
  2260. $tc = $accumulateWorkTimeTotal;
  2261. // Percentage of the learning paths
  2262. $pl = $accumulateWorkTime / $accumulateWorkTimeTotal;
  2263. // Minimum time for each learning path
  2264. $accumulateWorkTime = ($pl * $tc * $perc / 100);
  2265. // Spent time (in seconds) so far in the learning path
  2266. $lpTimeList = Tracking::getCalculateTime($studentId, $courseId, $sessionId);
  2267. $lpTime = isset($lpTimeList[TOOL_LEARNPATH][$prerequisite]) ? $lpTimeList[TOOL_LEARNPATH][$prerequisite] : 0;
  2268. if ($lpTime < ($accumulateWorkTime * 60)) {
  2269. $isBlocked = true;
  2270. }
  2271. }
  2272. }
  2273. }
  2274. return $isBlocked;
  2275. }
  2276. /**
  2277. * Checks if the learning path is visible for student after the progress
  2278. * of its prerequisite is completed, considering the time availability and
  2279. * the LP visibility.
  2280. *
  2281. * @param int $lp_id
  2282. * @param int $student_id
  2283. * @param null $courseCode
  2284. * @param int $sessionId
  2285. *
  2286. * @return bool
  2287. */
  2288. public static function is_lp_visible_for_student(
  2289. $lp_id,
  2290. $student_id,
  2291. $courseCode = null,
  2292. $sessionId = 0
  2293. ) {
  2294. $courseInfo = api_get_course_info($courseCode);
  2295. $lp_id = (int) $lp_id;
  2296. $sessionId = (int) $sessionId;
  2297. if (empty($courseInfo)) {
  2298. return false;
  2299. }
  2300. if (empty($sessionId)) {
  2301. $sessionId = api_get_session_id();
  2302. }
  2303. $itemInfo = api_get_item_property_info(
  2304. $courseInfo['real_id'],
  2305. TOOL_LEARNPATH,
  2306. $lp_id,
  2307. $sessionId
  2308. );
  2309. // If the item was deleted.
  2310. if (isset($itemInfo['visibility']) && $itemInfo['visibility'] == 2) {
  2311. return false;
  2312. }
  2313. // @todo remove this query and load the row info as a parameter
  2314. $table = Database::get_course_table(TABLE_LP_MAIN);
  2315. // Get current prerequisite
  2316. $sql = "SELECT id, prerequisite, subscribe_users, publicated_on, expired_on
  2317. FROM $table
  2318. WHERE iid = $lp_id";
  2319. $rs = Database::query($sql);
  2320. $now = time();
  2321. if (Database::num_rows($rs) > 0) {
  2322. $row = Database::fetch_array($rs, 'ASSOC');
  2323. $prerequisite = $row['prerequisite'];
  2324. $is_visible = true;
  2325. $isBlocked = self::isBlockedByPrerequisite(
  2326. $student_id,
  2327. $prerequisite,
  2328. $courseInfo,
  2329. $sessionId
  2330. );
  2331. if ($isBlocked) {
  2332. $is_visible = false;
  2333. }
  2334. // Also check the time availability of the LP
  2335. if ($is_visible) {
  2336. // Adding visibility restrictions
  2337. if (!empty($row['publicated_on'])) {
  2338. if ($now < api_strtotime($row['publicated_on'], 'UTC')) {
  2339. $is_visible = false;
  2340. }
  2341. }
  2342. // Blocking empty start times see BT#2800
  2343. global $_custom;
  2344. if (isset($_custom['lps_hidden_when_no_start_date']) &&
  2345. $_custom['lps_hidden_when_no_start_date']
  2346. ) {
  2347. if (empty($row['publicated_on'])) {
  2348. $is_visible = false;
  2349. }
  2350. }
  2351. if (!empty($row['expired_on'])) {
  2352. if ($now > api_strtotime($row['expired_on'], 'UTC')) {
  2353. $is_visible = false;
  2354. }
  2355. }
  2356. }
  2357. if ($is_visible) {
  2358. $subscriptionSettings = self::getSubscriptionSettings();
  2359. // Check if the subscription users/group to a LP is ON
  2360. if (isset($row['subscribe_users']) && $row['subscribe_users'] == 1 &&
  2361. $subscriptionSettings['allow_add_users_to_lp'] === true
  2362. ) {
  2363. // Try group
  2364. $is_visible = false;
  2365. // Checking only the user visibility
  2366. $userVisibility = api_get_item_visibility(
  2367. $courseInfo,
  2368. 'learnpath',
  2369. $row['id'],
  2370. $sessionId,
  2371. $student_id,
  2372. 'LearnpathSubscription'
  2373. );
  2374. if ($userVisibility == 1) {
  2375. $is_visible = true;
  2376. } else {
  2377. $userGroups = GroupManager::getAllGroupPerUserSubscription($student_id);
  2378. if (!empty($userGroups)) {
  2379. foreach ($userGroups as $groupInfo) {
  2380. $groupId = $groupInfo['iid'];
  2381. $userVisibility = api_get_item_visibility(
  2382. $courseInfo,
  2383. 'learnpath',
  2384. $row['id'],
  2385. $sessionId,
  2386. null,
  2387. 'LearnpathSubscription',
  2388. $groupId
  2389. );
  2390. if ($userVisibility == 1) {
  2391. $is_visible = true;
  2392. break;
  2393. }
  2394. }
  2395. }
  2396. }
  2397. }
  2398. }
  2399. return $is_visible;
  2400. }
  2401. return false;
  2402. }
  2403. /**
  2404. * @param int $lpId
  2405. * @param int $userId
  2406. * @param int $courseId
  2407. * @param int $sessionId
  2408. *
  2409. * @return int
  2410. */
  2411. public static function getProgress($lpId, $userId, $courseId, $sessionId = 0)
  2412. {
  2413. $lpId = (int) $lpId;
  2414. $userId = (int) $userId;
  2415. $courseId = (int) $courseId;
  2416. $sessionId = (int) $sessionId;
  2417. $sessionCondition = api_get_session_condition($sessionId);
  2418. $table = Database::get_course_table(TABLE_LP_VIEW);
  2419. $sql = "SELECT * FROM $table
  2420. WHERE
  2421. c_id = $courseId AND
  2422. lp_id = $lpId AND
  2423. user_id = $userId $sessionCondition ";
  2424. $res = Database::query($sql);
  2425. $progress = 0;
  2426. if (Database::num_rows($res) > 0) {
  2427. $row = Database:: fetch_array($res);
  2428. $progress = (int) $row['progress'];
  2429. }
  2430. return $progress;
  2431. }
  2432. /**
  2433. * Displays a progress bar
  2434. * completed so far.
  2435. *
  2436. * @param int $percentage Progress value to display
  2437. * @param string $text_add Text to display near the progress value
  2438. *
  2439. * @return string HTML string containing the progress bar
  2440. */
  2441. public static function get_progress_bar($percentage = -1, $text_add = '')
  2442. {
  2443. $text = $percentage.$text_add;
  2444. $output = '<div class="progress">
  2445. <div id="progress_bar_value"
  2446. class="progress-bar progress-bar-success" role="progressbar"
  2447. aria-valuenow="'.$percentage.'" aria-valuemin="0" aria-valuemax="100" style="width: '.$text.';">
  2448. '.$text.'
  2449. </div>
  2450. </div>';
  2451. return $output;
  2452. }
  2453. /**
  2454. * @param string $mode can be '%' or 'abs'
  2455. * otherwise this value will be used $this->progress_bar_mode
  2456. *
  2457. * @return string
  2458. */
  2459. public function getProgressBar($mode = null)
  2460. {
  2461. list($percentage, $text_add) = $this->get_progress_bar_text($mode);
  2462. return self::get_progress_bar($percentage, $text_add);
  2463. }
  2464. /**
  2465. * Gets the progress bar info to display inside the progress bar.
  2466. * Also used by scorm_api.php.
  2467. *
  2468. * @param string $mode Mode of display (can be '%' or 'abs').abs means
  2469. * we display a number of completed elements per total elements
  2470. * @param int $add Additional steps to fake as completed
  2471. *
  2472. * @return array Percentage or number and symbol (% or /xx)
  2473. */
  2474. public function get_progress_bar_text($mode = '', $add = 0)
  2475. {
  2476. if ($this->debug > 0) {
  2477. error_log('In learnpath::get_progress_bar_text()', 0);
  2478. }
  2479. if (empty($mode)) {
  2480. $mode = $this->progress_bar_mode;
  2481. }
  2482. $total_items = $this->getTotalItemsCountWithoutDirs();
  2483. if ($this->debug > 2) {
  2484. error_log('Total items available in this learnpath: '.$total_items, 0);
  2485. }
  2486. $completeItems = $this->get_complete_items_count();
  2487. if ($this->debug > 2) {
  2488. error_log('Items completed so far: '.$completeItems, 0);
  2489. }
  2490. if ($add != 0) {
  2491. $completeItems += $add;
  2492. if ($this->debug > 2) {
  2493. error_log('Items completed so far (+modifier): '.$completeItems, 0);
  2494. }
  2495. }
  2496. $text = '';
  2497. if ($completeItems > $total_items) {
  2498. $completeItems = $total_items;
  2499. }
  2500. $percentage = 0;
  2501. if ($mode == '%') {
  2502. if ($total_items > 0) {
  2503. $percentage = ((float) $completeItems / (float) $total_items) * 100;
  2504. } else {
  2505. $percentage = 0;
  2506. }
  2507. $percentage = number_format($percentage, 0);
  2508. $text = '%';
  2509. } elseif ($mode == 'abs') {
  2510. $percentage = $completeItems;
  2511. $text = '/'.$total_items;
  2512. }
  2513. return [
  2514. $percentage,
  2515. $text,
  2516. ];
  2517. }
  2518. /**
  2519. * Gets the progress bar mode.
  2520. *
  2521. * @return string The progress bar mode attribute
  2522. */
  2523. public function get_progress_bar_mode()
  2524. {
  2525. if ($this->debug > 0) {
  2526. error_log('In learnpath::get_progress_bar_mode()', 0);
  2527. }
  2528. if (!empty($this->progress_bar_mode)) {
  2529. return $this->progress_bar_mode;
  2530. } else {
  2531. return '%';
  2532. }
  2533. }
  2534. /**
  2535. * Gets the learnpath theme (remote or local).
  2536. *
  2537. * @return string Learnpath theme
  2538. */
  2539. public function get_theme()
  2540. {
  2541. if ($this->debug > 0) {
  2542. error_log('In learnpath::get_theme()', 0);
  2543. }
  2544. if (!empty($this->theme)) {
  2545. return $this->theme;
  2546. } else {
  2547. return '';
  2548. }
  2549. }
  2550. /**
  2551. * Gets the learnpath session id.
  2552. *
  2553. * @return int
  2554. */
  2555. public function get_lp_session_id()
  2556. {
  2557. if ($this->debug > 0) {
  2558. error_log('In learnpath::get_lp_session_id()', 0);
  2559. }
  2560. if (!empty($this->lp_session_id)) {
  2561. return (int) $this->lp_session_id;
  2562. } else {
  2563. return 0;
  2564. }
  2565. }
  2566. /**
  2567. * Gets the learnpath image.
  2568. *
  2569. * @return string Web URL of the LP image
  2570. */
  2571. public function get_preview_image()
  2572. {
  2573. if ($this->debug > 0) {
  2574. error_log('In learnpath::get_preview_image()', 0);
  2575. }
  2576. if (!empty($this->preview_image)) {
  2577. return $this->preview_image;
  2578. } else {
  2579. return '';
  2580. }
  2581. }
  2582. /**
  2583. * @param string $size
  2584. * @param string $path_type
  2585. *
  2586. * @return bool|string
  2587. */
  2588. public function get_preview_image_path($size = null, $path_type = 'web')
  2589. {
  2590. $preview_image = $this->get_preview_image();
  2591. if (isset($preview_image) && !empty($preview_image)) {
  2592. $image_sys_path = api_get_path(SYS_COURSE_PATH).$this->course_info['path'].'/upload/learning_path/images/';
  2593. $image_path = api_get_path(WEB_COURSE_PATH).$this->course_info['path'].'/upload/learning_path/images/';
  2594. if (isset($size)) {
  2595. $info = pathinfo($preview_image);
  2596. $image_custom_size = $info['filename'].'.'.$size.'.'.$info['extension'];
  2597. if (file_exists($image_sys_path.$image_custom_size)) {
  2598. if ($path_type == 'web') {
  2599. return $image_path.$image_custom_size;
  2600. } else {
  2601. return $image_sys_path.$image_custom_size;
  2602. }
  2603. }
  2604. } else {
  2605. if ($path_type == 'web') {
  2606. return $image_path.$preview_image;
  2607. } else {
  2608. return $image_sys_path.$preview_image;
  2609. }
  2610. }
  2611. }
  2612. return false;
  2613. }
  2614. /**
  2615. * Gets the learnpath author.
  2616. *
  2617. * @return string LP's author
  2618. */
  2619. public function get_author()
  2620. {
  2621. if ($this->debug > 0) {
  2622. error_log('In learnpath::get_author()', 0);
  2623. }
  2624. if (!empty($this->author)) {
  2625. return $this->author;
  2626. } else {
  2627. return '';
  2628. }
  2629. }
  2630. /**
  2631. * Gets hide table of contents.
  2632. *
  2633. * @return int
  2634. */
  2635. public function getHideTableOfContents()
  2636. {
  2637. return (int) $this->hide_toc_frame;
  2638. }
  2639. /**
  2640. * Generate a new prerequisites string for a given item. If this item was a sco and
  2641. * its prerequisites were strings (instead of IDs), then transform those strings into
  2642. * IDs, knowing that SCORM IDs are kept in the "ref" field of the lp_item table.
  2643. * Prefix all item IDs that end-up in the prerequisites string by "ITEM_" to use the
  2644. * same rule as the scormExport() method.
  2645. *
  2646. * @param int $item_id Item ID
  2647. *
  2648. * @return string Prerequisites string ready for the export as SCORM
  2649. */
  2650. public function get_scorm_prereq_string($item_id)
  2651. {
  2652. if ($this->debug > 0) {
  2653. error_log('In learnpath::get_scorm_prereq_string()');
  2654. }
  2655. if (!is_object($this->items[$item_id])) {
  2656. return false;
  2657. }
  2658. /** @var learnpathItem $oItem */
  2659. $oItem = $this->items[$item_id];
  2660. $prereq = $oItem->get_prereq_string();
  2661. if (empty($prereq)) {
  2662. return '';
  2663. }
  2664. if (preg_match('/^\d+$/', $prereq) &&
  2665. isset($this->items[$prereq]) &&
  2666. is_object($this->items[$prereq])
  2667. ) {
  2668. // If the prerequisite is a simple integer ID and this ID exists as an item ID,
  2669. // then simply return it (with the ITEM_ prefix).
  2670. //return 'ITEM_' . $prereq;
  2671. return $this->items[$prereq]->ref;
  2672. } else {
  2673. if (isset($this->refs_list[$prereq])) {
  2674. // It's a simple string item from which the ID can be found in the refs list,
  2675. // so we can transform it directly to an ID for export.
  2676. return $this->items[$this->refs_list[$prereq]]->ref;
  2677. } elseif (isset($this->refs_list['ITEM_'.$prereq])) {
  2678. return $this->items[$this->refs_list['ITEM_'.$prereq]]->ref;
  2679. } else {
  2680. // The last case, if it's a complex form, then find all the IDs (SCORM strings)
  2681. // and replace them, one by one, by the internal IDs (chamilo db)
  2682. // TODO: Modify the '*' replacement to replace the multiplier in front of it
  2683. // by a space as well.
  2684. $find = [
  2685. '&',
  2686. '|',
  2687. '~',
  2688. '=',
  2689. '<>',
  2690. '{',
  2691. '}',
  2692. '*',
  2693. '(',
  2694. ')',
  2695. ];
  2696. $replace = [
  2697. ' ',
  2698. ' ',
  2699. ' ',
  2700. ' ',
  2701. ' ',
  2702. ' ',
  2703. ' ',
  2704. ' ',
  2705. ' ',
  2706. ' ',
  2707. ];
  2708. $prereq_mod = str_replace($find, $replace, $prereq);
  2709. $ids = explode(' ', $prereq_mod);
  2710. foreach ($ids as $id) {
  2711. $id = trim($id);
  2712. if (isset($this->refs_list[$id])) {
  2713. $prereq = preg_replace(
  2714. '/[^a-zA-Z_0-9]('.$id.')[^a-zA-Z_0-9]/',
  2715. 'ITEM_'.$this->refs_list[$id],
  2716. $prereq
  2717. );
  2718. }
  2719. }
  2720. return $prereq;
  2721. }
  2722. }
  2723. }
  2724. /**
  2725. * Returns the XML DOM document's node.
  2726. *
  2727. * @param resource $children Reference to a list of objects to search for the given ITEM_*
  2728. * @param string $id The identifier to look for
  2729. *
  2730. * @return mixed The reference to the element found with that identifier. False if not found
  2731. */
  2732. public function get_scorm_xml_node(&$children, $id)
  2733. {
  2734. for ($i = 0; $i < $children->length; $i++) {
  2735. $item_temp = $children->item($i);
  2736. if ($item_temp->nodeName == 'item') {
  2737. if ($item_temp->getAttribute('identifier') == $id) {
  2738. return $item_temp;
  2739. }
  2740. }
  2741. $subchildren = $item_temp->childNodes;
  2742. if ($subchildren && $subchildren->length > 0) {
  2743. $val = $this->get_scorm_xml_node($subchildren, $id);
  2744. if (is_object($val)) {
  2745. return $val;
  2746. }
  2747. }
  2748. }
  2749. return false;
  2750. }
  2751. /**
  2752. * Gets the status list for all LP's items.
  2753. *
  2754. * @return array Array of [index] => [item ID => current status]
  2755. */
  2756. public function get_items_status_list()
  2757. {
  2758. if ($this->debug > 0) {
  2759. error_log('In learnpath::get_items_status_list()', 0);
  2760. }
  2761. $list = [];
  2762. foreach ($this->ordered_items as $item_id) {
  2763. $list[] = [
  2764. $item_id => $this->items[$item_id]->get_status(),
  2765. ];
  2766. }
  2767. return $list;
  2768. }
  2769. /**
  2770. * Return the number of interactions for the given learnpath Item View ID.
  2771. * This method can be used as static.
  2772. *
  2773. * @param int $lp_iv_id Item View ID
  2774. * @param int $course_id course id
  2775. *
  2776. * @return int
  2777. */
  2778. public static function get_interactions_count_from_db($lp_iv_id, $course_id)
  2779. {
  2780. $table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
  2781. $lp_iv_id = (int) $lp_iv_id;
  2782. $course_id = (int) $course_id;
  2783. $sql = "SELECT count(*) FROM $table
  2784. WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id";
  2785. $res = Database::query($sql);
  2786. $num = 0;
  2787. if (Database::num_rows($res)) {
  2788. $row = Database::fetch_array($res);
  2789. $num = $row[0];
  2790. }
  2791. return $num;
  2792. }
  2793. /**
  2794. * Return the interactions as an array for the given lp_iv_id.
  2795. * This method can be used as static.
  2796. *
  2797. * @param int $lp_iv_id Learnpath Item View ID
  2798. *
  2799. * @return array
  2800. *
  2801. * @todo Transcode labels instead of switching to HTML (which requires to know the encoding of the LP)
  2802. */
  2803. public static function get_iv_interactions_array($lp_iv_id, $course_id = 0)
  2804. {
  2805. $course_id = empty($course_id) ? api_get_course_int_id() : (int) $course_id;
  2806. $list = [];
  2807. $table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
  2808. $lp_iv_id = (int) $lp_iv_id;
  2809. if (empty($lp_iv_id) || empty($course_id)) {
  2810. return [];
  2811. }
  2812. $sql = "SELECT * FROM $table
  2813. WHERE c_id = ".$course_id." AND lp_iv_id = $lp_iv_id
  2814. ORDER BY order_id ASC";
  2815. $res = Database::query($sql);
  2816. $num = Database::num_rows($res);
  2817. if ($num > 0) {
  2818. $list[] = [
  2819. 'order_id' => api_htmlentities(get_lang('Order'), ENT_QUOTES),
  2820. 'id' => api_htmlentities(get_lang('InteractionID'), ENT_QUOTES),
  2821. 'type' => api_htmlentities(get_lang('Type'), ENT_QUOTES),
  2822. 'time' => api_htmlentities(get_lang('TimeFinished'), ENT_QUOTES),
  2823. 'correct_responses' => api_htmlentities(get_lang('CorrectAnswers'), ENT_QUOTES),
  2824. 'student_response' => api_htmlentities(get_lang('StudentResponse'), ENT_QUOTES),
  2825. 'result' => api_htmlentities(get_lang('Result'), ENT_QUOTES),
  2826. 'latency' => api_htmlentities(get_lang('LatencyTimeSpent'), ENT_QUOTES),
  2827. 'student_response_formatted' => '',
  2828. ];
  2829. while ($row = Database::fetch_array($res)) {
  2830. $studentResponseFormatted = urldecode($row['student_response']);
  2831. $content_student_response = explode('__|', $studentResponseFormatted);
  2832. if (count($content_student_response) > 0) {
  2833. if (count($content_student_response) >= 3) {
  2834. // Pop the element off the end of array.
  2835. array_pop($content_student_response);
  2836. }
  2837. $studentResponseFormatted = implode(',', $content_student_response);
  2838. }
  2839. $list[] = [
  2840. 'order_id' => $row['order_id'] + 1,
  2841. 'id' => urldecode($row['interaction_id']), //urldecode because they often have %2F or stuff like that
  2842. 'type' => $row['interaction_type'],
  2843. 'time' => $row['completion_time'],
  2844. 'correct_responses' => '', // Hide correct responses from students.
  2845. 'student_response' => $row['student_response'],
  2846. 'result' => $row['result'],
  2847. 'latency' => $row['latency'],
  2848. 'student_response_formatted' => $studentResponseFormatted,
  2849. ];
  2850. }
  2851. }
  2852. return $list;
  2853. }
  2854. /**
  2855. * Return the number of objectives for the given learnpath Item View ID.
  2856. * This method can be used as static.
  2857. *
  2858. * @param int $lp_iv_id Item View ID
  2859. * @param int $course_id Course ID
  2860. *
  2861. * @return int Number of objectives
  2862. */
  2863. public static function get_objectives_count_from_db($lp_iv_id, $course_id)
  2864. {
  2865. $table = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
  2866. $course_id = (int) $course_id;
  2867. $lp_iv_id = (int) $lp_iv_id;
  2868. $sql = "SELECT count(*) FROM $table
  2869. WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id";
  2870. //@todo seems that this always returns 0
  2871. $res = Database::query($sql);
  2872. $num = 0;
  2873. if (Database::num_rows($res)) {
  2874. $row = Database::fetch_array($res);
  2875. $num = $row[0];
  2876. }
  2877. return $num;
  2878. }
  2879. /**
  2880. * Return the objectives as an array for the given lp_iv_id.
  2881. * This method can be used as static.
  2882. *
  2883. * @param int $lpItemViewId Learnpath Item View ID
  2884. * @param int $course_id
  2885. *
  2886. * @return array
  2887. *
  2888. * @todo Translate labels
  2889. */
  2890. public static function get_iv_objectives_array($lpItemViewId = 0, $course_id = 0)
  2891. {
  2892. $course_id = empty($course_id) ? api_get_course_int_id() : (int) $course_id;
  2893. $lpItemViewId = (int) $lpItemViewId;
  2894. if (empty($course_id) || empty($lpItemViewId)) {
  2895. return [];
  2896. }
  2897. $table = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
  2898. $sql = "SELECT * FROM $table
  2899. WHERE c_id = $course_id AND lp_iv_id = $lpItemViewId
  2900. ORDER BY order_id ASC";
  2901. $res = Database::query($sql);
  2902. $num = Database::num_rows($res);
  2903. $list = [];
  2904. if ($num > 0) {
  2905. $list[] = [
  2906. 'order_id' => api_htmlentities(get_lang('Order'), ENT_QUOTES),
  2907. 'objective_id' => api_htmlentities(get_lang('ObjectiveID'), ENT_QUOTES),
  2908. 'score_raw' => api_htmlentities(get_lang('ObjectiveRawScore'), ENT_QUOTES),
  2909. 'score_max' => api_htmlentities(get_lang('ObjectiveMaxScore'), ENT_QUOTES),
  2910. 'score_min' => api_htmlentities(get_lang('ObjectiveMinScore'), ENT_QUOTES),
  2911. 'status' => api_htmlentities(get_lang('ObjectiveStatus'), ENT_QUOTES),
  2912. ];
  2913. while ($row = Database::fetch_array($res)) {
  2914. $list[] = [
  2915. 'order_id' => $row['order_id'] + 1,
  2916. 'objective_id' => urldecode($row['objective_id']), // urldecode() because they often have %2F
  2917. 'score_raw' => $row['score_raw'],
  2918. 'score_max' => $row['score_max'],
  2919. 'score_min' => $row['score_min'],
  2920. 'status' => $row['status'],
  2921. ];
  2922. }
  2923. }
  2924. return $list;
  2925. }
  2926. /**
  2927. * Generate and return the table of contents for this learnpath. The (flat) table returned can be
  2928. * used by get_html_toc() to be ready to display.
  2929. *
  2930. * @return array TOC as a table with 4 elements per row: title, link, status and level
  2931. */
  2932. public function get_toc()
  2933. {
  2934. if ($this->debug > 0) {
  2935. error_log('learnpath::get_toc()', 0);
  2936. }
  2937. $toc = [];
  2938. foreach ($this->ordered_items as $item_id) {
  2939. if ($this->debug > 2) {
  2940. error_log('learnpath::get_toc(): getting info for item '.$item_id, 0);
  2941. }
  2942. // TODO: Change this link generation and use new function instead.
  2943. $toc[] = [
  2944. 'id' => $item_id,
  2945. 'title' => $this->items[$item_id]->get_title(),
  2946. 'status' => $this->items[$item_id]->get_status(),
  2947. 'level' => $this->items[$item_id]->get_level(),
  2948. 'type' => $this->items[$item_id]->get_type(),
  2949. 'description' => $this->items[$item_id]->get_description(),
  2950. 'path' => $this->items[$item_id]->get_path(),
  2951. 'parent' => $this->items[$item_id]->get_parent(),
  2952. ];
  2953. }
  2954. if ($this->debug > 2) {
  2955. error_log('In learnpath::get_toc() - TOC array: '.print_r($toc, true), 0);
  2956. }
  2957. return $toc;
  2958. }
  2959. /**
  2960. * Generate and return the table of contents for this learnpath. The JS
  2961. * table returned is used inside of scorm_api.php.
  2962. *
  2963. * @param string $varname
  2964. *
  2965. * @return string A JS array variable construction
  2966. */
  2967. public function get_items_details_as_js($varname = 'olms.lms_item_types')
  2968. {
  2969. if ($this->debug > 0) {
  2970. error_log('In learnpath::get_items_details_as_js()', 0);
  2971. }
  2972. $toc = $varname.' = new Array();';
  2973. foreach ($this->ordered_items as $item_id) {
  2974. $toc .= $varname."['i$item_id'] = '".$this->items[$item_id]->get_type()."';";
  2975. }
  2976. if ($this->debug > 2) {
  2977. error_log('In learnpath::get_items_details_as_js() - TOC array: '.print_r($toc, true), 0);
  2978. }
  2979. return $toc;
  2980. }
  2981. /**
  2982. * Gets the learning path type.
  2983. *
  2984. * @param bool $get_name Return the name? If false, return the ID. Default is false.
  2985. *
  2986. * @return mixed Type ID or name, depending on the parameter
  2987. */
  2988. public function get_type($get_name = false)
  2989. {
  2990. $res = false;
  2991. if ($this->debug > 0) {
  2992. error_log('In learnpath::get_type()', 0);
  2993. }
  2994. if (!empty($this->type) && (!$get_name)) {
  2995. $res = $this->type;
  2996. }
  2997. if ($this->debug > 2) {
  2998. error_log('In learnpath::get_type() - Returning '.($res ? $res : 'false'), 0);
  2999. }
  3000. return $res;
  3001. }
  3002. /**
  3003. * Gets the learning path type as static method.
  3004. *
  3005. * @param int $lp_id
  3006. *
  3007. * @return mixed Type ID or name, depending on the parameter
  3008. */
  3009. public static function get_type_static($lp_id = 0)
  3010. {
  3011. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  3012. $lp_id = (int) $lp_id;
  3013. $sql = "SELECT lp_type FROM $tbl_lp
  3014. WHERE iid = $lp_id";
  3015. $res = Database::query($sql);
  3016. if ($res === false) {
  3017. return null;
  3018. }
  3019. if (Database::num_rows($res) <= 0) {
  3020. return null;
  3021. }
  3022. $row = Database::fetch_array($res);
  3023. return $row['lp_type'];
  3024. }
  3025. /**
  3026. * Gets a flat list of item IDs ordered for display (level by level ordered by order_display)
  3027. * This method can be used as abstract and is recursive.
  3028. *
  3029. * @param int $lp Learnpath ID
  3030. * @param int $parent Parent ID of the items to look for
  3031. * @param int $course_id
  3032. *
  3033. * @return array Ordered list of item IDs (empty array on error)
  3034. */
  3035. public static function get_flat_ordered_items_list($lp = 1, $parent = 0, $course_id = 0)
  3036. {
  3037. if (empty($course_id)) {
  3038. $course_id = api_get_course_int_id();
  3039. } else {
  3040. $course_id = (int) $course_id;
  3041. }
  3042. $list = [];
  3043. if (empty($lp)) {
  3044. return $list;
  3045. }
  3046. $lp = (int) $lp;
  3047. $parent = (int) $parent;
  3048. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  3049. $sql = "SELECT iid FROM $tbl_lp_item
  3050. WHERE c_id = $course_id AND lp_id = $lp AND parent_item_id = $parent
  3051. ORDER BY display_order";
  3052. $res = Database::query($sql);
  3053. while ($row = Database::fetch_array($res)) {
  3054. $sublist = self::get_flat_ordered_items_list(
  3055. $lp,
  3056. $row['iid'],
  3057. $course_id
  3058. );
  3059. $list[] = $row['iid'];
  3060. foreach ($sublist as $item) {
  3061. $list[] = $item;
  3062. }
  3063. }
  3064. return $list;
  3065. }
  3066. /**
  3067. * @return array
  3068. */
  3069. public static function getChapterTypes()
  3070. {
  3071. return [
  3072. 'dir',
  3073. ];
  3074. }
  3075. /**
  3076. * Uses the table generated by get_toc() and returns an HTML-formattedstring ready to display.
  3077. *
  3078. * @param $tree
  3079. *
  3080. * @return array HTML TOC ready to display
  3081. */
  3082. public function getParentToc($tree)
  3083. {
  3084. if ($this->debug > 0) {
  3085. error_log('In learnpath::get_html_toc()', 0);
  3086. }
  3087. if (empty($tree)) {
  3088. $tree = $this->get_toc();
  3089. }
  3090. $dirTypes = self::getChapterTypes();
  3091. $myCurrentId = $this->get_current_item_id();
  3092. $listParent = [];
  3093. $listChildren = [];
  3094. $listNotParent = [];
  3095. $list = [];
  3096. foreach ($tree as $subtree) {
  3097. if (in_array($subtree['type'], $dirTypes)) {
  3098. $listChildren = $this->getChildrenToc($tree, $subtree['id']);
  3099. $subtree['children'] = $listChildren;
  3100. if (!empty($subtree['children'])) {
  3101. foreach ($subtree['children'] as $subItem) {
  3102. if ($subItem['id'] == $this->current) {
  3103. $subtree['parent_current'] = 'in';
  3104. $subtree['current'] = 'on';
  3105. }
  3106. }
  3107. }
  3108. $listParent[] = $subtree;
  3109. }
  3110. if (!in_array($subtree['type'], $dirTypes) && $subtree['parent'] == null) {
  3111. $classStatus = [
  3112. 'not attempted' => 'scorm_not_attempted',
  3113. 'incomplete' => 'scorm_not_attempted',
  3114. 'failed' => 'scorm_failed',
  3115. 'completed' => 'scorm_completed',
  3116. 'passed' => 'scorm_completed',
  3117. 'succeeded' => 'scorm_completed',
  3118. 'browsed' => 'scorm_completed',
  3119. ];
  3120. if (isset($classStatus[$subtree['status']])) {
  3121. $cssStatus = $classStatus[$subtree['status']];
  3122. }
  3123. $title = Security::remove_XSS($subtree['title']);
  3124. unset($subtree['title']);
  3125. if (empty($title)) {
  3126. $title = self::rl_get_resource_name(api_get_course_id(), $this->get_id(), $subtree['id']);
  3127. }
  3128. $classStyle = null;
  3129. if ($subtree['id'] == $this->current) {
  3130. $classStyle = 'scorm_item_normal '.$classStyle.'scorm_highlight';
  3131. } elseif (!in_array($subtree['type'], $dirTypes)) {
  3132. $classStyle = 'scorm_item_normal '.$classStyle.' ';
  3133. }
  3134. $subtree['title'] = $title;
  3135. $subtree['class'] = $classStyle.' '.$cssStatus;
  3136. $subtree['url'] = $this->get_link('http', $subtree['id'], $tree);
  3137. $subtree['current_id'] = $myCurrentId;
  3138. $listNotParent[] = $subtree;
  3139. }
  3140. }
  3141. $list['are_parents'] = $listParent;
  3142. $list['not_parents'] = $listNotParent;
  3143. return $list;
  3144. }
  3145. /**
  3146. * Uses the table generated by get_toc() and returns an HTML-formattedstring ready to display.
  3147. *
  3148. * @param array $tree
  3149. * @param int $id
  3150. * @param bool $parent
  3151. *
  3152. * @return array HTML TOC ready to display
  3153. */
  3154. public function getChildrenToc($tree, $id, $parent = true)
  3155. {
  3156. if ($this->debug > 0) {
  3157. error_log('In learnpath::get_html_toc()', 0);
  3158. }
  3159. if (empty($tree)) {
  3160. $tree = $this->get_toc();
  3161. }
  3162. $dirTypes = self::getChapterTypes();
  3163. $mycurrentitemid = $this->get_current_item_id();
  3164. $list = [];
  3165. $classStatus = [
  3166. 'not attempted' => 'scorm_not_attempted',
  3167. 'incomplete' => 'scorm_not_attempted',
  3168. 'failed' => 'scorm_failed',
  3169. 'completed' => 'scorm_completed',
  3170. 'passed' => 'scorm_completed',
  3171. 'succeeded' => 'scorm_completed',
  3172. 'browsed' => 'scorm_completed',
  3173. ];
  3174. foreach ($tree as $subtree) {
  3175. $subtree['tree'] = null;
  3176. if (!in_array($subtree['type'], $dirTypes) && $subtree['parent'] == $id) {
  3177. if ($subtree['id'] == $this->current) {
  3178. $subtree['current'] = 'active';
  3179. } else {
  3180. $subtree['current'] = null;
  3181. }
  3182. if (isset($classStatus[$subtree['status']])) {
  3183. $cssStatus = $classStatus[$subtree['status']];
  3184. }
  3185. $title = Security::remove_XSS($subtree['title']);
  3186. unset($subtree['title']);
  3187. if (empty($title)) {
  3188. $title = self::rl_get_resource_name(api_get_course_id(), $this->get_id(), $subtree['id']);
  3189. }
  3190. $classStyle = null;
  3191. if ($subtree['id'] == $this->current) {
  3192. $classStyle = 'scorm_item_normal '.$classStyle.'scorm_highlight';
  3193. } elseif (!in_array($subtree['type'], $dirTypes)) {
  3194. $classStyle = 'scorm_item_normal '.$classStyle.' ';
  3195. }
  3196. if (in_array($subtree['type'], $dirTypes)) {
  3197. $subtree['title'] = stripslashes($title);
  3198. } else {
  3199. $subtree['title'] = $title;
  3200. $subtree['class'] = $classStyle.' '.$cssStatus;
  3201. $subtree['url'] = $this->get_link('http', $subtree['id'], $tree);
  3202. $subtree['current_id'] = $mycurrentitemid;
  3203. }
  3204. $list[] = $subtree;
  3205. }
  3206. }
  3207. return $list;
  3208. }
  3209. /**
  3210. * Uses the table generated by get_toc() and returns an HTML-formatted string ready to display.
  3211. *
  3212. * @param array $toc_list
  3213. *
  3214. * @return array HTML TOC ready to display
  3215. */
  3216. public function getListArrayToc($toc_list = [])
  3217. {
  3218. if ($this->debug > 0) {
  3219. error_log('In learnpath::get_html_toc()', 0);
  3220. }
  3221. if (empty($toc_list)) {
  3222. $toc_list = $this->get_toc();
  3223. }
  3224. // Temporary variables.
  3225. $mycurrentitemid = $this->get_current_item_id();
  3226. $list = [];
  3227. $arrayList = [];
  3228. $classStatus = [
  3229. 'not attempted' => 'scorm_not_attempted',
  3230. 'incomplete' => 'scorm_not_attempted',
  3231. 'failed' => 'scorm_failed',
  3232. 'completed' => 'scorm_completed',
  3233. 'passed' => 'scorm_completed',
  3234. 'succeeded' => 'scorm_completed',
  3235. 'browsed' => 'scorm_completed',
  3236. ];
  3237. foreach ($toc_list as $item) {
  3238. $list['id'] = $item['id'];
  3239. $list['status'] = $item['status'];
  3240. $cssStatus = null;
  3241. if (isset($classStatus[$item['status']])) {
  3242. $cssStatus = $classStatus[$item['status']];
  3243. }
  3244. $classStyle = ' ';
  3245. $dirTypes = self::getChapterTypes();
  3246. if (in_array($item['type'], $dirTypes)) {
  3247. $classStyle = 'scorm_item_section ';
  3248. }
  3249. if ($item['id'] == $this->current) {
  3250. $classStyle = 'scorm_item_normal '.$classStyle.'scorm_highlight';
  3251. } elseif (!in_array($item['type'], $dirTypes)) {
  3252. $classStyle = 'scorm_item_normal '.$classStyle.' ';
  3253. }
  3254. $title = $item['title'];
  3255. if (empty($title)) {
  3256. $title = self::rl_get_resource_name(
  3257. api_get_course_id(),
  3258. $this->get_id(),
  3259. $item['id']
  3260. );
  3261. }
  3262. $title = Security::remove_XSS($item['title']);
  3263. if (empty($item['description'])) {
  3264. $list['description'] = $title;
  3265. } else {
  3266. $list['description'] = $item['description'];
  3267. }
  3268. $list['class'] = $classStyle.' '.$cssStatus;
  3269. $list['level'] = $item['level'];
  3270. $list['type'] = $item['type'];
  3271. if (in_array($item['type'], $dirTypes)) {
  3272. $list['css_level'] = 'level_'.$item['level'];
  3273. } else {
  3274. $list['css_level'] = 'level_'.$item['level'].' scorm_type_'.self::format_scorm_type_item($item['type']);
  3275. }
  3276. if (in_array($item['type'], $dirTypes)) {
  3277. $list['title'] = stripslashes($title);
  3278. } else {
  3279. $list['title'] = stripslashes($title);
  3280. $list['url'] = $this->get_link('http', $item['id'], $toc_list);
  3281. $list['current_id'] = $mycurrentitemid;
  3282. }
  3283. $arrayList[] = $list;
  3284. }
  3285. return $arrayList;
  3286. }
  3287. /**
  3288. * Returns an HTML-formatted string ready to display with teacher buttons
  3289. * in LP view menu.
  3290. *
  3291. * @return string HTML TOC ready to display
  3292. */
  3293. public function get_teacher_toc_buttons()
  3294. {
  3295. $isAllow = api_is_allowed_to_edit(null, true, false, false);
  3296. $hideIcons = api_get_configuration_value('hide_teacher_icons_lp');
  3297. $html = '';
  3298. if ($isAllow && $hideIcons == false) {
  3299. if ($this->get_lp_session_id() == api_get_session_id()) {
  3300. $html .= '<div id="actions_lp" class="actions_lp"><hr>';
  3301. $html .= '<div class="btn-group">';
  3302. $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'>".
  3303. Display::returnFontAwesomeIcon('street-view').get_lang('Overview')."</a>";
  3304. $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'>".
  3305. Display::returnFontAwesomeIcon('pencil').get_lang('Edit')."</a>";
  3306. $html .= '<a class="btn btn-sm btn-default" href="lp_controller.php?'.api_get_cidreq()."&action=edit&lp_id=".$this->lp_id.'&isStudentView=false">'.
  3307. Display::returnFontAwesomeIcon('cog').get_lang('Settings').'</a>';
  3308. $html .= '</div>';
  3309. $html .= '</div>';
  3310. }
  3311. }
  3312. return $html;
  3313. }
  3314. /**
  3315. * Gets the learnpath maker name - generally the editor's name.
  3316. *
  3317. * @return string Learnpath maker name
  3318. */
  3319. public function get_maker()
  3320. {
  3321. if ($this->debug > 0) {
  3322. error_log('In learnpath::get_maker()', 0);
  3323. }
  3324. if (!empty($this->maker)) {
  3325. return $this->maker;
  3326. } else {
  3327. return '';
  3328. }
  3329. }
  3330. /**
  3331. * Gets the learnpath name/title.
  3332. *
  3333. * @return string Learnpath name/title
  3334. */
  3335. public function get_name()
  3336. {
  3337. if ($this->debug > 0) {
  3338. error_log('In learnpath::get_name()', 0);
  3339. }
  3340. if (!empty($this->name)) {
  3341. return $this->name;
  3342. } else {
  3343. return 'N/A';
  3344. }
  3345. }
  3346. /**
  3347. * Gets a link to the resource from the present location, depending on item ID.
  3348. *
  3349. * @param string $type Type of link expected
  3350. * @param int $item_id Learnpath item ID
  3351. * @param bool $provided_toc
  3352. *
  3353. * @return string $provided_toc Link to the lp_item resource
  3354. */
  3355. public function get_link($type = 'http', $item_id = null, $provided_toc = false)
  3356. {
  3357. $course_id = $this->get_course_int_id();
  3358. if ($this->debug > 0) {
  3359. error_log('In learnpath::get_link('.$type.','.$item_id.')', 0);
  3360. }
  3361. if (empty($item_id)) {
  3362. if ($this->debug > 2) {
  3363. error_log('In learnpath::get_link() - no item id given in learnpath::get_link()');
  3364. error_log('using current: '.$this->get_current_item_id(), 0);
  3365. }
  3366. $item_id = $this->get_current_item_id();
  3367. if (empty($item_id)) {
  3368. if ($this->debug > 2) {
  3369. error_log('In learnpath::get_link() - no current item id found in learnpath object', 0);
  3370. }
  3371. //still empty, this means there was no item_id given and we are not in an object context or
  3372. //the object property is empty, return empty link
  3373. $this->first();
  3374. return '';
  3375. }
  3376. }
  3377. $file = '';
  3378. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3379. $lp_item_table = Database::get_course_table(TABLE_LP_ITEM);
  3380. $lp_item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  3381. $item_id = (int) $item_id;
  3382. $sql = "SELECT
  3383. l.lp_type as ltype,
  3384. l.path as lpath,
  3385. li.item_type as litype,
  3386. li.path as lipath,
  3387. li.parameters as liparams
  3388. FROM $lp_table l
  3389. INNER JOIN $lp_item_table li
  3390. ON (li.lp_id = l.iid)
  3391. WHERE
  3392. li.iid = $item_id
  3393. ";
  3394. if ($this->debug > 2) {
  3395. error_log('In learnpath::get_link() - selecting item '.$sql, 0);
  3396. }
  3397. $res = Database::query($sql);
  3398. if (Database::num_rows($res) > 0) {
  3399. $row = Database::fetch_array($res);
  3400. $lp_type = $row['ltype'];
  3401. $lp_path = $row['lpath'];
  3402. $lp_item_type = $row['litype'];
  3403. $lp_item_path = $row['lipath'];
  3404. $lp_item_params = $row['liparams'];
  3405. if (empty($lp_item_params) && strpos($lp_item_path, '?') !== false) {
  3406. list($lp_item_path, $lp_item_params) = explode('?', $lp_item_path);
  3407. }
  3408. $sys_course_path = api_get_path(SYS_COURSE_PATH).api_get_course_path();
  3409. if ($type === 'http') {
  3410. //web path
  3411. $course_path = api_get_path(WEB_COURSE_PATH).api_get_course_path();
  3412. } else {
  3413. $course_path = $sys_course_path; //system path
  3414. }
  3415. // Fixed issue BT#1272 - If the item type is a Chamilo Item (quiz, link, etc),
  3416. // then change the lp type to thread it as a normal Chamilo LP not a SCO.
  3417. if (in_array(
  3418. $lp_item_type,
  3419. ['quiz', 'document', 'final_item', 'link', 'forum', 'thread', 'student_publication']
  3420. )
  3421. ) {
  3422. $lp_type = 1;
  3423. }
  3424. if ($this->debug > 2) {
  3425. error_log('In learnpath::get_link() - $lp_type '.$lp_type, 0);
  3426. error_log('In learnpath::get_link() - $lp_item_type '.$lp_item_type, 0);
  3427. }
  3428. // Now go through the specific cases to get the end of the path
  3429. // @todo Use constants instead of int values.
  3430. switch ($lp_type) {
  3431. case 1:
  3432. $file = self::rl_get_resource_link_for_learnpath(
  3433. $course_id,
  3434. $this->get_id(),
  3435. $item_id,
  3436. $this->get_view_id()
  3437. );
  3438. if ($this->debug > 0) {
  3439. error_log('rl_get_resource_link_for_learnpath - file: '.$file, 0);
  3440. }
  3441. switch ($lp_item_type) {
  3442. case 'document':
  3443. // Shows a button to download the file instead of just downloading the file directly.
  3444. $documentPathInfo = pathinfo($file);
  3445. if (isset($documentPathInfo['extension'])) {
  3446. $parsed = parse_url($documentPathInfo['extension']);
  3447. if (isset($parsed['path'])) {
  3448. $extension = $parsed['path'];
  3449. $extensionsToDownload = [
  3450. 'zip',
  3451. 'ppt',
  3452. 'pptx',
  3453. 'ods',
  3454. 'xlsx',
  3455. 'xls',
  3456. 'csv',
  3457. 'doc',
  3458. 'docx',
  3459. 'dot',
  3460. ];
  3461. if (in_array($extension, $extensionsToDownload)) {
  3462. $file = api_get_path(WEB_CODE_PATH).
  3463. 'lp/embed.php?type=download&source=file&lp_item_id='.$item_id.'&'.api_get_cidreq();
  3464. }
  3465. }
  3466. }
  3467. break;
  3468. case 'dir':
  3469. $file = 'lp_content.php?type=dir';
  3470. break;
  3471. case 'link':
  3472. if (Link::is_youtube_link($file)) {
  3473. $src = Link::get_youtube_video_id($file);
  3474. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=youtube&source='.$src;
  3475. } elseif (Link::isVimeoLink($file)) {
  3476. $src = Link::getVimeoLinkId($file);
  3477. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=vimeo&source='.$src;
  3478. } else {
  3479. // If the current site is HTTPS and the link is
  3480. // HTTP, browsers will refuse opening the link
  3481. $urlId = api_get_current_access_url_id();
  3482. $url = api_get_access_url($urlId, false);
  3483. $protocol = substr($url['url'], 0, 5);
  3484. if ($protocol === 'https') {
  3485. $linkProtocol = substr($file, 0, 5);
  3486. if ($linkProtocol === 'http:') {
  3487. //this is the special intervention case
  3488. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=nonhttps&source='.urlencode($file);
  3489. }
  3490. }
  3491. }
  3492. break;
  3493. case 'quiz':
  3494. // Check how much attempts of a exercise exits in lp
  3495. $lp_item_id = $this->get_current_item_id();
  3496. $lp_view_id = $this->get_view_id();
  3497. $prevent_reinit = null;
  3498. if (isset($this->items[$this->current])) {
  3499. $prevent_reinit = $this->items[$this->current]->get_prevent_reinit();
  3500. }
  3501. if (empty($provided_toc)) {
  3502. if ($this->debug > 0) {
  3503. error_log('In learnpath::get_link() Loading get_toc ', 0);
  3504. }
  3505. $list = $this->get_toc();
  3506. } else {
  3507. if ($this->debug > 0) {
  3508. error_log('In learnpath::get_link() Loading get_toc from "cache" ', 0);
  3509. }
  3510. $list = $provided_toc;
  3511. }
  3512. $type_quiz = false;
  3513. foreach ($list as $toc) {
  3514. if ($toc['id'] == $lp_item_id && $toc['type'] == 'quiz') {
  3515. $type_quiz = true;
  3516. }
  3517. }
  3518. if ($type_quiz) {
  3519. $lp_item_id = (int) $lp_item_id;
  3520. $lp_view_id = (int) $lp_view_id;
  3521. $sql = "SELECT count(*) FROM $lp_item_view_table
  3522. WHERE
  3523. c_id = $course_id AND
  3524. lp_item_id='".$lp_item_id."' AND
  3525. lp_view_id ='".$lp_view_id."' AND
  3526. status='completed'";
  3527. $result = Database::query($sql);
  3528. $row_count = Database:: fetch_row($result);
  3529. $count_item_view = (int) $row_count[0];
  3530. $not_multiple_attempt = 0;
  3531. if ($prevent_reinit === 1 && $count_item_view > 0) {
  3532. $not_multiple_attempt = 1;
  3533. }
  3534. $file .= '&not_multiple_attempt='.$not_multiple_attempt;
  3535. }
  3536. break;
  3537. }
  3538. $tmp_array = explode('/', $file);
  3539. $document_name = $tmp_array[count($tmp_array) - 1];
  3540. if (strpos($document_name, '_DELETED_')) {
  3541. $file = 'blank.php?error=document_deleted';
  3542. }
  3543. break;
  3544. case 2:
  3545. if ($this->debug > 2) {
  3546. error_log('In learnpath::get_link() '.__LINE__.' - Item type: '.$lp_item_type, 0);
  3547. }
  3548. if ($lp_item_type != 'dir') {
  3549. // Quite complex here:
  3550. // We want to make sure 'http://' (and similar) links can
  3551. // be loaded as is (withouth the Chamilo path in front) but
  3552. // some contents use this form: resource.htm?resource=http://blablabla
  3553. // which means we have to find a protocol at the path's start, otherwise
  3554. // it should not be considered as an external URL.
  3555. // if ($this->prerequisites_match($item_id)) {
  3556. if (preg_match('#^[a-zA-Z]{2,5}://#', $lp_item_path) != 0) {
  3557. if ($this->debug > 2) {
  3558. error_log('In learnpath::get_link() '.__LINE__.' - Found match for protocol in '.$lp_item_path, 0);
  3559. }
  3560. // Distant url, return as is.
  3561. $file = $lp_item_path;
  3562. } else {
  3563. if ($this->debug > 2) {
  3564. error_log('In learnpath::get_link() '.__LINE__.' - No starting protocol in '.$lp_item_path, 0);
  3565. }
  3566. // Prevent getting untranslatable urls.
  3567. $lp_item_path = preg_replace('/%2F/', '/', $lp_item_path);
  3568. $lp_item_path = preg_replace('/%3A/', ':', $lp_item_path);
  3569. // Prepare the path.
  3570. $file = $course_path.'/scorm/'.$lp_path.'/'.$lp_item_path;
  3571. // TODO: Fix this for urls with protocol header.
  3572. $file = str_replace('//', '/', $file);
  3573. $file = str_replace(':/', '://', $file);
  3574. if (substr($lp_path, -1) == '/') {
  3575. $lp_path = substr($lp_path, 0, -1);
  3576. }
  3577. if (!is_file(realpath($sys_course_path.'/scorm/'.$lp_path.'/'.$lp_item_path))) {
  3578. // if file not found.
  3579. $decoded = html_entity_decode($lp_item_path);
  3580. list($decoded) = explode('?', $decoded);
  3581. if (!is_file(realpath($sys_course_path.'/scorm/'.$lp_path.'/'.$decoded))) {
  3582. $file = self::rl_get_resource_link_for_learnpath(
  3583. $course_id,
  3584. $this->get_id(),
  3585. $item_id,
  3586. $this->get_view_id()
  3587. );
  3588. if (empty($file)) {
  3589. $file = 'blank.php?error=document_not_found';
  3590. } else {
  3591. $tmp_array = explode('/', $file);
  3592. $document_name = $tmp_array[count($tmp_array) - 1];
  3593. if (strpos($document_name, '_DELETED_')) {
  3594. $file = 'blank.php?error=document_deleted';
  3595. } else {
  3596. $file = 'blank.php?error=document_not_found';
  3597. }
  3598. }
  3599. } else {
  3600. $file = $course_path.'/scorm/'.$lp_path.'/'.$decoded;
  3601. }
  3602. }
  3603. }
  3604. // We want to use parameters if they were defined in the imsmanifest
  3605. if (strpos($file, 'blank.php') === false) {
  3606. $lp_item_params = ltrim($lp_item_params, '?');
  3607. $file .= (strstr($file, '?') === false ? '?' : '').$lp_item_params;
  3608. }
  3609. } else {
  3610. $file = 'lp_content.php?type=dir';
  3611. }
  3612. break;
  3613. case 3:
  3614. if ($this->debug > 2) {
  3615. error_log('In learnpath::get_link() '.__LINE__.' - Item type: '.$lp_item_type, 0);
  3616. }
  3617. // Formatting AICC HACP append URL.
  3618. $aicc_append = '?aicc_sid='.urlencode(session_id()).'&aicc_url='.urlencode(api_get_path(WEB_CODE_PATH).'lp/aicc_hacp.php').'&';
  3619. if (!empty($lp_item_params)) {
  3620. $aicc_append .= $lp_item_params.'&';
  3621. }
  3622. if ($lp_item_type != 'dir') {
  3623. // Quite complex here:
  3624. // We want to make sure 'http://' (and similar) links can
  3625. // be loaded as is (withouth the Chamilo path in front) but
  3626. // some contents use this form: resource.htm?resource=http://blablabla
  3627. // which means we have to find a protocol at the path's start, otherwise
  3628. // it should not be considered as an external URL.
  3629. if (preg_match('#^[a-zA-Z]{2,5}://#', $lp_item_path) != 0) {
  3630. if ($this->debug > 2) {
  3631. error_log('In learnpath::get_link() '.__LINE__.' - Found match for protocol in '.$lp_item_path, 0);
  3632. }
  3633. // Distant url, return as is.
  3634. $file = $lp_item_path;
  3635. // Enabled and modified by Ivan Tcholakov, 16-OCT-2008.
  3636. /*
  3637. if (stristr($file,'<servername>') !== false) {
  3638. $file = str_replace('<servername>', $course_path.'/scorm/'.$lp_path.'/', $lp_item_path);
  3639. }
  3640. */
  3641. if (stripos($file, '<servername>') !== false) {
  3642. //$file = str_replace('<servername>',$course_path.'/scorm/'.$lp_path.'/',$lp_item_path);
  3643. $web_course_path = str_replace('https://', '', str_replace('http://', '', $course_path));
  3644. $file = str_replace('<servername>', $web_course_path.'/scorm/'.$lp_path, $lp_item_path);
  3645. }
  3646. $file .= $aicc_append;
  3647. } else {
  3648. if ($this->debug > 2) {
  3649. error_log('In learnpath::get_link() '.__LINE__.' - No starting protocol in '.$lp_item_path, 0);
  3650. }
  3651. // Prevent getting untranslatable urls.
  3652. $lp_item_path = preg_replace('/%2F/', '/', $lp_item_path);
  3653. $lp_item_path = preg_replace('/%3A/', ':', $lp_item_path);
  3654. // Prepare the path - lp_path might be unusable because it includes the "aicc" subdir name.
  3655. $file = $course_path.'/scorm/'.$lp_path.'/'.$lp_item_path;
  3656. // TODO: Fix this for urls with protocol header.
  3657. $file = str_replace('//', '/', $file);
  3658. $file = str_replace(':/', '://', $file);
  3659. $file .= $aicc_append;
  3660. }
  3661. } else {
  3662. $file = 'lp_content.php?type=dir';
  3663. }
  3664. break;
  3665. case 4:
  3666. break;
  3667. default:
  3668. break;
  3669. }
  3670. // Replace &amp; by & because &amp; will break URL with params
  3671. $file = !empty($file) ? str_replace('&amp;', '&', $file) : '';
  3672. }
  3673. if ($this->debug > 2) {
  3674. error_log('In learnpath::get_link() - returning "'.$file.'" from get_link', 0);
  3675. }
  3676. return $file;
  3677. }
  3678. /**
  3679. * Gets the latest usable view or generate a new one.
  3680. *
  3681. * @param int $attempt_num Optional attempt number. If none given, takes the highest from the lp_view table
  3682. *
  3683. * @return int DB lp_view id
  3684. */
  3685. public function get_view($attempt_num = 0)
  3686. {
  3687. if ($this->debug > 0) {
  3688. error_log('In learnpath::get_view()', 0);
  3689. }
  3690. $search = '';
  3691. // Use $attempt_num to enable multi-views management (disabled so far).
  3692. if ($attempt_num != 0 && intval(strval($attempt_num)) == $attempt_num) {
  3693. $search = 'AND view_count = '.$attempt_num;
  3694. }
  3695. // When missing $attempt_num, search for a unique lp_view record for this lp and user.
  3696. $lp_view_table = Database::get_course_table(TABLE_LP_VIEW);
  3697. $course_id = api_get_course_int_id();
  3698. $sessionId = api_get_session_id();
  3699. $sql = "SELECT iid, view_count FROM $lp_view_table
  3700. WHERE
  3701. c_id = $course_id AND
  3702. lp_id = ".$this->get_id()." AND
  3703. user_id = ".$this->get_user_id()." AND
  3704. session_id = $sessionId
  3705. $search
  3706. ORDER BY view_count DESC";
  3707. $res = Database::query($sql);
  3708. if (Database::num_rows($res) > 0) {
  3709. $row = Database::fetch_array($res);
  3710. $this->lp_view_id = $row['iid'];
  3711. } elseif (!api_is_invitee()) {
  3712. // There is no database record, create one.
  3713. $sql = "INSERT INTO $lp_view_table (c_id, lp_id, user_id, view_count, session_id) VALUES
  3714. ($course_id, ".$this->get_id().",".$this->get_user_id().", 1, $sessionId)";
  3715. Database::query($sql);
  3716. $id = Database::insert_id();
  3717. $this->lp_view_id = $id;
  3718. $sql = "UPDATE $lp_view_table SET id = iid WHERE iid = $id";
  3719. Database::query($sql);
  3720. }
  3721. return $this->lp_view_id;
  3722. }
  3723. /**
  3724. * Gets the current view id.
  3725. *
  3726. * @return int View ID (from lp_view)
  3727. */
  3728. public function get_view_id()
  3729. {
  3730. if ($this->debug > 0) {
  3731. error_log('In learnpath::get_view_id()', 0);
  3732. }
  3733. if (!empty($this->lp_view_id)) {
  3734. return $this->lp_view_id;
  3735. } else {
  3736. return 0;
  3737. }
  3738. }
  3739. /**
  3740. * Gets the update queue.
  3741. *
  3742. * @return array Array containing IDs of items to be updated by JavaScript
  3743. */
  3744. public function get_update_queue()
  3745. {
  3746. if ($this->debug > 0) {
  3747. error_log('In learnpath::get_update_queue()', 0);
  3748. }
  3749. return $this->update_queue;
  3750. }
  3751. /**
  3752. * Gets the user ID.
  3753. *
  3754. * @return int User ID
  3755. */
  3756. public function get_user_id()
  3757. {
  3758. if ($this->debug > 0) {
  3759. error_log('In learnpath::get_user_id()', 0);
  3760. }
  3761. if (!empty($this->user_id)) {
  3762. return $this->user_id;
  3763. } else {
  3764. return false;
  3765. }
  3766. }
  3767. /**
  3768. * Checks if any of the items has an audio element attached.
  3769. *
  3770. * @return bool True or false
  3771. */
  3772. public function has_audio()
  3773. {
  3774. if ($this->debug > 1) {
  3775. error_log('In learnpath::has_audio()', 0);
  3776. }
  3777. $has = false;
  3778. foreach ($this->items as $i => $item) {
  3779. if (!empty($this->items[$i]->audio)) {
  3780. $has = true;
  3781. break;
  3782. }
  3783. }
  3784. return $has;
  3785. }
  3786. /**
  3787. * Moves an item up and down at its level.
  3788. *
  3789. * @param int $id Item to move up and down
  3790. * @param string $direction Direction 'up' or 'down'
  3791. *
  3792. * @return bool|int
  3793. */
  3794. public function move_item($id, $direction)
  3795. {
  3796. $course_id = api_get_course_int_id();
  3797. if ($this->debug > 0) {
  3798. error_log('In learnpath::move_item('.$id.','.$direction.')', 0);
  3799. }
  3800. if (empty($id) || empty($direction)) {
  3801. return false;
  3802. }
  3803. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  3804. $sql_sel = "SELECT *
  3805. FROM $tbl_lp_item
  3806. WHERE
  3807. iid = $id
  3808. ";
  3809. $res_sel = Database::query($sql_sel);
  3810. // Check if elem exists.
  3811. if (Database::num_rows($res_sel) < 1) {
  3812. return false;
  3813. }
  3814. // Gather data.
  3815. $row = Database::fetch_array($res_sel);
  3816. $previous = $row['previous_item_id'];
  3817. $next = $row['next_item_id'];
  3818. $display = $row['display_order'];
  3819. $parent = $row['parent_item_id'];
  3820. $lp = $row['lp_id'];
  3821. // Update the item (switch with previous/next one).
  3822. switch ($direction) {
  3823. case 'up':
  3824. if ($this->debug > 2) {
  3825. error_log('Movement up detected', 0);
  3826. }
  3827. if ($display > 1) {
  3828. $sql_sel2 = "SELECT * FROM $tbl_lp_item
  3829. WHERE iid = $previous";
  3830. if ($this->debug > 2) {
  3831. error_log('Selecting previous: '.$sql_sel2, 0);
  3832. }
  3833. $res_sel2 = Database::query($sql_sel2);
  3834. if (Database::num_rows($res_sel2) < 1) {
  3835. $previous_previous = 0;
  3836. }
  3837. // Gather data.
  3838. $row2 = Database::fetch_array($res_sel2);
  3839. $previous_previous = $row2['previous_item_id'];
  3840. // Update previous_previous item (switch "next" with current).
  3841. if ($previous_previous != 0) {
  3842. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3843. next_item_id = $id
  3844. WHERE iid = $previous_previous";
  3845. if ($this->debug > 2) {
  3846. error_log($sql_upd2, 0);
  3847. }
  3848. Database::query($sql_upd2);
  3849. }
  3850. // Update previous item (switch with current).
  3851. if ($previous != 0) {
  3852. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3853. next_item_id = $next,
  3854. previous_item_id = $id,
  3855. display_order = display_order +1
  3856. WHERE iid = $previous";
  3857. if ($this->debug > 2) {
  3858. error_log($sql_upd2, 0);
  3859. }
  3860. Database::query($sql_upd2);
  3861. }
  3862. // Update current item (switch with previous).
  3863. if ($id != 0) {
  3864. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3865. next_item_id = $previous,
  3866. previous_item_id = $previous_previous,
  3867. display_order = display_order-1
  3868. WHERE c_id = ".$course_id." AND id = $id";
  3869. if ($this->debug > 2) {
  3870. error_log($sql_upd2, 0);
  3871. }
  3872. Database::query($sql_upd2);
  3873. }
  3874. // Update next item (new previous item).
  3875. if (!empty($next)) {
  3876. $sql_upd2 = "UPDATE $tbl_lp_item SET previous_item_id = $previous
  3877. WHERE iid = $next";
  3878. if ($this->debug > 2) {
  3879. error_log($sql_upd2, 0);
  3880. }
  3881. Database::query($sql_upd2);
  3882. }
  3883. $display = $display - 1;
  3884. }
  3885. break;
  3886. case 'down':
  3887. if ($this->debug > 2) {
  3888. error_log('Movement down detected', 0);
  3889. }
  3890. if ($next != 0) {
  3891. $sql_sel2 = "SELECT * FROM $tbl_lp_item
  3892. WHERE iid = $next";
  3893. if ($this->debug > 2) {
  3894. error_log('Selecting next: '.$sql_sel2, 0);
  3895. }
  3896. $res_sel2 = Database::query($sql_sel2);
  3897. if (Database::num_rows($res_sel2) < 1) {
  3898. $next_next = 0;
  3899. }
  3900. // Gather data.
  3901. $row2 = Database::fetch_array($res_sel2);
  3902. $next_next = $row2['next_item_id'];
  3903. // Update previous item (switch with current).
  3904. if ($previous != 0) {
  3905. $sql_upd2 = "UPDATE $tbl_lp_item
  3906. SET next_item_id = $next
  3907. WHERE iid = $previous";
  3908. Database::query($sql_upd2);
  3909. }
  3910. // Update current item (switch with previous).
  3911. if ($id != 0) {
  3912. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3913. previous_item_id = $next,
  3914. next_item_id = $next_next,
  3915. display_order = display_order + 1
  3916. WHERE iid = $id";
  3917. Database::query($sql_upd2);
  3918. }
  3919. // Update next item (new previous item).
  3920. if ($next != 0) {
  3921. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3922. previous_item_id = $previous,
  3923. next_item_id = $id,
  3924. display_order = display_order-1
  3925. WHERE iid = $next";
  3926. Database::query($sql_upd2);
  3927. }
  3928. // Update next_next item (switch "previous" with current).
  3929. if ($next_next != 0) {
  3930. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3931. previous_item_id = $id
  3932. WHERE iid = $next_next";
  3933. Database::query($sql_upd2);
  3934. }
  3935. $display = $display + 1;
  3936. }
  3937. break;
  3938. default:
  3939. return false;
  3940. }
  3941. return $display;
  3942. }
  3943. /**
  3944. * Move a LP up (display_order).
  3945. *
  3946. * @param int $lp_id Learnpath ID
  3947. * @param int $categoryId Category ID
  3948. *
  3949. * @return bool
  3950. */
  3951. public static function move_up($lp_id, $categoryId = 0)
  3952. {
  3953. $courseId = api_get_course_int_id();
  3954. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3955. $categoryCondition = '';
  3956. if (!empty($categoryId)) {
  3957. $categoryId = (int) $categoryId;
  3958. $categoryCondition = " AND category_id = $categoryId";
  3959. }
  3960. $sql = "SELECT * FROM $lp_table
  3961. WHERE c_id = $courseId
  3962. $categoryCondition
  3963. ORDER BY display_order";
  3964. $res = Database::query($sql);
  3965. if ($res === false) {
  3966. return false;
  3967. }
  3968. $lps = [];
  3969. $lp_order = [];
  3970. $num = Database::num_rows($res);
  3971. // First check the order is correct, globally (might be wrong because
  3972. // of versions < 1.8.4)
  3973. if ($num > 0) {
  3974. $i = 1;
  3975. while ($row = Database::fetch_array($res)) {
  3976. if ($row['display_order'] != $i) { // If we find a gap in the order, we need to fix it.
  3977. $sql = "UPDATE $lp_table SET display_order = $i
  3978. WHERE iid = ".$row['iid'];
  3979. Database::query($sql);
  3980. }
  3981. $row['display_order'] = $i;
  3982. $lps[$row['iid']] = $row;
  3983. $lp_order[$i] = $row['iid'];
  3984. $i++;
  3985. }
  3986. }
  3987. if ($num > 1) { // If there's only one element, no need to sort.
  3988. $order = $lps[$lp_id]['display_order'];
  3989. if ($order > 1) { // If it's the first element, no need to move up.
  3990. $sql = "UPDATE $lp_table SET display_order = $order
  3991. WHERE iid = ".$lp_order[$order - 1];
  3992. Database::query($sql);
  3993. $sql = "UPDATE $lp_table SET display_order = ".($order - 1)."
  3994. WHERE iid = $lp_id";
  3995. Database::query($sql);
  3996. }
  3997. }
  3998. return true;
  3999. }
  4000. /**
  4001. * Move a learnpath down (display_order).
  4002. *
  4003. * @param int $lp_id Learnpath ID
  4004. * @param int $categoryId Category ID
  4005. *
  4006. * @return bool
  4007. */
  4008. public static function move_down($lp_id, $categoryId = 0)
  4009. {
  4010. $courseId = api_get_course_int_id();
  4011. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4012. $categoryCondition = '';
  4013. if (!empty($categoryId)) {
  4014. $categoryId = (int) $categoryId;
  4015. $categoryCondition = " AND category_id = $categoryId";
  4016. }
  4017. $sql = "SELECT * FROM $lp_table
  4018. WHERE c_id = $courseId
  4019. $categoryCondition
  4020. ORDER BY display_order";
  4021. $res = Database::query($sql);
  4022. if ($res === false) {
  4023. return false;
  4024. }
  4025. $lps = [];
  4026. $lp_order = [];
  4027. $num = Database::num_rows($res);
  4028. $max = 0;
  4029. // First check the order is correct, globally (might be wrong because
  4030. // of versions < 1.8.4).
  4031. if ($num > 0) {
  4032. $i = 1;
  4033. while ($row = Database::fetch_array($res)) {
  4034. $max = $i;
  4035. if ($row['display_order'] != $i) {
  4036. // If we find a gap in the order, we need to fix it.
  4037. $sql = "UPDATE $lp_table SET display_order = $i
  4038. WHERE iid = ".$row['iid'];
  4039. Database::query($sql);
  4040. }
  4041. $row['display_order'] = $i;
  4042. $lps[$row['iid']] = $row;
  4043. $lp_order[$i] = $row['iid'];
  4044. $i++;
  4045. }
  4046. }
  4047. if ($num > 1) { // If there's only one element, no need to sort.
  4048. $order = $lps[$lp_id]['display_order'];
  4049. if ($order < $max) { // If it's the first element, no need to move up.
  4050. $sql = "UPDATE $lp_table SET display_order = $order
  4051. WHERE iid = ".$lp_order[$order + 1];
  4052. Database::query($sql);
  4053. $sql = "UPDATE $lp_table SET display_order = ".($order + 1)."
  4054. WHERE iid = $lp_id";
  4055. Database::query($sql);
  4056. }
  4057. }
  4058. return true;
  4059. }
  4060. /**
  4061. * Updates learnpath attributes to point to the next element
  4062. * The last part is similar to set_current_item but processing the other way around.
  4063. */
  4064. public function next()
  4065. {
  4066. if ($this->debug > 0) {
  4067. error_log('In learnpath::next()', 0);
  4068. }
  4069. $this->last = $this->get_current_item_id();
  4070. $this->items[$this->last]->save(
  4071. false,
  4072. $this->prerequisites_match($this->last)
  4073. );
  4074. $this->autocomplete_parents($this->last);
  4075. $new_index = $this->get_next_index();
  4076. if ($this->debug > 2) {
  4077. error_log('New index: '.$new_index, 0);
  4078. }
  4079. $this->index = $new_index;
  4080. if ($this->debug > 2) {
  4081. error_log('Now having orderedlist['.$new_index.'] = '.$this->ordered_items[$new_index], 0);
  4082. }
  4083. $this->current = $this->ordered_items[$new_index];
  4084. if ($this->debug > 2) {
  4085. error_log('new item id is '.$this->current.'-'.$this->get_current_item_id(), 0);
  4086. }
  4087. }
  4088. /**
  4089. * Open a resource = initialise all local variables relative to this resource. Depending on the child
  4090. * class, this might be redefined to allow several behaviours depending on the document type.
  4091. *
  4092. * @param int $id Resource ID
  4093. */
  4094. public function open($id)
  4095. {
  4096. if ($this->debug > 0) {
  4097. error_log('In learnpath::open()', 0);
  4098. }
  4099. // TODO:
  4100. // set the current resource attribute to this resource
  4101. // switch on element type (redefine in child class?)
  4102. // set status for this item to "opened"
  4103. // start timer
  4104. // initialise score
  4105. $this->index = 0; //or = the last item seen (see $this->last)
  4106. }
  4107. /**
  4108. * Check that all prerequisites are fulfilled. Returns true and an
  4109. * empty string on success, returns false
  4110. * and the prerequisite string on error.
  4111. * This function is based on the rules for aicc_script language as
  4112. * described in the SCORM 1.2 CAM documentation page 108.
  4113. *
  4114. * @param int $itemId Optional item ID. If none given, uses the current open item.
  4115. *
  4116. * @return bool true if prerequisites are matched, false otherwise - Empty string if true returned, prerequisites
  4117. * string otherwise
  4118. */
  4119. public function prerequisites_match($itemId = null)
  4120. {
  4121. $allow = api_get_configuration_value('allow_teachers_to_access_blocked_lp_by_prerequisite');
  4122. if ($allow) {
  4123. if (api_is_allowed_to_edit() ||
  4124. api_is_platform_admin(true) ||
  4125. api_is_drh() ||
  4126. api_is_coach(api_get_session_id(), api_get_course_int_id())
  4127. ) {
  4128. return true;
  4129. }
  4130. }
  4131. $debug = $this->debug;
  4132. if ($debug > 0) {
  4133. error_log('In learnpath::prerequisites_match()', 0);
  4134. }
  4135. if (empty($itemId)) {
  4136. $itemId = $this->current;
  4137. }
  4138. $currentItem = $this->getItem($itemId);
  4139. if ($currentItem) {
  4140. if ($this->type == 2) {
  4141. // Getting prereq from scorm
  4142. $prereq_string = $this->get_scorm_prereq_string($itemId);
  4143. } else {
  4144. $prereq_string = $currentItem->get_prereq_string();
  4145. }
  4146. if (empty($prereq_string)) {
  4147. if ($debug > 0) {
  4148. error_log('Found prereq_string is empty return true');
  4149. }
  4150. return true;
  4151. }
  4152. // Clean spaces.
  4153. $prereq_string = str_replace(' ', '', $prereq_string);
  4154. if ($debug > 0) {
  4155. error_log('Found prereq_string: '.$prereq_string, 0);
  4156. }
  4157. // Now send to the parse_prereq() function that will check this component's prerequisites.
  4158. $result = $currentItem->parse_prereq(
  4159. $prereq_string,
  4160. $this->items,
  4161. $this->refs_list,
  4162. $this->get_user_id()
  4163. );
  4164. if ($result === false) {
  4165. $this->set_error_msg($currentItem->prereq_alert);
  4166. }
  4167. } else {
  4168. $result = true;
  4169. if ($debug > 1) {
  4170. error_log('$this->items['.$itemId.'] was not an object', 0);
  4171. }
  4172. }
  4173. if ($debug > 1) {
  4174. error_log('End of prerequisites_match(). Error message is now '.$this->error, 0);
  4175. }
  4176. return $result;
  4177. }
  4178. /**
  4179. * Updates learnpath attributes to point to the previous element
  4180. * The last part is similar to set_current_item but processing the other way around.
  4181. */
  4182. public function previous()
  4183. {
  4184. if ($this->debug > 0) {
  4185. error_log('In learnpath::previous()', 0);
  4186. }
  4187. $this->last = $this->get_current_item_id();
  4188. $this->items[$this->last]->save(
  4189. false,
  4190. $this->prerequisites_match($this->last)
  4191. );
  4192. $this->autocomplete_parents($this->last);
  4193. $new_index = $this->get_previous_index();
  4194. $this->index = $new_index;
  4195. $this->current = $this->ordered_items[$new_index];
  4196. }
  4197. /**
  4198. * Publishes a learnpath. This basically means show or hide the learnpath
  4199. * to normal users.
  4200. * Can be used as abstract.
  4201. *
  4202. * @param int $lp_id Learnpath ID
  4203. * @param int $set_visibility New visibility
  4204. *
  4205. * @return bool
  4206. */
  4207. public static function toggle_visibility($lp_id, $set_visibility = 1)
  4208. {
  4209. $action = 'visible';
  4210. if ($set_visibility != 1) {
  4211. $action = 'invisible';
  4212. self::toggle_publish($lp_id, 'i');
  4213. }
  4214. return api_item_property_update(
  4215. api_get_course_info(),
  4216. TOOL_LEARNPATH,
  4217. $lp_id,
  4218. $action,
  4219. api_get_user_id()
  4220. );
  4221. }
  4222. /**
  4223. * Publishes a learnpath category.
  4224. * This basically means show or hide the learnpath category to normal users.
  4225. *
  4226. * @param int $id
  4227. * @param int $visibility
  4228. *
  4229. * @throws \Doctrine\ORM\NonUniqueResultException
  4230. * @throws \Doctrine\ORM\ORMException
  4231. * @throws \Doctrine\ORM\OptimisticLockException
  4232. * @throws \Doctrine\ORM\TransactionRequiredException
  4233. *
  4234. * @return bool
  4235. */
  4236. public static function toggleCategoryVisibility($id, $visibility = 1)
  4237. {
  4238. $action = 'visible';
  4239. if ($visibility != 1) {
  4240. $action = 'invisible';
  4241. $list = new LearnpathList(
  4242. api_get_user_id(),
  4243. null,
  4244. null,
  4245. null,
  4246. false,
  4247. $id
  4248. );
  4249. $lpList = $list->get_flat_list();
  4250. foreach ($lpList as $lp) {
  4251. self::toggle_visibility($lp['iid'], 0);
  4252. }
  4253. self::toggleCategoryPublish($id, 0);
  4254. }
  4255. return api_item_property_update(
  4256. api_get_course_info(),
  4257. TOOL_LEARNPATH_CATEGORY,
  4258. $id,
  4259. $action,
  4260. api_get_user_id()
  4261. );
  4262. }
  4263. /**
  4264. * Publishes a learnpath. This basically means show or hide the learnpath
  4265. * on the course homepage
  4266. * Can be used as abstract.
  4267. *
  4268. * @param int $lp_id Learnpath id
  4269. * @param string $set_visibility New visibility (v/i - visible/invisible)
  4270. *
  4271. * @return bool
  4272. */
  4273. public static function toggle_publish($lp_id, $set_visibility = 'v')
  4274. {
  4275. $course_id = api_get_course_int_id();
  4276. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4277. $lp_id = (int) $lp_id;
  4278. $sql = "SELECT * FROM $tbl_lp
  4279. WHERE iid = $lp_id";
  4280. $result = Database::query($sql);
  4281. if (Database::num_rows($result)) {
  4282. $row = Database::fetch_array($result);
  4283. $name = Database::escape_string($row['name']);
  4284. if ($set_visibility == 'i') {
  4285. $v = 0;
  4286. }
  4287. if ($set_visibility == 'v') {
  4288. $v = 1;
  4289. }
  4290. $session_id = api_get_session_id();
  4291. $session_condition = api_get_session_condition($session_id);
  4292. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  4293. $link = 'lp/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  4294. $oldLink = 'newscorm/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  4295. $sql = "SELECT * FROM $tbl_tool
  4296. WHERE
  4297. c_id = $course_id AND
  4298. (link = '$link' OR link = '$oldLink') AND
  4299. image = 'scormbuilder.gif' AND
  4300. (
  4301. link LIKE '$link%' OR
  4302. link LIKE '$oldLink%'
  4303. )
  4304. $session_condition
  4305. ";
  4306. $result = Database::query($sql);
  4307. $num = Database::num_rows($result);
  4308. if ($set_visibility == 'i' && $num > 0) {
  4309. $sql = "DELETE FROM $tbl_tool
  4310. WHERE
  4311. c_id = $course_id AND
  4312. (link = '$link' OR link = '$oldLink') AND
  4313. image='scormbuilder.gif'
  4314. $session_condition";
  4315. Database::query($sql);
  4316. } elseif ($set_visibility == 'v' && $num == 0) {
  4317. $sql = "INSERT INTO $tbl_tool (category, c_id, name, link, image, visibility, admin, address, added_tool, session_id) VALUES
  4318. ('authoring', $course_id, '$name', '$link', 'scormbuilder.gif', '$v', '0','pastillegris.gif', 0, $session_id)";
  4319. Database::query($sql);
  4320. $insertId = Database::insert_id();
  4321. if ($insertId) {
  4322. $sql = "UPDATE $tbl_tool SET id = iid WHERE iid = $insertId";
  4323. Database::query($sql);
  4324. }
  4325. } elseif ($set_visibility == 'v' && $num > 0) {
  4326. $sql = "UPDATE $tbl_tool SET
  4327. c_id = $course_id,
  4328. name = '$name',
  4329. link = '$link',
  4330. image = 'scormbuilder.gif',
  4331. visibility = '$v',
  4332. admin = '0',
  4333. address = 'pastillegris.gif',
  4334. added_tool = 0,
  4335. session_id = $session_id
  4336. WHERE
  4337. c_id = ".$course_id." AND
  4338. (link = '$link' OR link = '$oldLink') AND
  4339. image='scormbuilder.gif'
  4340. $session_condition
  4341. ";
  4342. Database::query($sql);
  4343. } else {
  4344. // Parameter and database incompatible, do nothing, exit.
  4345. return false;
  4346. }
  4347. } else {
  4348. return false;
  4349. }
  4350. }
  4351. /**
  4352. * Publishes a learnpath.
  4353. * Show or hide the learnpath category on the course homepage.
  4354. *
  4355. * @param int $id
  4356. * @param int $setVisibility
  4357. *
  4358. * @throws \Doctrine\ORM\NonUniqueResultException
  4359. * @throws \Doctrine\ORM\ORMException
  4360. * @throws \Doctrine\ORM\OptimisticLockException
  4361. * @throws \Doctrine\ORM\TransactionRequiredException
  4362. *
  4363. * @return bool
  4364. */
  4365. public static function toggleCategoryPublish($id, $setVisibility = 1)
  4366. {
  4367. $courseId = api_get_course_int_id();
  4368. $sessionId = api_get_session_id();
  4369. $sessionCondition = api_get_session_condition(
  4370. $sessionId,
  4371. true,
  4372. false,
  4373. 't.sessionId'
  4374. );
  4375. $em = Database::getManager();
  4376. /** @var CLpCategory $category */
  4377. $category = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  4378. if (!$category) {
  4379. return false;
  4380. }
  4381. if (empty($courseId)) {
  4382. return false;
  4383. }
  4384. $link = self::getCategoryLinkForTool($id);
  4385. /** @var CTool $tool */
  4386. $tool = $em->createQuery("
  4387. SELECT t FROM ChamiloCourseBundle:CTool t
  4388. WHERE
  4389. t.cId = :course AND
  4390. t.link = :link1 AND
  4391. t.image = 'lp_category.gif' AND
  4392. t.link LIKE :link2
  4393. $sessionCondition
  4394. ")
  4395. ->setParameters([
  4396. 'course' => (int) $courseId,
  4397. 'link1' => $link,
  4398. 'link2' => "$link%",
  4399. ])
  4400. ->getOneOrNullResult();
  4401. if ($setVisibility == 0 && $tool) {
  4402. $em->remove($tool);
  4403. $em->flush();
  4404. return true;
  4405. }
  4406. if ($setVisibility == 1 && !$tool) {
  4407. $tool = new CTool();
  4408. $tool
  4409. ->setCategory('authoring')
  4410. ->setCId($courseId)
  4411. ->setName(strip_tags($category->getName()))
  4412. ->setLink($link)
  4413. ->setImage('lp_category.gif')
  4414. ->setVisibility(1)
  4415. ->setAdmin(0)
  4416. ->setAddress('pastillegris.gif')
  4417. ->setAddedTool(0)
  4418. ->setSessionId($sessionId)
  4419. ->setTarget('_self');
  4420. $em->persist($tool);
  4421. $em->flush();
  4422. $tool->setId($tool->getIid());
  4423. $em->persist($tool);
  4424. $em->flush();
  4425. return true;
  4426. }
  4427. if ($setVisibility == 1 && $tool) {
  4428. $tool
  4429. ->setName(strip_tags($category->getName()))
  4430. ->setVisibility(1);
  4431. $em->persist($tool);
  4432. $em->flush();
  4433. return true;
  4434. }
  4435. return false;
  4436. }
  4437. /**
  4438. * Check if the learnpath category is visible for a user.
  4439. *
  4440. * @param CLpCategory $category
  4441. * @param User $user
  4442. * @param int
  4443. * @param int
  4444. *
  4445. * @return bool
  4446. */
  4447. public static function categoryIsVisibleForStudent(
  4448. CLpCategory $category,
  4449. User $user,
  4450. $courseId = 0,
  4451. $sessionId = 0
  4452. ) {
  4453. $subscriptionSettings = self::getSubscriptionSettings();
  4454. if ($subscriptionSettings['allow_add_users_to_lp_category'] == false) {
  4455. return true;
  4456. }
  4457. $isAllowedToEdit = api_is_allowed_to_edit(null, true);
  4458. if ($isAllowedToEdit) {
  4459. return true;
  4460. }
  4461. if (empty($category)) {
  4462. return false;
  4463. }
  4464. $users = $category->getUsers();
  4465. if (empty($users) || !$users->count()) {
  4466. return true;
  4467. }
  4468. $courseId = empty($courseId) ? api_get_course_int_id() : (int) $courseId;
  4469. $sessionId = empty($sessionId) ? api_get_session_id() : (int) $sessionId;
  4470. if ($category->hasUserAdded($user)) {
  4471. return true;
  4472. }
  4473. $groups = GroupManager::getAllGroupPerUserSubscription($user->getId());
  4474. if (!empty($groups)) {
  4475. $em = Database::getManager();
  4476. /** @var ItemPropertyRepository $itemRepo */
  4477. $itemRepo = $em->getRepository('ChamiloCourseBundle:CItemProperty');
  4478. /** @var CourseRepository $courseRepo */
  4479. $courseRepo = $em->getRepository('ChamiloCoreBundle:Course');
  4480. $session = null;
  4481. if (!empty($sessionId)) {
  4482. $session = $em->getRepository('ChamiloCoreBundle:Session')->find($sessionId);
  4483. }
  4484. $course = $courseRepo->find($courseId);
  4485. // Subscribed groups to a LP
  4486. $subscribedGroupsInLp = $itemRepo->getGroupsSubscribedToItem(
  4487. TOOL_LEARNPATH_CATEGORY,
  4488. $category->getId(),
  4489. $course,
  4490. $session
  4491. );
  4492. if (!empty($subscribedGroupsInLp)) {
  4493. $groups = array_column($groups, 'iid');
  4494. /** @var CItemProperty $item */
  4495. foreach ($subscribedGroupsInLp as $item) {
  4496. if ($item->getGroup() &&
  4497. in_array($item->getGroup()->getId(), $groups)
  4498. ) {
  4499. return true;
  4500. }
  4501. }
  4502. }
  4503. }
  4504. return false;
  4505. }
  4506. /**
  4507. * Check if a learnpath category is published as course tool.
  4508. *
  4509. * @param CLpCategory $category
  4510. * @param int $courseId
  4511. *
  4512. * @return bool
  4513. */
  4514. public static function categoryIsPublished(
  4515. CLpCategory $category,
  4516. $courseId
  4517. ) {
  4518. $link = self::getCategoryLinkForTool($category->getId());
  4519. $em = Database::getManager();
  4520. $tools = $em
  4521. ->createQuery("
  4522. SELECT t FROM ChamiloCourseBundle:CTool t
  4523. WHERE t.cId = :course AND
  4524. t.name = :name AND
  4525. t.image = 'lp_category.gif' AND
  4526. t.link LIKE :link
  4527. ")
  4528. ->setParameters([
  4529. 'course' => $courseId,
  4530. 'name' => strip_tags($category->getName()),
  4531. 'link' => "$link%",
  4532. ])
  4533. ->getResult();
  4534. /** @var CTool $tool */
  4535. $tool = current($tools);
  4536. return $tool ? $tool->getVisibility() : false;
  4537. }
  4538. /**
  4539. * Restart the whole learnpath. Return the URL of the first element.
  4540. * Make sure the results are saved with anoter method. This method should probably be redefined in children classes.
  4541. * To use a similar method statically, use the create_new_attempt() method.
  4542. *
  4543. * @return bool
  4544. */
  4545. public function restart()
  4546. {
  4547. if ($this->debug > 0) {
  4548. error_log('In learnpath::restart()', 0);
  4549. }
  4550. // TODO
  4551. // Call autosave method to save the current progress.
  4552. //$this->index = 0;
  4553. if (api_is_invitee()) {
  4554. return false;
  4555. }
  4556. $session_id = api_get_session_id();
  4557. $course_id = api_get_course_int_id();
  4558. $lp_view_table = Database::get_course_table(TABLE_LP_VIEW);
  4559. $sql = "INSERT INTO $lp_view_table (c_id, lp_id, user_id, view_count, session_id)
  4560. VALUES ($course_id, ".$this->lp_id.",".$this->get_user_id().",".($this->attempt + 1).", $session_id)";
  4561. if ($this->debug > 2) {
  4562. error_log('Inserting new lp_view for restart: '.$sql, 0);
  4563. }
  4564. Database::query($sql);
  4565. $view_id = Database::insert_id();
  4566. if ($view_id) {
  4567. $sql = "UPDATE $lp_view_table SET id = iid WHERE iid = $view_id";
  4568. Database::query($sql);
  4569. $this->lp_view_id = $view_id;
  4570. $this->attempt = $this->attempt + 1;
  4571. } else {
  4572. $this->error = 'Could not insert into item_view table...';
  4573. return false;
  4574. }
  4575. $this->autocomplete_parents($this->current);
  4576. foreach ($this->items as $index => $dummy) {
  4577. $this->items[$index]->restart();
  4578. $this->items[$index]->set_lp_view($this->lp_view_id);
  4579. }
  4580. $this->first();
  4581. return true;
  4582. }
  4583. /**
  4584. * Saves the current item.
  4585. *
  4586. * @return bool
  4587. */
  4588. public function save_current()
  4589. {
  4590. $debug = $this->debug;
  4591. // TODO: Do a better check on the index pointing to the right item (it is supposed to be working
  4592. // on $ordered_items[] but not sure it's always safe to use with $items[]).
  4593. if ($debug) {
  4594. error_log('save_current() saving item '.$this->current, 0);
  4595. error_log(''.print_r($this->items, true), 0);
  4596. }
  4597. if (isset($this->items[$this->current]) &&
  4598. is_object($this->items[$this->current])
  4599. ) {
  4600. if ($debug) {
  4601. error_log('Before save last_scorm_session_time: '.$this->items[$this->current]->getLastScormSessionTime());
  4602. }
  4603. $res = $this->items[$this->current]->save(
  4604. false,
  4605. $this->prerequisites_match($this->current)
  4606. );
  4607. $this->autocomplete_parents($this->current);
  4608. $status = $this->items[$this->current]->get_status();
  4609. $this->update_queue[$this->current] = $status;
  4610. if ($debug) {
  4611. error_log('After save last_scorm_session_time: '.$this->items[$this->current]->getLastScormSessionTime());
  4612. }
  4613. return $res;
  4614. }
  4615. return false;
  4616. }
  4617. /**
  4618. * Saves the given item.
  4619. *
  4620. * @param int $item_id Optional (will take from $_REQUEST if null)
  4621. * @param bool $from_outside Save from url params (true) or from current attributes (false). Default true
  4622. *
  4623. * @return bool
  4624. */
  4625. public function save_item($item_id = null, $from_outside = true)
  4626. {
  4627. $debug = $this->debug;
  4628. if ($debug) {
  4629. error_log('In learnpath::save_item('.$item_id.','.intval($from_outside).')', 0);
  4630. }
  4631. // TODO: Do a better check on the index pointing to the right item (it is supposed to be working
  4632. // on $ordered_items[] but not sure it's always safe to use with $items[]).
  4633. if (empty($item_id)) {
  4634. $item_id = (int) $_REQUEST['id'];
  4635. }
  4636. if (empty($item_id)) {
  4637. $item_id = $this->get_current_item_id();
  4638. }
  4639. if (isset($this->items[$item_id]) &&
  4640. is_object($this->items[$item_id])
  4641. ) {
  4642. if ($debug) {
  4643. error_log('Object exists');
  4644. }
  4645. // Saving the item.
  4646. $res = $this->items[$item_id]->save(
  4647. $from_outside,
  4648. $this->prerequisites_match($item_id)
  4649. );
  4650. if ($debug) {
  4651. error_log('update_queue before:');
  4652. error_log(print_r($this->update_queue, 1));
  4653. }
  4654. $this->autocomplete_parents($item_id);
  4655. $status = $this->items[$item_id]->get_status();
  4656. $this->update_queue[$item_id] = $status;
  4657. if ($debug) {
  4658. error_log('get_status(): '.$status);
  4659. error_log('update_queue after:');
  4660. error_log(print_r($this->update_queue, 1));
  4661. }
  4662. return $res;
  4663. }
  4664. return false;
  4665. }
  4666. /**
  4667. * Saves the last item seen's ID only in case.
  4668. */
  4669. public function save_last()
  4670. {
  4671. $course_id = api_get_course_int_id();
  4672. $debug = $this->debug;
  4673. if ($debug) {
  4674. error_log('In learnpath::save_last()', 0);
  4675. }
  4676. $session_condition = api_get_session_condition(
  4677. api_get_session_id(),
  4678. true,
  4679. false
  4680. );
  4681. $table = Database::get_course_table(TABLE_LP_VIEW);
  4682. if (isset($this->current) && !api_is_invitee()) {
  4683. if ($debug) {
  4684. error_log('Saving current item ('.$this->current.') for later review', 0);
  4685. }
  4686. $sql = "UPDATE $table SET
  4687. last_item = ".intval($this->get_current_item_id())."
  4688. WHERE
  4689. c_id = $course_id AND
  4690. lp_id = ".$this->get_id()." AND
  4691. user_id = ".$this->get_user_id()." ".$session_condition;
  4692. if ($debug) {
  4693. error_log('Saving last item seen : '.$sql, 0);
  4694. }
  4695. Database::query($sql);
  4696. }
  4697. if (!api_is_invitee()) {
  4698. // Save progress.
  4699. list($progress) = $this->get_progress_bar_text('%');
  4700. if ($progress >= 0 && $progress <= 100) {
  4701. $progress = (int) $progress;
  4702. $sql = "UPDATE $table SET
  4703. progress = $progress
  4704. WHERE
  4705. c_id = $course_id AND
  4706. lp_id = ".$this->get_id()." AND
  4707. user_id = ".$this->get_user_id()." ".$session_condition;
  4708. // Ignore errors as some tables might not have the progress field just yet.
  4709. Database::query($sql);
  4710. if ($debug) {
  4711. error_log($sql);
  4712. }
  4713. $this->progress_db = $progress;
  4714. }
  4715. }
  4716. }
  4717. /**
  4718. * Sets the current item ID (checks if valid and authorized first).
  4719. *
  4720. * @param int $item_id New item ID. If not given or not authorized, defaults to current
  4721. */
  4722. public function set_current_item($item_id = null)
  4723. {
  4724. $debug = $this->debug;
  4725. if ($debug) {
  4726. error_log('In learnpath::set_current_item('.$item_id.')', 0);
  4727. }
  4728. if (empty($item_id)) {
  4729. if ($debug) {
  4730. error_log('No new current item given, ignore...', 0);
  4731. }
  4732. // Do nothing.
  4733. } else {
  4734. if ($debug) {
  4735. error_log('New current item given is '.$item_id.'...', 0);
  4736. }
  4737. if (is_numeric($item_id)) {
  4738. $item_id = (int) $item_id;
  4739. // TODO: Check in database here.
  4740. $this->last = $this->current;
  4741. $this->current = $item_id;
  4742. // TODO: Update $this->index as well.
  4743. foreach ($this->ordered_items as $index => $item) {
  4744. if ($item == $this->current) {
  4745. $this->index = $index;
  4746. break;
  4747. }
  4748. }
  4749. if ($debug) {
  4750. error_log('set_current_item('.$item_id.') done. Index is now : '.$this->index);
  4751. }
  4752. } else {
  4753. if ($debug) {
  4754. error_log('set_current_item('.$item_id.') failed. Not a numeric value: ');
  4755. }
  4756. }
  4757. }
  4758. }
  4759. /**
  4760. * Sets the encoding.
  4761. *
  4762. * @param string $enc New encoding
  4763. *
  4764. * @return bool
  4765. *
  4766. * @todo (as of Chamilo 1.8.8): Check in the future whether this method is needed.
  4767. */
  4768. public function set_encoding($enc = 'UTF-8')
  4769. {
  4770. if ($this->debug > 0) {
  4771. error_log('In learnpath::set_encoding()', 0);
  4772. }
  4773. $enc = api_refine_encoding_id($enc);
  4774. if (empty($enc)) {
  4775. $enc = api_get_system_encoding();
  4776. }
  4777. if (api_is_encoding_supported($enc)) {
  4778. $lp = $this->get_id();
  4779. if ($lp != 0) {
  4780. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4781. $sql = "UPDATE $tbl_lp SET default_encoding = '$enc'
  4782. WHERE iid = ".$lp;
  4783. $res = Database::query($sql);
  4784. return $res;
  4785. }
  4786. }
  4787. return false;
  4788. }
  4789. /**
  4790. * Sets the JS lib setting in the database directly.
  4791. * This is the JavaScript library file this lp needs to load on startup.
  4792. *
  4793. * @param string $lib Proximity setting
  4794. *
  4795. * @return bool True on update success. False otherwise.
  4796. */
  4797. public function set_jslib($lib = '')
  4798. {
  4799. if ($this->debug > 0) {
  4800. error_log('In learnpath::set_jslib()', 0);
  4801. }
  4802. $lp = $this->get_id();
  4803. if ($lp != 0) {
  4804. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4805. $sql = "UPDATE $tbl_lp SET js_lib = '$lib'
  4806. WHERE iid = $lp";
  4807. $res = Database::query($sql);
  4808. return $res;
  4809. } else {
  4810. return false;
  4811. }
  4812. }
  4813. /**
  4814. * Sets the name of the LP maker (publisher) (and save).
  4815. *
  4816. * @param string $name Optional string giving the new content_maker of this learnpath
  4817. *
  4818. * @return bool True
  4819. */
  4820. public function set_maker($name = '')
  4821. {
  4822. if ($this->debug > 0) {
  4823. error_log('In learnpath::set_maker()', 0);
  4824. }
  4825. if (empty($name)) {
  4826. return false;
  4827. }
  4828. $this->maker = $name;
  4829. $table = Database::get_course_table(TABLE_LP_MAIN);
  4830. $lp_id = $this->get_id();
  4831. $sql = "UPDATE $table SET
  4832. content_maker = '".Database::escape_string($this->maker)."'
  4833. WHERE iid = $lp_id";
  4834. if ($this->debug > 2) {
  4835. error_log('lp updated with new content_maker : '.$this->maker, 0);
  4836. }
  4837. Database::query($sql);
  4838. return true;
  4839. }
  4840. /**
  4841. * Sets the name of the current learnpath (and save).
  4842. *
  4843. * @param string $name Optional string giving the new name of this learnpath
  4844. *
  4845. * @return bool True/False
  4846. */
  4847. public function set_name($name = null)
  4848. {
  4849. if ($this->debug > 0) {
  4850. error_log('In learnpath::set_name()', 0);
  4851. }
  4852. if (empty($name)) {
  4853. return false;
  4854. }
  4855. $this->name = Database::escape_string($name);
  4856. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4857. $lp_id = $this->get_id();
  4858. $course_id = $this->course_info['real_id'];
  4859. $sql = "UPDATE $lp_table SET
  4860. name = '".Database::escape_string($this->name)."'
  4861. WHERE iid = $lp_id";
  4862. if ($this->debug > 2) {
  4863. error_log('lp updated with new name : '.$this->name, 0);
  4864. }
  4865. $result = Database::query($sql);
  4866. // If the lp is visible on the homepage, change his name there.
  4867. if (Database::affected_rows($result)) {
  4868. $session_id = api_get_session_id();
  4869. $session_condition = api_get_session_condition($session_id);
  4870. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  4871. $link = 'lp/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  4872. $sql = "UPDATE $tbl_tool SET name = '$this->name'
  4873. WHERE
  4874. c_id = $course_id AND
  4875. (link='$link' AND image='scormbuilder.gif' $session_condition)";
  4876. Database::query($sql);
  4877. return true;
  4878. } else {
  4879. return false;
  4880. }
  4881. }
  4882. /**
  4883. * Set index specified prefix terms for all items in this path.
  4884. *
  4885. * @param string $terms_string Comma-separated list of terms
  4886. * @param string $prefix Xapian term prefix
  4887. *
  4888. * @return bool False on error, true otherwise
  4889. */
  4890. public function set_terms_by_prefix($terms_string, $prefix)
  4891. {
  4892. $course_id = api_get_course_int_id();
  4893. if (api_get_setting('search_enabled') !== 'true') {
  4894. return false;
  4895. }
  4896. if (!extension_loaded('xapian')) {
  4897. return false;
  4898. }
  4899. $terms_string = trim($terms_string);
  4900. $terms = explode(',', $terms_string);
  4901. array_walk($terms, 'trim_value');
  4902. $stored_terms = $this->get_common_index_terms_by_prefix($prefix);
  4903. // Don't do anything if no change, verify only at DB, not the search engine.
  4904. if ((count(array_diff($terms, $stored_terms)) == 0) && (count(array_diff($stored_terms, $terms)) == 0)) {
  4905. return false;
  4906. }
  4907. require_once 'xapian.php'; // TODO: Try catch every xapian use or make wrappers on API.
  4908. require_once api_get_path(LIBRARY_PATH).'search/xapian/XapianQuery.php';
  4909. $items_table = Database::get_course_table(TABLE_LP_ITEM);
  4910. // TODO: Make query secure agains XSS : use member attr instead of post var.
  4911. $lp_id = (int) $_POST['lp_id'];
  4912. $sql = "SELECT * FROM $items_table WHERE c_id = $course_id AND lp_id = $lp_id";
  4913. $result = Database::query($sql);
  4914. $di = new ChamiloIndexer();
  4915. while ($lp_item = Database::fetch_array($result)) {
  4916. // Get search_did.
  4917. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  4918. $sql = 'SELECT * FROM %s
  4919. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
  4920. LIMIT 1';
  4921. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp_id, $lp_item['id']);
  4922. //echo $sql; echo '<br>';
  4923. $res = Database::query($sql);
  4924. if (Database::num_rows($res) > 0) {
  4925. $se_ref = Database::fetch_array($res);
  4926. // Compare terms.
  4927. $doc = $di->get_document($se_ref['search_did']);
  4928. $xapian_terms = xapian_get_doc_terms($doc, $prefix);
  4929. $xterms = [];
  4930. foreach ($xapian_terms as $xapian_term) {
  4931. $xterms[] = substr($xapian_term['name'], 1);
  4932. }
  4933. $dterms = $terms;
  4934. $missing_terms = array_diff($dterms, $xterms);
  4935. $deprecated_terms = array_diff($xterms, $dterms);
  4936. // Save it to search engine.
  4937. foreach ($missing_terms as $term) {
  4938. $doc->add_term($prefix.$term, 1);
  4939. }
  4940. foreach ($deprecated_terms as $term) {
  4941. $doc->remove_term($prefix.$term);
  4942. }
  4943. $di->getDb()->replace_document((int) $se_ref['search_did'], $doc);
  4944. $di->getDb()->flush();
  4945. }
  4946. }
  4947. return true;
  4948. }
  4949. /**
  4950. * Sets the theme of the LP (local/remote) (and save).
  4951. *
  4952. * @param string $name Optional string giving the new theme of this learnpath
  4953. *
  4954. * @return bool Returns true if theme name is not empty
  4955. */
  4956. public function set_theme($name = '')
  4957. {
  4958. if ($this->debug > 0) {
  4959. error_log('In learnpath::set_theme()', 0);
  4960. }
  4961. $this->theme = $name;
  4962. $table = Database::get_course_table(TABLE_LP_MAIN);
  4963. $lp_id = $this->get_id();
  4964. $sql = "UPDATE $table
  4965. SET theme = '".Database::escape_string($this->theme)."'
  4966. WHERE iid = $lp_id";
  4967. if ($this->debug > 2) {
  4968. error_log('lp updated with new theme : '.$this->theme, 0);
  4969. }
  4970. Database::query($sql);
  4971. return true;
  4972. }
  4973. /**
  4974. * Sets the image of an LP (and save).
  4975. *
  4976. * @param string $name Optional string giving the new image of this learnpath
  4977. *
  4978. * @return bool Returns true if theme name is not empty
  4979. */
  4980. public function set_preview_image($name = '')
  4981. {
  4982. if ($this->debug > 0) {
  4983. error_log('In learnpath::set_preview_image()', 0);
  4984. }
  4985. $this->preview_image = $name;
  4986. $table = Database::get_course_table(TABLE_LP_MAIN);
  4987. $lp_id = $this->get_id();
  4988. $sql = "UPDATE $table SET
  4989. preview_image = '".Database::escape_string($this->preview_image)."'
  4990. WHERE iid = $lp_id";
  4991. if ($this->debug > 2) {
  4992. error_log('lp updated with new preview image : '.$this->preview_image, 0);
  4993. }
  4994. Database::query($sql);
  4995. return true;
  4996. }
  4997. /**
  4998. * Sets the author of a LP (and save).
  4999. *
  5000. * @param string $name Optional string giving the new author of this learnpath
  5001. *
  5002. * @return bool Returns true if author's name is not empty
  5003. */
  5004. public function set_author($name = '')
  5005. {
  5006. if ($this->debug > 0) {
  5007. error_log('In learnpath::set_author()', 0);
  5008. }
  5009. $this->author = $name;
  5010. $table = Database::get_course_table(TABLE_LP_MAIN);
  5011. $lp_id = $this->get_id();
  5012. $sql = "UPDATE $table SET author = '".Database::escape_string($name)."'
  5013. WHERE iid = $lp_id";
  5014. if ($this->debug > 2) {
  5015. error_log('lp updated with new preview author : '.$this->author, 0);
  5016. }
  5017. Database::query($sql);
  5018. return true;
  5019. }
  5020. /**
  5021. * Sets the hide_toc_frame parameter of a LP (and save).
  5022. *
  5023. * @param int $hide 1 if frame is hidden 0 then else
  5024. *
  5025. * @return bool Returns true if author's name is not empty
  5026. */
  5027. public function set_hide_toc_frame($hide)
  5028. {
  5029. if ($this->debug > 0) {
  5030. error_log('In learnpath::set_hide_toc_frame()', 0);
  5031. }
  5032. if (intval($hide) == $hide) {
  5033. $this->hide_toc_frame = $hide;
  5034. $table = Database::get_course_table(TABLE_LP_MAIN);
  5035. $lp_id = $this->get_id();
  5036. $sql = "UPDATE $table SET
  5037. hide_toc_frame = '".(int) $this->hide_toc_frame."'
  5038. WHERE iid = $lp_id";
  5039. if ($this->debug > 2) {
  5040. error_log('lp updated with new preview hide_toc_frame : '.$this->author, 0);
  5041. }
  5042. Database::query($sql);
  5043. return true;
  5044. } else {
  5045. return false;
  5046. }
  5047. }
  5048. /**
  5049. * Sets the prerequisite of a LP (and save).
  5050. *
  5051. * @param int $prerequisite integer giving the new prerequisite of this learnpath
  5052. *
  5053. * @return bool returns true if prerequisite is not empty
  5054. */
  5055. public function set_prerequisite($prerequisite)
  5056. {
  5057. if ($this->debug > 0) {
  5058. error_log('In learnpath::set_prerequisite()', 0);
  5059. }
  5060. $this->prerequisite = (int) $prerequisite;
  5061. $table = Database::get_course_table(TABLE_LP_MAIN);
  5062. $lp_id = $this->get_id();
  5063. $sql = "UPDATE $table SET prerequisite = '".$this->prerequisite."'
  5064. WHERE iid = $lp_id";
  5065. if ($this->debug > 2) {
  5066. error_log('lp updated with new preview requisite : '.$this->requisite, 0);
  5067. }
  5068. Database::query($sql);
  5069. return true;
  5070. }
  5071. /**
  5072. * Sets the location/proximity of the LP (local/remote) (and save).
  5073. *
  5074. * @param string $name Optional string giving the new location of this learnpath
  5075. *
  5076. * @return bool True on success / False on error
  5077. */
  5078. public function set_proximity($name = '')
  5079. {
  5080. if ($this->debug > 0) {
  5081. error_log('In learnpath::set_proximity()', 0);
  5082. }
  5083. if (empty($name)) {
  5084. return false;
  5085. }
  5086. $this->proximity = $name;
  5087. $table = Database::get_course_table(TABLE_LP_MAIN);
  5088. $lp_id = $this->get_id();
  5089. $sql = "UPDATE $table SET
  5090. content_local = '".Database::escape_string($name)."'
  5091. WHERE iid = $lp_id";
  5092. if ($this->debug > 2) {
  5093. error_log('lp updated with new proximity : '.$this->proximity, 0);
  5094. }
  5095. Database::query($sql);
  5096. return true;
  5097. }
  5098. /**
  5099. * Sets the previous item ID to a given ID. Generally, this should be set to the previous 'current' item.
  5100. *
  5101. * @param int $id DB ID of the item
  5102. */
  5103. public function set_previous_item($id)
  5104. {
  5105. if ($this->debug > 0) {
  5106. error_log('In learnpath::set_previous_item()', 0);
  5107. }
  5108. $this->last = $id;
  5109. }
  5110. /**
  5111. * Sets use_max_score.
  5112. *
  5113. * @param int $use_max_score Optional string giving the new location of this learnpath
  5114. *
  5115. * @return bool True on success / False on error
  5116. */
  5117. public function set_use_max_score($use_max_score = 1)
  5118. {
  5119. if ($this->debug > 0) {
  5120. error_log('In learnpath::set_use_max_score()', 0);
  5121. }
  5122. $use_max_score = (int) $use_max_score;
  5123. $this->use_max_score = $use_max_score;
  5124. $table = Database::get_course_table(TABLE_LP_MAIN);
  5125. $lp_id = $this->get_id();
  5126. $sql = "UPDATE $table SET
  5127. use_max_score = '".$this->use_max_score."'
  5128. WHERE iid = $lp_id";
  5129. if ($this->debug > 2) {
  5130. error_log('lp updated with new use_max_score : '.$this->use_max_score, 0);
  5131. }
  5132. Database::query($sql);
  5133. return true;
  5134. }
  5135. /**
  5136. * Sets and saves the expired_on date.
  5137. *
  5138. * @param string $expired_on Optional string giving the new author of this learnpath
  5139. *
  5140. * @throws \Doctrine\ORM\OptimisticLockException
  5141. *
  5142. * @return bool Returns true if author's name is not empty
  5143. */
  5144. public function set_expired_on($expired_on)
  5145. {
  5146. if ($this->debug > 0) {
  5147. error_log('In learnpath::set_expired_on()', 0);
  5148. }
  5149. $em = Database::getManager();
  5150. /** @var CLp $lp */
  5151. $lp = $em
  5152. ->getRepository('ChamiloCourseBundle:CLp')
  5153. ->findOneBy(
  5154. [
  5155. 'iid' => $this->get_id(),
  5156. ]
  5157. );
  5158. if (!$lp) {
  5159. return false;
  5160. }
  5161. $this->expired_on = !empty($expired_on) ? api_get_utc_datetime($expired_on, false, true) : null;
  5162. $lp->setExpiredOn($this->expired_on);
  5163. $em->persist($lp);
  5164. $em->flush();
  5165. if ($this->debug > 2) {
  5166. error_log('lp updated with new expired_on : '.$this->expired_on, 0);
  5167. }
  5168. return true;
  5169. }
  5170. /**
  5171. * Sets and saves the publicated_on date.
  5172. *
  5173. * @param string $publicated_on Optional string giving the new author of this learnpath
  5174. *
  5175. * @throws \Doctrine\ORM\OptimisticLockException
  5176. *
  5177. * @return bool Returns true if author's name is not empty
  5178. */
  5179. public function set_publicated_on($publicated_on)
  5180. {
  5181. if ($this->debug > 0) {
  5182. error_log('In learnpath::set_expired_on()', 0);
  5183. }
  5184. $em = Database::getManager();
  5185. /** @var CLp $lp */
  5186. $lp = $em
  5187. ->getRepository('ChamiloCourseBundle:CLp')
  5188. ->findOneBy(
  5189. [
  5190. 'iid' => $this->get_id(),
  5191. ]
  5192. );
  5193. if (!$lp) {
  5194. return false;
  5195. }
  5196. $this->publicated_on = !empty($publicated_on) ? api_get_utc_datetime($publicated_on, false, true) : null;
  5197. $lp->setPublicatedOn($this->publicated_on);
  5198. $em->persist($lp);
  5199. $em->flush();
  5200. if ($this->debug > 2) {
  5201. error_log('lp updated with new publicated_on : '.$this->publicated_on, 0);
  5202. }
  5203. return true;
  5204. }
  5205. /**
  5206. * Sets and saves the expired_on date.
  5207. *
  5208. * @return bool Returns true if author's name is not empty
  5209. */
  5210. public function set_modified_on()
  5211. {
  5212. if ($this->debug > 0) {
  5213. error_log('In learnpath::set_expired_on()', 0);
  5214. }
  5215. $this->modified_on = api_get_utc_datetime();
  5216. $table = Database::get_course_table(TABLE_LP_MAIN);
  5217. $lp_id = $this->get_id();
  5218. $sql = "UPDATE $table SET modified_on = '".$this->modified_on."'
  5219. WHERE iid = $lp_id";
  5220. if ($this->debug > 2) {
  5221. error_log('lp updated with new expired_on : '.$this->modified_on, 0);
  5222. }
  5223. Database::query($sql);
  5224. return true;
  5225. }
  5226. /**
  5227. * Sets the object's error message.
  5228. *
  5229. * @param string $error Error message. If empty, reinits the error string
  5230. */
  5231. public function set_error_msg($error = '')
  5232. {
  5233. if ($this->debug > 0) {
  5234. error_log('In learnpath::set_error_msg()', 0);
  5235. }
  5236. if (empty($error)) {
  5237. $this->error = '';
  5238. } else {
  5239. $this->error .= $error;
  5240. }
  5241. }
  5242. /**
  5243. * Launches the current item if not 'sco'
  5244. * (starts timer and make sure there is a record ready in the DB).
  5245. *
  5246. * @param bool $allow_new_attempt Whether to allow a new attempt or not
  5247. *
  5248. * @return bool
  5249. */
  5250. public function start_current_item($allow_new_attempt = false)
  5251. {
  5252. $debug = $this->debug;
  5253. if ($debug) {
  5254. error_log('In learnpath::start_current_item()');
  5255. error_log('current: '.$this->current);
  5256. }
  5257. if ($this->current != 0 && isset($this->items[$this->current]) && is_object($this->items[$this->current])) {
  5258. $type = $this->get_type();
  5259. $item_type = $this->items[$this->current]->get_type();
  5260. if (($type == 2 && $item_type != 'sco') ||
  5261. ($type == 3 && $item_type != 'au') ||
  5262. ($type == 1 && $item_type != TOOL_QUIZ && $item_type != TOOL_HOTPOTATOES)
  5263. ) {
  5264. if ($debug) {
  5265. error_log('item type: '.$item_type);
  5266. error_log('lp type: '.$type);
  5267. }
  5268. $this->items[$this->current]->open($allow_new_attempt);
  5269. $this->autocomplete_parents($this->current);
  5270. $prereq_check = $this->prerequisites_match($this->current);
  5271. if ($debug) {
  5272. error_log('start_current_item will save item with prereq: '.$prereq_check);
  5273. }
  5274. $this->items[$this->current]->save(false, $prereq_check);
  5275. }
  5276. // If sco, then it is supposed to have been updated by some other call.
  5277. if ($item_type == 'sco') {
  5278. $this->items[$this->current]->restart();
  5279. }
  5280. }
  5281. if ($debug) {
  5282. error_log('lp_view_session_id');
  5283. error_log($this->lp_view_session_id);
  5284. error_log('api session id');
  5285. error_log(api_get_session_id());
  5286. error_log('End of learnpath::start_current_item()');
  5287. }
  5288. return true;
  5289. }
  5290. /**
  5291. * Stops the processing and counters for the old item (as held in $this->last).
  5292. *
  5293. * @return bool True/False
  5294. */
  5295. public function stop_previous_item()
  5296. {
  5297. $debug = $this->debug;
  5298. if ($debug) {
  5299. error_log('In learnpath::stop_previous_item()', 0);
  5300. }
  5301. if ($this->last != 0 && $this->last != $this->current &&
  5302. isset($this->items[$this->last]) && is_object($this->items[$this->last])
  5303. ) {
  5304. if ($debug) {
  5305. error_log('In learnpath::stop_previous_item() - '.$this->last.' is object');
  5306. }
  5307. switch ($this->get_type()) {
  5308. case '3':
  5309. if ($this->items[$this->last]->get_type() != 'au') {
  5310. if ($debug) {
  5311. error_log('In learnpath::stop_previous_item() - '.$this->last.' in lp_type 3 is <> au');
  5312. }
  5313. $this->items[$this->last]->close();
  5314. } else {
  5315. if ($debug) {
  5316. error_log('In learnpath::stop_previous_item() - Item is an AU, saving is managed by AICC signals');
  5317. }
  5318. }
  5319. break;
  5320. case '2':
  5321. if ($this->items[$this->last]->get_type() != 'sco') {
  5322. if ($debug) {
  5323. error_log('In learnpath::stop_previous_item() - '.$this->last.' in lp_type 2 is <> sco');
  5324. }
  5325. $this->items[$this->last]->close();
  5326. } else {
  5327. if ($debug) {
  5328. error_log('In learnpath::stop_previous_item() - Item is a SCO, saving is managed by SCO signals');
  5329. }
  5330. }
  5331. break;
  5332. case '1':
  5333. default:
  5334. if ($debug) {
  5335. error_log('In learnpath::stop_previous_item() - '.$this->last.' in lp_type 1 is asset');
  5336. }
  5337. $this->items[$this->last]->close();
  5338. break;
  5339. }
  5340. } else {
  5341. if ($debug) {
  5342. error_log('In learnpath::stop_previous_item() - No previous element found, ignoring...');
  5343. }
  5344. return false;
  5345. }
  5346. return true;
  5347. }
  5348. /**
  5349. * Updates the default view mode from fullscreen to embedded and inversely.
  5350. *
  5351. * @return string The current default view mode ('fullscreen' or 'embedded')
  5352. */
  5353. public function update_default_view_mode()
  5354. {
  5355. if ($this->debug > 0) {
  5356. error_log('In learnpath::update_default_view_mode()', 0);
  5357. }
  5358. $table = Database::get_course_table(TABLE_LP_MAIN);
  5359. $sql = "SELECT * FROM $table
  5360. WHERE iid = ".$this->get_id();
  5361. $res = Database::query($sql);
  5362. if (Database::num_rows($res) > 0) {
  5363. $row = Database::fetch_array($res);
  5364. $default_view_mode = $row['default_view_mod'];
  5365. $view_mode = $default_view_mode;
  5366. switch ($default_view_mode) {
  5367. case 'fullscreen': // default with popup
  5368. $view_mode = 'embedded';
  5369. break;
  5370. case 'embedded': // default view with left menu
  5371. $view_mode = 'embedframe';
  5372. break;
  5373. case 'embedframe': //folded menu
  5374. $view_mode = 'impress';
  5375. break;
  5376. case 'impress':
  5377. $view_mode = 'fullscreen';
  5378. break;
  5379. }
  5380. $sql = "UPDATE $table SET default_view_mod = '$view_mode'
  5381. WHERE iid = ".$this->get_id();
  5382. Database::query($sql);
  5383. $this->mode = $view_mode;
  5384. return $view_mode;
  5385. } else {
  5386. if ($this->debug > 2) {
  5387. error_log('Problem in update_default_view() - could not find LP '.$this->get_id().' in DB', 0);
  5388. }
  5389. }
  5390. return -1;
  5391. }
  5392. /**
  5393. * Updates the default behaviour about auto-commiting SCORM updates.
  5394. *
  5395. * @return bool True if auto-commit has been set to 'on', false otherwise
  5396. */
  5397. public function update_default_scorm_commit()
  5398. {
  5399. if ($this->debug > 0) {
  5400. error_log('In learnpath::update_default_scorm_commit()', 0);
  5401. }
  5402. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5403. $sql = "SELECT * FROM $lp_table
  5404. WHERE iid = ".$this->get_id();
  5405. $res = Database::query($sql);
  5406. if (Database::num_rows($res) > 0) {
  5407. $row = Database::fetch_array($res);
  5408. $force = $row['force_commit'];
  5409. if ($force == 1) {
  5410. $force = 0;
  5411. $force_return = false;
  5412. } elseif ($force == 0) {
  5413. $force = 1;
  5414. $force_return = true;
  5415. }
  5416. $sql = "UPDATE $lp_table SET force_commit = $force
  5417. WHERE iid = ".$this->get_id();
  5418. Database::query($sql);
  5419. $this->force_commit = $force_return;
  5420. return $force_return;
  5421. } else {
  5422. if ($this->debug > 2) {
  5423. error_log('Problem in update_default_scorm_commit() - could not find LP '.$this->get_id().' in DB', 0);
  5424. }
  5425. }
  5426. return -1;
  5427. }
  5428. /**
  5429. * Updates the order of learning paths (goes through all of them by order and fills the gaps).
  5430. *
  5431. * @return bool True on success, false on failure
  5432. */
  5433. public function update_display_order()
  5434. {
  5435. $course_id = api_get_course_int_id();
  5436. $table = Database::get_course_table(TABLE_LP_MAIN);
  5437. $sql = "SELECT * FROM $table
  5438. WHERE c_id = $course_id
  5439. ORDER BY display_order";
  5440. $res = Database::query($sql);
  5441. if ($res === false) {
  5442. return false;
  5443. }
  5444. $num = Database::num_rows($res);
  5445. // First check the order is correct, globally (might be wrong because
  5446. // of versions < 1.8.4).
  5447. if ($num > 0) {
  5448. $i = 1;
  5449. while ($row = Database::fetch_array($res)) {
  5450. if ($row['display_order'] != $i) {
  5451. // If we find a gap in the order, we need to fix it.
  5452. $sql = "UPDATE $table SET display_order = $i
  5453. WHERE iid = ".$row['iid'];
  5454. Database::query($sql);
  5455. }
  5456. $i++;
  5457. }
  5458. }
  5459. return true;
  5460. }
  5461. /**
  5462. * Updates the "prevent_reinit" value that enables control on reinitialising items on second view.
  5463. *
  5464. * @return bool True if prevent_reinit has been set to 'on', false otherwise (or 1 or 0 in this case)
  5465. */
  5466. public function update_reinit()
  5467. {
  5468. if ($this->debug > 0) {
  5469. error_log('In learnpath::update_reinit()', 0);
  5470. }
  5471. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5472. $sql = "SELECT * FROM $lp_table
  5473. WHERE iid = ".$this->get_id();
  5474. $res = Database::query($sql);
  5475. if (Database::num_rows($res) > 0) {
  5476. $row = Database::fetch_array($res);
  5477. $force = $row['prevent_reinit'];
  5478. if ($force == 1) {
  5479. $force = 0;
  5480. } elseif ($force == 0) {
  5481. $force = 1;
  5482. }
  5483. $sql = "UPDATE $lp_table SET prevent_reinit = $force
  5484. WHERE iid = ".$this->get_id();
  5485. Database::query($sql);
  5486. $this->prevent_reinit = $force;
  5487. return $force;
  5488. } else {
  5489. if ($this->debug > 2) {
  5490. error_log('Problem in update_reinit() - could not find LP '.$this->get_id().' in DB', 0);
  5491. }
  5492. }
  5493. return -1;
  5494. }
  5495. /**
  5496. * Determine the attempt_mode thanks to prevent_reinit and seriousgame_mode db flag.
  5497. *
  5498. * @return string 'single', 'multi' or 'seriousgame'
  5499. *
  5500. * @author ndiechburg <noel@cblue.be>
  5501. */
  5502. public function get_attempt_mode()
  5503. {
  5504. //Set default value for seriousgame_mode
  5505. if (!isset($this->seriousgame_mode)) {
  5506. $this->seriousgame_mode = 0;
  5507. }
  5508. // Set default value for prevent_reinit
  5509. if (!isset($this->prevent_reinit)) {
  5510. $this->prevent_reinit = 1;
  5511. }
  5512. if ($this->seriousgame_mode == 1 && $this->prevent_reinit == 1) {
  5513. return 'seriousgame';
  5514. }
  5515. if ($this->seriousgame_mode == 0 && $this->prevent_reinit == 1) {
  5516. return 'single';
  5517. }
  5518. if ($this->seriousgame_mode == 0 && $this->prevent_reinit == 0) {
  5519. return 'multiple';
  5520. }
  5521. return 'single';
  5522. }
  5523. /**
  5524. * Register the attempt mode into db thanks to flags prevent_reinit and seriousgame_mode flags.
  5525. *
  5526. * @param string 'seriousgame', 'single' or 'multiple'
  5527. *
  5528. * @return bool
  5529. *
  5530. * @author ndiechburg <noel@cblue.be>
  5531. */
  5532. public function set_attempt_mode($mode)
  5533. {
  5534. switch ($mode) {
  5535. case 'seriousgame':
  5536. $sg_mode = 1;
  5537. $prevent_reinit = 1;
  5538. break;
  5539. case 'single':
  5540. $sg_mode = 0;
  5541. $prevent_reinit = 1;
  5542. break;
  5543. case 'multiple':
  5544. $sg_mode = 0;
  5545. $prevent_reinit = 0;
  5546. break;
  5547. default:
  5548. $sg_mode = 0;
  5549. $prevent_reinit = 0;
  5550. break;
  5551. }
  5552. $this->prevent_reinit = $prevent_reinit;
  5553. $this->seriousgame_mode = $sg_mode;
  5554. $table = Database::get_course_table(TABLE_LP_MAIN);
  5555. $sql = "UPDATE $table SET
  5556. prevent_reinit = $prevent_reinit ,
  5557. seriousgame_mode = $sg_mode
  5558. WHERE iid = ".$this->get_id();
  5559. $res = Database::query($sql);
  5560. if ($res) {
  5561. return true;
  5562. } else {
  5563. return false;
  5564. }
  5565. }
  5566. /**
  5567. * Switch between multiple attempt, single attempt or serious_game mode (only for scorm).
  5568. *
  5569. * @author ndiechburg <noel@cblue.be>
  5570. */
  5571. public function switch_attempt_mode()
  5572. {
  5573. if ($this->debug > 0) {
  5574. error_log('In learnpath::switch_attempt_mode()', 0);
  5575. }
  5576. $mode = $this->get_attempt_mode();
  5577. switch ($mode) {
  5578. case 'single':
  5579. $next_mode = 'multiple';
  5580. break;
  5581. case 'multiple':
  5582. $next_mode = 'seriousgame';
  5583. break;
  5584. case 'seriousgame':
  5585. $next_mode = 'single';
  5586. break;
  5587. default:
  5588. $next_mode = 'single';
  5589. break;
  5590. }
  5591. $this->set_attempt_mode($next_mode);
  5592. }
  5593. /**
  5594. * Switch the lp in ktm mode. This is a special scorm mode with unique attempt
  5595. * but possibility to do again a completed item.
  5596. *
  5597. * @return bool true if seriousgame_mode has been set to 1, false otherwise
  5598. *
  5599. * @author ndiechburg <noel@cblue.be>
  5600. */
  5601. public function set_seriousgame_mode()
  5602. {
  5603. if ($this->debug > 0) {
  5604. error_log('In learnpath::set_seriousgame_mode()', 0);
  5605. }
  5606. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5607. $sql = "SELECT * FROM $lp_table
  5608. WHERE iid = ".$this->get_id();
  5609. $res = Database::query($sql);
  5610. if (Database::num_rows($res) > 0) {
  5611. $row = Database::fetch_array($res);
  5612. $force = $row['seriousgame_mode'];
  5613. if ($force == 1) {
  5614. $force = 0;
  5615. } elseif ($force == 0) {
  5616. $force = 1;
  5617. }
  5618. $sql = "UPDATE $lp_table SET seriousgame_mode = $force
  5619. WHERE iid = ".$this->get_id();
  5620. Database::query($sql);
  5621. $this->seriousgame_mode = $force;
  5622. return $force;
  5623. } else {
  5624. if ($this->debug > 2) {
  5625. error_log('Problem in set_seriousgame_mode() - could not find LP '.$this->get_id().' in DB', 0);
  5626. }
  5627. }
  5628. return -1;
  5629. }
  5630. /**
  5631. * Updates the "scorm_debug" value that shows or hide the debug window.
  5632. *
  5633. * @return bool True if scorm_debug has been set to 'on', false otherwise (or 1 or 0 in this case)
  5634. */
  5635. public function update_scorm_debug()
  5636. {
  5637. if ($this->debug > 0) {
  5638. error_log('In learnpath::update_scorm_debug()', 0);
  5639. }
  5640. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5641. $sql = "SELECT * FROM $lp_table
  5642. WHERE iid = ".$this->get_id();
  5643. $res = Database::query($sql);
  5644. if (Database::num_rows($res) > 0) {
  5645. $row = Database::fetch_array($res);
  5646. $force = $row['debug'];
  5647. if ($force == 1) {
  5648. $force = 0;
  5649. } elseif ($force == 0) {
  5650. $force = 1;
  5651. }
  5652. $sql = "UPDATE $lp_table SET debug = $force
  5653. WHERE iid = ".$this->get_id();
  5654. Database::query($sql);
  5655. $this->scorm_debug = $force;
  5656. return $force;
  5657. } else {
  5658. if ($this->debug > 2) {
  5659. error_log('Problem in update_scorm_debug() - could not find LP '.$this->get_id().' in DB', 0);
  5660. }
  5661. }
  5662. return -1;
  5663. }
  5664. /**
  5665. * Function that makes a call to the function sort_tree_array and create_tree_array.
  5666. *
  5667. * @author Kevin Van Den Haute
  5668. *
  5669. * @param array
  5670. */
  5671. public function tree_array($array)
  5672. {
  5673. if ($this->debug > 1) {
  5674. error_log('In learnpath::tree_array()', 0);
  5675. }
  5676. $array = $this->sort_tree_array($array);
  5677. $this->create_tree_array($array);
  5678. }
  5679. /**
  5680. * Creates an array with the elements of the learning path tree in it.
  5681. *
  5682. * @author Kevin Van Den Haute
  5683. *
  5684. * @param array $array
  5685. * @param int $parent
  5686. * @param int $depth
  5687. * @param array $tmp
  5688. */
  5689. public function create_tree_array($array, $parent = 0, $depth = -1, $tmp = [])
  5690. {
  5691. if ($this->debug > 1) {
  5692. error_log('In learnpath::create_tree_array())', 0);
  5693. }
  5694. if (is_array($array)) {
  5695. for ($i = 0; $i < count($array); $i++) {
  5696. if ($array[$i]['parent_item_id'] == $parent) {
  5697. if (!in_array($array[$i]['parent_item_id'], $tmp)) {
  5698. $tmp[] = $array[$i]['parent_item_id'];
  5699. $depth++;
  5700. }
  5701. $preq = (empty($array[$i]['prerequisite']) ? '' : $array[$i]['prerequisite']);
  5702. $audio = isset($array[$i]['audio']) ? $array[$i]['audio'] : null;
  5703. $path = isset($array[$i]['path']) ? $array[$i]['path'] : null;
  5704. $prerequisiteMinScore = isset($array[$i]['prerequisite_min_score']) ? $array[$i]['prerequisite_min_score'] : null;
  5705. $prerequisiteMaxScore = isset($array[$i]['prerequisite_max_score']) ? $array[$i]['prerequisite_max_score'] : null;
  5706. $ref = isset($array[$i]['ref']) ? $array[$i]['ref'] : '';
  5707. $this->arrMenu[] = [
  5708. 'id' => $array[$i]['id'],
  5709. 'ref' => $ref,
  5710. 'item_type' => $array[$i]['item_type'],
  5711. 'title' => $array[$i]['title'],
  5712. 'path' => $path,
  5713. 'description' => $array[$i]['description'],
  5714. 'parent_item_id' => $array[$i]['parent_item_id'],
  5715. 'previous_item_id' => $array[$i]['previous_item_id'],
  5716. 'next_item_id' => $array[$i]['next_item_id'],
  5717. 'min_score' => $array[$i]['min_score'],
  5718. 'max_score' => $array[$i]['max_score'],
  5719. 'mastery_score' => $array[$i]['mastery_score'],
  5720. 'display_order' => $array[$i]['display_order'],
  5721. 'prerequisite' => $preq,
  5722. 'depth' => $depth,
  5723. 'audio' => $audio,
  5724. 'prerequisite_min_score' => $prerequisiteMinScore,
  5725. 'prerequisite_max_score' => $prerequisiteMaxScore,
  5726. ];
  5727. $this->create_tree_array($array, $array[$i]['id'], $depth, $tmp);
  5728. }
  5729. }
  5730. }
  5731. }
  5732. /**
  5733. * Sorts a multi dimensional array by parent id and display order.
  5734. *
  5735. * @author Kevin Van Den Haute
  5736. *
  5737. * @param array $array (array with al the learning path items in it)
  5738. *
  5739. * @return array
  5740. */
  5741. public function sort_tree_array($array)
  5742. {
  5743. foreach ($array as $key => $row) {
  5744. $parent[$key] = $row['parent_item_id'];
  5745. $position[$key] = $row['display_order'];
  5746. }
  5747. if (count($array) > 0) {
  5748. array_multisort($parent, SORT_ASC, $position, SORT_ASC, $array);
  5749. }
  5750. return $array;
  5751. }
  5752. /**
  5753. * Function that creates a html list of learning path items so that we can add audio files to them.
  5754. *
  5755. * @author Kevin Van Den Haute
  5756. *
  5757. * @return string
  5758. */
  5759. public function overview()
  5760. {
  5761. if ($this->debug > 0) {
  5762. error_log('In learnpath::overview()', 0);
  5763. }
  5764. $return = '';
  5765. $update_audio = isset($_GET['updateaudio']) ? $_GET['updateaudio'] : null;
  5766. // we need to start a form when we want to update all the mp3 files
  5767. if ($update_audio == 'true') {
  5768. $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">';
  5769. }
  5770. $return .= '<div id="message"></div>';
  5771. if (count($this->items) == 0) {
  5772. $return .= Display::return_message(get_lang('YouShouldAddItemsBeforeAttachAudio'), 'normal');
  5773. } else {
  5774. $return_audio = '<table class="data_table">';
  5775. $return_audio .= '<tr>';
  5776. $return_audio .= '<th width="40%">'.get_lang('Title').'</th>';
  5777. $return_audio .= '<th>'.get_lang('Audio').'</th>';
  5778. $return_audio .= '</tr>';
  5779. if ($update_audio != 'true') {
  5780. $return .= '<div class="col-md-12">';
  5781. $return .= self::return_new_tree($update_audio);
  5782. $return .= '</div>';
  5783. $return .= Display::div(
  5784. Display::url(get_lang('Save'), '#', ['id' => 'listSubmit', 'class' => 'btn btn-primary']),
  5785. ['style' => 'float:left; margin-top:15px;width:100%']
  5786. );
  5787. } else {
  5788. $return_audio .= self::return_new_tree($update_audio);
  5789. $return .= $return_audio.'</table>';
  5790. }
  5791. // We need to close the form when we are updating the mp3 files.
  5792. if ($update_audio == 'true') {
  5793. $return .= '<div class="footer-audio">';
  5794. $return .= Display::button(
  5795. 'save_audio',
  5796. '<em class="fa fa-file-audio-o"></em> '.get_lang('SaveAudioAndOrganization'),
  5797. ['class' => 'btn btn-primary', 'type' => 'submit']
  5798. );
  5799. $return .= '</div>';
  5800. }
  5801. }
  5802. // We need to close the form when we are updating the mp3 files.
  5803. if ($update_audio == 'true' && isset($this->arrMenu) && count($this->arrMenu) != 0) {
  5804. $return .= '</form>';
  5805. }
  5806. return $return;
  5807. }
  5808. /**
  5809. * @param string $update_audio
  5810. *
  5811. * @return array
  5812. */
  5813. public function processBuildMenuElements($update_audio = 'false')
  5814. {
  5815. $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
  5816. $course_id = api_get_course_int_id();
  5817. $table = Database::get_course_table(TABLE_LP_ITEM);
  5818. $sql = "SELECT * FROM $table
  5819. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  5820. $result = Database::query($sql);
  5821. $arrLP = [];
  5822. while ($row = Database::fetch_array($result)) {
  5823. $arrLP[] = [
  5824. 'id' => $row['iid'],
  5825. 'item_type' => $row['item_type'],
  5826. 'title' => Security::remove_XSS($row['title']),
  5827. 'path' => $row['path'],
  5828. 'description' => Security::remove_XSS($row['description']),
  5829. 'parent_item_id' => $row['parent_item_id'],
  5830. 'previous_item_id' => $row['previous_item_id'],
  5831. 'next_item_id' => $row['next_item_id'],
  5832. 'max_score' => $row['max_score'],
  5833. 'min_score' => $row['min_score'],
  5834. 'mastery_score' => $row['mastery_score'],
  5835. 'prerequisite' => $row['prerequisite'],
  5836. 'display_order' => $row['display_order'],
  5837. 'audio' => $row['audio'],
  5838. 'prerequisite_max_score' => $row['prerequisite_max_score'],
  5839. 'prerequisite_min_score' => $row['prerequisite_min_score'],
  5840. ];
  5841. }
  5842. $this->tree_array($arrLP);
  5843. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  5844. unset($this->arrMenu);
  5845. $default_data = null;
  5846. $default_content = null;
  5847. $elements = [];
  5848. $return_audio = null;
  5849. $iconPath = api_get_path(SYS_CODE_PATH).'img/';
  5850. $mainUrl = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq();
  5851. for ($i = 0; $i < count($arrLP); $i++) {
  5852. $title = $arrLP[$i]['title'];
  5853. $title_cut = cut($arrLP[$i]['title'], self::MAX_LP_ITEM_TITLE_LENGTH);
  5854. // Link for the documents
  5855. if ($arrLP[$i]['item_type'] == 'document' || $arrLP[$i]['item_type'] == TOOL_READOUT_TEXT) {
  5856. $url = $mainUrl.'&action=view_item&mode=preview_document&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5857. $title_cut = Display::url(
  5858. $title_cut,
  5859. $url,
  5860. [
  5861. 'class' => 'ajax moved',
  5862. 'data-title' => $title,
  5863. 'title' => $title,
  5864. ]
  5865. );
  5866. }
  5867. // Detect if type is FINAL_ITEM to set path_id to SESSION
  5868. if ($arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM) {
  5869. Session::write('pathItem', $arrLP[$i]['path']);
  5870. }
  5871. if (($i % 2) == 0) {
  5872. $oddClass = 'row_odd';
  5873. } else {
  5874. $oddClass = 'row_even';
  5875. }
  5876. $return_audio .= '<tr id ="lp_item_'.$arrLP[$i]['id'].'" class="'.$oddClass.'">';
  5877. $icon_name = str_replace(' ', '', $arrLP[$i]['item_type']);
  5878. if (file_exists($iconPath.'lp_'.$icon_name.'.png')) {
  5879. $icon = Display::return_icon('lp_'.$icon_name.'.png');
  5880. } else {
  5881. if (file_exists($iconPath.'lp_'.$icon_name.'.gif')) {
  5882. $icon = Display::return_icon('lp_'.$icon_name.'.gif');
  5883. } else {
  5884. if ($arrLP[$i]['item_type'] === TOOL_LP_FINAL_ITEM) {
  5885. $icon = Display::return_icon('certificate.png');
  5886. } else {
  5887. $icon = Display::return_icon('folder_document.gif');
  5888. }
  5889. }
  5890. }
  5891. // The audio column.
  5892. $return_audio .= '<td align="left" style="padding-left:10px;">';
  5893. $audio = '';
  5894. if (!$update_audio || $update_audio != 'true') {
  5895. if (empty($arrLP[$i]['audio'])) {
  5896. $audio .= '';
  5897. }
  5898. } else {
  5899. $types = self::getChapterTypes();
  5900. if (!in_array($arrLP[$i]['item_type'], $types)) {
  5901. $audio .= '<input type="file" name="mp3file'.$arrLP[$i]['id'].'" id="mp3file" />';
  5902. if (!empty($arrLP[$i]['audio'])) {
  5903. $audio .= '<br />'.Security::remove_XSS($arrLP[$i]['audio']).'<br />
  5904. <input type="checkbox" name="removemp3'.$arrLP[$i]['id'].'" id="checkbox'.$arrLP[$i]['id'].'" />'.get_lang('RemoveAudio');
  5905. }
  5906. }
  5907. }
  5908. $return_audio .= Display::span($icon.' '.$title).
  5909. Display::tag(
  5910. 'td',
  5911. $audio,
  5912. ['style' => '']
  5913. );
  5914. $return_audio .= '</td>';
  5915. $move_icon = '';
  5916. $move_item_icon = '';
  5917. $edit_icon = '';
  5918. $delete_icon = '';
  5919. $audio_icon = '';
  5920. $prerequisities_icon = '';
  5921. $forumIcon = '';
  5922. $previewIcon = '';
  5923. $pluginCalendarIcon = '';
  5924. $pluginCalendar = api_get_plugin_setting('learning_calendar', 'enabled') === 'true';
  5925. $plugin = null;
  5926. if ($pluginCalendar) {
  5927. $plugin = LearningCalendarPlugin::create();
  5928. }
  5929. $pluginUrl = api_get_path(WEB_PLUGIN_PATH).'learning_calendar/start.php?';
  5930. if ($is_allowed_to_edit) {
  5931. if (!$update_audio || $update_audio != 'true') {
  5932. if ($arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM) {
  5933. $move_icon .= '<a class="moved" href="#">';
  5934. $move_icon .= Display::return_icon(
  5935. 'move_everywhere.png',
  5936. get_lang('Move'),
  5937. [],
  5938. ICON_SIZE_TINY
  5939. );
  5940. $move_icon .= '</a>';
  5941. }
  5942. }
  5943. // No edit for this item types
  5944. if (!in_array($arrLP[$i]['item_type'], ['sco', 'asset', 'final_item'])) {
  5945. if ($arrLP[$i]['item_type'] != 'dir') {
  5946. $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">';
  5947. $edit_icon .= Display::return_icon(
  5948. 'edit.png',
  5949. get_lang('LearnpathEditModule'),
  5950. [],
  5951. ICON_SIZE_TINY
  5952. );
  5953. $edit_icon .= '</a>';
  5954. if (!in_array($arrLP[$i]['item_type'], ['forum', 'thread'])) {
  5955. $forumThread = null;
  5956. if (isset($this->items[$arrLP[$i]['id']])) {
  5957. $forumThread = $this->items[$arrLP[$i]['id']]->getForumThread(
  5958. $this->course_int_id,
  5959. $this->lp_session_id
  5960. );
  5961. }
  5962. if ($forumThread) {
  5963. $forumIconUrl = $mainUrl.'&'.http_build_query([
  5964. 'action' => 'dissociate_forum',
  5965. 'id' => $arrLP[$i]['id'],
  5966. 'lp_id' => $this->lp_id,
  5967. ]);
  5968. $forumIcon = Display::url(
  5969. Display::return_icon(
  5970. 'forum.png',
  5971. get_lang('DissociateForumToLPItem'),
  5972. [],
  5973. ICON_SIZE_TINY
  5974. ),
  5975. $forumIconUrl,
  5976. ['class' => 'btn btn-default lp-btn-dissociate-forum']
  5977. );
  5978. } else {
  5979. $forumIconUrl = $mainUrl.'&'.http_build_query([
  5980. 'action' => 'create_forum',
  5981. 'id' => $arrLP[$i]['id'],
  5982. 'lp_id' => $this->lp_id,
  5983. ]);
  5984. $forumIcon = Display::url(
  5985. Display::return_icon(
  5986. 'forum.png',
  5987. get_lang('AssociateForumToLPItem'),
  5988. [],
  5989. ICON_SIZE_TINY
  5990. ),
  5991. $forumIconUrl,
  5992. ['class' => 'btn btn-default lp-btn-associate-forum']
  5993. );
  5994. }
  5995. }
  5996. } else {
  5997. $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">';
  5998. $edit_icon .= Display::return_icon(
  5999. 'edit.png',
  6000. get_lang('LearnpathEditModule'),
  6001. [],
  6002. ICON_SIZE_TINY
  6003. );
  6004. $edit_icon .= '</a>';
  6005. }
  6006. } else {
  6007. if ($arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM) {
  6008. $edit_icon .= '<a href="'.$mainUrl.'&action=edit_item&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'" class="btn btn-default">';
  6009. $edit_icon .= Display::return_icon(
  6010. 'edit.png',
  6011. get_lang('Edit'),
  6012. [],
  6013. ICON_SIZE_TINY
  6014. );
  6015. $edit_icon .= '</a>';
  6016. }
  6017. }
  6018. if ($pluginCalendar) {
  6019. $pluginLink = $pluginUrl.
  6020. '&action=toggle_visibility&lp_item_id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  6021. $iconCalendar = Display::return_icon('agenda_na.png', get_lang('OneDay'), [], ICON_SIZE_TINY);
  6022. $itemInfo = $plugin->getItemVisibility($arrLP[$i]['id']);
  6023. if ($itemInfo && $itemInfo['value'] == 1) {
  6024. $iconCalendar = Display::return_icon('agenda.png', get_lang('OneDay'), [], ICON_SIZE_TINY);
  6025. }
  6026. $pluginCalendarIcon = Display::url(
  6027. $iconCalendar,
  6028. $pluginLink,
  6029. ['class' => 'btn btn-default']
  6030. );
  6031. }
  6032. $delete_icon .= ' <a
  6033. href="'.$mainUrl.'&action=delete_item&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'"
  6034. onclick="return confirmation(\''.addslashes($title).'\');"
  6035. class="btn btn-default">';
  6036. $delete_icon .= Display::return_icon(
  6037. 'delete.png',
  6038. get_lang('LearnpathDeleteModule'),
  6039. [],
  6040. ICON_SIZE_TINY
  6041. );
  6042. $delete_icon .= '</a>';
  6043. $url = $mainUrl.'&view=build&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  6044. $previewImage = Display::return_icon(
  6045. 'preview_view.png',
  6046. get_lang('Preview'),
  6047. [],
  6048. ICON_SIZE_TINY
  6049. );
  6050. switch ($arrLP[$i]['item_type']) {
  6051. case TOOL_DOCUMENT:
  6052. case TOOL_LP_FINAL_ITEM:
  6053. case TOOL_READOUT_TEXT:
  6054. $urlPreviewLink = $mainUrl.'&action=view_item&mode=preview_document&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  6055. $previewIcon = Display::url(
  6056. $previewImage,
  6057. $urlPreviewLink,
  6058. [
  6059. 'target' => '_blank',
  6060. 'class' => 'btn btn-default',
  6061. 'data-title' => $arrLP[$i]['title'],
  6062. 'title' => $arrLP[$i]['title'],
  6063. ]
  6064. );
  6065. break;
  6066. case TOOL_THREAD:
  6067. case TOOL_FORUM:
  6068. case TOOL_QUIZ:
  6069. case TOOL_STUDENTPUBLICATION:
  6070. case TOOL_LP_FINAL_ITEM:
  6071. case TOOL_LINK:
  6072. //$target = '';
  6073. //$class = 'btn btn-default ajax';
  6074. //if ($arrLP[$i]['item_type'] == TOOL_LINK) {
  6075. $class = 'btn btn-default';
  6076. $target = '_blank';
  6077. //}
  6078. $link = self::rl_get_resource_link_for_learnpath(
  6079. $this->course_int_id,
  6080. $this->lp_id,
  6081. $arrLP[$i]['id'],
  6082. 0
  6083. );
  6084. $previewIcon = Display::url(
  6085. $previewImage,
  6086. $link,
  6087. [
  6088. 'class' => $class,
  6089. 'data-title' => $arrLP[$i]['title'],
  6090. 'title' => $arrLP[$i]['title'],
  6091. 'target' => $target,
  6092. ]
  6093. );
  6094. break;
  6095. default:
  6096. $previewIcon = Display::url(
  6097. $previewImage,
  6098. $url.'&action=view_item',
  6099. ['class' => 'btn btn-default', 'target' => '_blank']
  6100. );
  6101. break;
  6102. }
  6103. if ($arrLP[$i]['item_type'] != 'dir') {
  6104. $prerequisities_icon = Display::url(
  6105. Display::return_icon(
  6106. 'accept.png',
  6107. get_lang('LearnpathPrerequisites'),
  6108. [],
  6109. ICON_SIZE_TINY
  6110. ),
  6111. $url.'&action=edit_item_prereq',
  6112. ['class' => 'btn btn-default']
  6113. );
  6114. if ($arrLP[$i]['item_type'] != 'final_item') {
  6115. $move_item_icon = Display::url(
  6116. Display::return_icon(
  6117. 'move.png',
  6118. get_lang('Move'),
  6119. [],
  6120. ICON_SIZE_TINY
  6121. ),
  6122. $url.'&action=move_item',
  6123. ['class' => 'btn btn-default']
  6124. );
  6125. }
  6126. $audio_icon = Display::url(
  6127. Display::return_icon(
  6128. 'audio.png',
  6129. get_lang('UplUpload'),
  6130. [],
  6131. ICON_SIZE_TINY
  6132. ),
  6133. $url.'&action=add_audio',
  6134. ['class' => 'btn btn-default']
  6135. );
  6136. }
  6137. }
  6138. if ($update_audio != 'true') {
  6139. $row = $move_icon.' '.$icon.
  6140. Display::span($title_cut).
  6141. Display::tag(
  6142. 'div',
  6143. "<div class=\"btn-group btn-group-xs\">
  6144. $previewIcon
  6145. $audio
  6146. $edit_icon
  6147. $pluginCalendarIcon
  6148. $forumIcon
  6149. $prerequisities_icon
  6150. $move_item_icon
  6151. $audio_icon
  6152. $delete_icon
  6153. </div>",
  6154. ['class' => 'btn-toolbar button_actions']
  6155. );
  6156. } else {
  6157. $row =
  6158. Display::span($title.$icon).
  6159. Display::span($audio, ['class' => 'button_actions']);
  6160. }
  6161. $parent_id = $arrLP[$i]['parent_item_id'];
  6162. $default_data[$arrLP[$i]['id']] = $row;
  6163. $default_content[$arrLP[$i]['id']] = $arrLP[$i];
  6164. if (empty($parent_id)) {
  6165. $elements[$arrLP[$i]['id']]['data'] = $row;
  6166. $elements[$arrLP[$i]['id']]['type'] = $arrLP[$i]['item_type'];
  6167. } else {
  6168. $parent_arrays = [];
  6169. if ($arrLP[$i]['depth'] > 1) {
  6170. //Getting list of parents
  6171. for ($j = 0; $j < $arrLP[$i]['depth']; $j++) {
  6172. foreach ($arrLP as $item) {
  6173. if ($item['id'] == $parent_id) {
  6174. if ($item['parent_item_id'] == 0) {
  6175. $parent_id = $item['id'];
  6176. break;
  6177. } else {
  6178. $parent_id = $item['parent_item_id'];
  6179. if (empty($parent_arrays)) {
  6180. $parent_arrays[] = intval($item['id']);
  6181. }
  6182. $parent_arrays[] = $parent_id;
  6183. break;
  6184. }
  6185. }
  6186. }
  6187. }
  6188. }
  6189. if (!empty($parent_arrays)) {
  6190. $parent_arrays = array_reverse($parent_arrays);
  6191. $val = '$elements';
  6192. $x = 0;
  6193. foreach ($parent_arrays as $item) {
  6194. if ($x != count($parent_arrays) - 1) {
  6195. $val .= '["'.$item.'"]["children"]';
  6196. } else {
  6197. $val .= '["'.$item.'"]["children"]';
  6198. }
  6199. $x++;
  6200. }
  6201. $val .= "";
  6202. $code_str = $val."[".$arrLP[$i]['id']."][\"load_data\"] = '".$arrLP[$i]['id']."' ; ";
  6203. eval($code_str);
  6204. } else {
  6205. $elements[$parent_id]['children'][$arrLP[$i]['id']]['data'] = $row;
  6206. $elements[$parent_id]['children'][$arrLP[$i]['id']]['type'] = $arrLP[$i]['item_type'];
  6207. }
  6208. }
  6209. }
  6210. return [
  6211. 'elements' => $elements,
  6212. 'default_data' => $default_data,
  6213. 'default_content' => $default_content,
  6214. 'return_audio' => $return_audio,
  6215. ];
  6216. }
  6217. /**
  6218. * @param string $updateAudio true/false strings
  6219. *
  6220. * @return string
  6221. */
  6222. public function returnLpItemList($updateAudio)
  6223. {
  6224. $result = $this->processBuildMenuElements($updateAudio);
  6225. $html = self::print_recursive(
  6226. $result['elements'],
  6227. $result['default_data'],
  6228. $result['default_content']
  6229. );
  6230. if (!empty($html)) {
  6231. $html .= Display::return_message(get_lang('DragAndDropAnElementHere'));
  6232. }
  6233. return $html;
  6234. }
  6235. /**
  6236. * @param string $update_audio
  6237. * @param bool $drop_element_here
  6238. *
  6239. * @return string
  6240. */
  6241. public function return_new_tree($update_audio = 'false', $drop_element_here = false)
  6242. {
  6243. $return = '';
  6244. $result = $this->processBuildMenuElements($update_audio);
  6245. $list = '<ul id="lp_item_list">';
  6246. $tree = $this->print_recursive(
  6247. $result['elements'],
  6248. $result['default_data'],
  6249. $result['default_content']
  6250. );
  6251. if (!empty($tree)) {
  6252. $list .= $tree;
  6253. } else {
  6254. if ($drop_element_here) {
  6255. $list .= Display::return_message(get_lang('DragAndDropAnElementHere'));
  6256. }
  6257. }
  6258. $list .= '</ul>';
  6259. $return .= Display::panelCollapse(
  6260. $this->name,
  6261. $list,
  6262. 'scorm-list',
  6263. null,
  6264. 'scorm-list-accordion',
  6265. 'scorm-list-collapse'
  6266. );
  6267. if ($update_audio === 'true') {
  6268. $return = $result['return_audio'];
  6269. }
  6270. return $return;
  6271. }
  6272. /**
  6273. * @param array $elements
  6274. * @param array $default_data
  6275. * @param array $default_content
  6276. *
  6277. * @return string
  6278. */
  6279. public function print_recursive($elements, $default_data, $default_content)
  6280. {
  6281. $return = '';
  6282. foreach ($elements as $key => $item) {
  6283. if (isset($item['load_data']) || empty($item['data'])) {
  6284. $item['data'] = $default_data[$item['load_data']];
  6285. $item['type'] = $default_content[$item['load_data']]['item_type'];
  6286. }
  6287. $sub_list = '';
  6288. if (isset($item['type']) && $item['type'] == 'dir') {
  6289. // empty value
  6290. $sub_list = Display::tag('li', '', ['class' => 'sub_item empty']);
  6291. }
  6292. if (empty($item['children'])) {
  6293. $sub_list = Display::tag('ul', $sub_list, ['id' => 'UL_'.$key, 'class' => 'record li_container']);
  6294. $active = null;
  6295. if (isset($_REQUEST['id']) && $key == $_REQUEST['id']) {
  6296. $active = 'active';
  6297. }
  6298. $return .= Display::tag(
  6299. 'li',
  6300. Display::div($item['data'], ['class' => "item_data $active"]).$sub_list,
  6301. ['id' => $key, 'class' => 'record li_container']
  6302. );
  6303. } else {
  6304. // Sections
  6305. $data = '';
  6306. if (isset($item['children'])) {
  6307. $data = self::print_recursive($item['children'], $default_data, $default_content);
  6308. }
  6309. $sub_list = Display::tag('ul', $sub_list.$data, ['id' => 'UL_'.$key, 'class' => 'record li_container']);
  6310. $return .= Display::tag(
  6311. 'li',
  6312. Display::div($item['data'], ['class' => 'item_data']).$sub_list,
  6313. ['id' => $key, 'class' => 'record li_container']
  6314. );
  6315. }
  6316. }
  6317. return $return;
  6318. }
  6319. /**
  6320. * This function builds the action menu.
  6321. *
  6322. * @param bool $returnContent Optional
  6323. * @param bool $showRequirementButtons Optional. Allow show the requirements button
  6324. * @param bool $isConfigPage Optional. If is the config page, show the edit button
  6325. * @param bool $allowExpand Optional. Allow show the expand/contract button
  6326. *
  6327. * @return string
  6328. */
  6329. public function build_action_menu(
  6330. $returnContent = false,
  6331. $showRequirementButtons = true,
  6332. $isConfigPage = false,
  6333. $allowExpand = true
  6334. ) {
  6335. $actionsLeft = '';
  6336. $actionsRight = '';
  6337. $actionsLeft .= Display::url(
  6338. Display::return_icon(
  6339. 'back.png',
  6340. get_lang('ReturnToLearningPaths'),
  6341. '',
  6342. ICON_SIZE_MEDIUM
  6343. ),
  6344. 'lp_controller.php?'.api_get_cidreq()
  6345. );
  6346. $actionsLeft .= Display::url(
  6347. Display::return_icon(
  6348. 'preview_view.png',
  6349. get_lang('Preview'),
  6350. '',
  6351. ICON_SIZE_MEDIUM
  6352. ),
  6353. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6354. 'action' => 'view',
  6355. 'lp_id' => $this->lp_id,
  6356. 'isStudentView' => 'true',
  6357. ])
  6358. );
  6359. $actionsLeft .= Display::url(
  6360. Display::return_icon(
  6361. 'upload_audio.png',
  6362. get_lang('UpdateAllAudioFragments'),
  6363. '',
  6364. ICON_SIZE_MEDIUM
  6365. ),
  6366. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6367. 'action' => 'admin_view',
  6368. 'lp_id' => $this->lp_id,
  6369. 'updateaudio' => 'true',
  6370. ])
  6371. );
  6372. if (!$isConfigPage) {
  6373. $actionsLeft .= Display::url(
  6374. Display::return_icon(
  6375. 'settings.png',
  6376. get_lang('CourseSettings'),
  6377. '',
  6378. ICON_SIZE_MEDIUM
  6379. ),
  6380. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6381. 'action' => 'edit',
  6382. 'lp_id' => $this->lp_id,
  6383. ])
  6384. );
  6385. } else {
  6386. $actionsLeft .= Display::url(
  6387. Display::return_icon(
  6388. 'edit.png',
  6389. get_lang('Edit'),
  6390. '',
  6391. ICON_SIZE_MEDIUM
  6392. ),
  6393. 'lp_controller.php?'.http_build_query([
  6394. 'action' => 'build',
  6395. 'lp_id' => $this->lp_id,
  6396. ]).'&'.api_get_cidreq()
  6397. );
  6398. }
  6399. if ($allowExpand) {
  6400. $actionsLeft .= Display::url(
  6401. Display::return_icon(
  6402. 'expand.png',
  6403. get_lang('Expand'),
  6404. ['id' => 'expand'],
  6405. ICON_SIZE_MEDIUM
  6406. ).
  6407. Display::return_icon(
  6408. 'contract.png',
  6409. get_lang('Collapse'),
  6410. ['id' => 'contract', 'class' => 'hide'],
  6411. ICON_SIZE_MEDIUM
  6412. ),
  6413. '#',
  6414. ['role' => 'button', 'id' => 'hide_bar_template']
  6415. );
  6416. }
  6417. if ($showRequirementButtons) {
  6418. $buttons = [
  6419. [
  6420. 'title' => get_lang('SetPrerequisiteForEachItem'),
  6421. 'href' => 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6422. 'action' => 'set_previous_step_as_prerequisite',
  6423. 'lp_id' => $this->lp_id,
  6424. ]),
  6425. ],
  6426. [
  6427. 'title' => get_lang('ClearAllPrerequisites'),
  6428. 'href' => 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6429. 'action' => 'clear_prerequisites',
  6430. 'lp_id' => $this->lp_id,
  6431. ]),
  6432. ],
  6433. ];
  6434. $actionsRight = Display::groupButtonWithDropDown(
  6435. get_lang('PrerequisitesOptions'),
  6436. $buttons,
  6437. true
  6438. );
  6439. }
  6440. $toolbar = Display::toolbarAction(
  6441. 'actions-lp-controller',
  6442. [$actionsLeft, $actionsRight]
  6443. );
  6444. if ($returnContent) {
  6445. return $toolbar;
  6446. }
  6447. echo $toolbar;
  6448. }
  6449. /**
  6450. * Creates the default learning path folder.
  6451. *
  6452. * @param array $course
  6453. * @param int $creatorId
  6454. *
  6455. * @return bool
  6456. */
  6457. public static function generate_learning_path_folder($course, $creatorId = 0)
  6458. {
  6459. // Creating learning_path folder
  6460. $dir = '/learning_path';
  6461. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document';
  6462. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6463. $folder = false;
  6464. if (!is_dir($filepath.'/'.$dir)) {
  6465. $folderData = create_unexisting_directory(
  6466. $course,
  6467. $creatorId,
  6468. 0,
  6469. null,
  6470. 0,
  6471. $filepath,
  6472. $dir,
  6473. get_lang('LearningPaths'),
  6474. 0
  6475. );
  6476. if (!empty($folderData)) {
  6477. $folder = true;
  6478. }
  6479. } else {
  6480. $folder = true;
  6481. }
  6482. return $folder;
  6483. }
  6484. /**
  6485. * @param array $course
  6486. * @param string $lp_name
  6487. * @param int $creatorId
  6488. *
  6489. * @return array
  6490. */
  6491. public function generate_lp_folder($course, $lp_name = '', $creatorId = 0)
  6492. {
  6493. $filepath = '';
  6494. $dir = '/learning_path/';
  6495. if (empty($lp_name)) {
  6496. $lp_name = $this->name;
  6497. }
  6498. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6499. $folder = self::generate_learning_path_folder($course, $creatorId);
  6500. // Limits title size
  6501. $title = api_substr(api_replace_dangerous_char($lp_name), 0, 80);
  6502. $dir = $dir.$title;
  6503. // Creating LP folder
  6504. $documentId = null;
  6505. if ($folder) {
  6506. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document';
  6507. if (!is_dir($filepath.'/'.$dir)) {
  6508. $folderData = create_unexisting_directory(
  6509. $course,
  6510. $creatorId,
  6511. 0,
  6512. 0,
  6513. 0,
  6514. $filepath,
  6515. $dir,
  6516. $lp_name
  6517. );
  6518. if (!empty($folderData)) {
  6519. $folder = true;
  6520. }
  6521. $documentId = $folderData['id'];
  6522. } else {
  6523. $folder = true;
  6524. }
  6525. $dir = $dir.'/';
  6526. if ($folder) {
  6527. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document'.$dir;
  6528. }
  6529. }
  6530. if (empty($documentId)) {
  6531. $dir = api_remove_trailing_slash($dir);
  6532. $documentId = DocumentManager::get_document_id($course, $dir, 0);
  6533. }
  6534. $array = [
  6535. 'dir' => $dir,
  6536. 'filepath' => $filepath,
  6537. 'folder' => $folder,
  6538. 'id' => $documentId,
  6539. ];
  6540. return $array;
  6541. }
  6542. /**
  6543. * Create a new document //still needs some finetuning.
  6544. *
  6545. * @param array $courseInfo
  6546. * @param string $content
  6547. * @param string $title
  6548. * @param string $extension
  6549. * @param int $parentId
  6550. * @param int $creatorId creator id
  6551. *
  6552. * @return int
  6553. */
  6554. public function create_document(
  6555. $courseInfo,
  6556. $content = '',
  6557. $title = '',
  6558. $extension = 'html',
  6559. $parentId = 0,
  6560. $creatorId = 0
  6561. ) {
  6562. if (!empty($courseInfo)) {
  6563. $course_id = $courseInfo['real_id'];
  6564. } else {
  6565. $course_id = api_get_course_int_id();
  6566. }
  6567. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6568. $sessionId = api_get_session_id();
  6569. // Generates folder
  6570. $result = $this->generate_lp_folder($courseInfo);
  6571. $dir = $result['dir'];
  6572. if (empty($parentId) || $parentId == '/') {
  6573. $postDir = isset($_POST['dir']) ? $_POST['dir'] : $dir;
  6574. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir; // Please, do not modify this dirname formatting.
  6575. if ($parentId === '/') {
  6576. $dir = '/';
  6577. }
  6578. // Please, do not modify this dirname formatting.
  6579. if (strstr($dir, '..')) {
  6580. $dir = '/';
  6581. }
  6582. if (!empty($dir[0]) && $dir[0] == '.') {
  6583. $dir = substr($dir, 1);
  6584. }
  6585. if (!empty($dir[0]) && $dir[0] != '/') {
  6586. $dir = '/'.$dir;
  6587. }
  6588. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  6589. $dir .= '/';
  6590. }
  6591. } else {
  6592. $parentInfo = DocumentManager::get_document_data_by_id(
  6593. $parentId,
  6594. $courseInfo['code']
  6595. );
  6596. if (!empty($parentInfo)) {
  6597. $dir = $parentInfo['path'].'/';
  6598. }
  6599. }
  6600. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  6601. if (!is_dir($filepath)) {
  6602. $dir = '/';
  6603. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  6604. }
  6605. // stripslashes() before calling api_replace_dangerous_char() because $_POST['title']
  6606. // is already escaped twice when it gets here.
  6607. $originalTitle = !empty($title) ? $title : $_POST['title'];
  6608. if (!empty($title)) {
  6609. $title = api_replace_dangerous_char(stripslashes($title));
  6610. } else {
  6611. $title = api_replace_dangerous_char(stripslashes($_POST['title']));
  6612. }
  6613. $title = disable_dangerous_file($title);
  6614. $filename = $title;
  6615. $content = !empty($content) ? $content : $_POST['content_lp'];
  6616. $tmp_filename = $filename;
  6617. $i = 0;
  6618. while (file_exists($filepath.$tmp_filename.'.'.$extension)) {
  6619. $tmp_filename = $filename.'_'.++$i;
  6620. }
  6621. $filename = $tmp_filename.'.'.$extension;
  6622. if ($extension == 'html') {
  6623. $content = stripslashes($content);
  6624. $content = str_replace(
  6625. api_get_path(WEB_COURSE_PATH),
  6626. api_get_path(REL_PATH).'courses/',
  6627. $content
  6628. );
  6629. // Change the path of mp3 to absolute.
  6630. // The first regexp deals with :// urls.
  6631. $content = preg_replace(
  6632. "|(flashvars=\"file=)([^:/]+)/|",
  6633. "$1".api_get_path(
  6634. REL_COURSE_PATH
  6635. ).$courseInfo['path'].'/document/',
  6636. $content
  6637. );
  6638. // The second regexp deals with audio/ urls.
  6639. $content = preg_replace(
  6640. "|(flashvars=\"file=)([^/]+)/|",
  6641. "$1".api_get_path(
  6642. REL_COURSE_PATH
  6643. ).$courseInfo['path'].'/document/$2/',
  6644. $content
  6645. );
  6646. // For flv player: To prevent edition problem with firefox,
  6647. // we have to use a strange tip (don't blame me please).
  6648. $content = str_replace(
  6649. '</body>',
  6650. '<style type="text/css">body{}</style></body>',
  6651. $content
  6652. );
  6653. }
  6654. if (!file_exists($filepath.$filename)) {
  6655. if ($fp = @fopen($filepath.$filename, 'w')) {
  6656. fputs($fp, $content);
  6657. fclose($fp);
  6658. $file_size = filesize($filepath.$filename);
  6659. $save_file_path = $dir.$filename;
  6660. $document_id = add_document(
  6661. $courseInfo,
  6662. $save_file_path,
  6663. 'file',
  6664. $file_size,
  6665. $tmp_filename,
  6666. '',
  6667. 0, //readonly
  6668. true,
  6669. null,
  6670. $sessionId,
  6671. $creatorId
  6672. );
  6673. if ($document_id) {
  6674. api_item_property_update(
  6675. $courseInfo,
  6676. TOOL_DOCUMENT,
  6677. $document_id,
  6678. 'DocumentAdded',
  6679. $creatorId,
  6680. null,
  6681. null,
  6682. null,
  6683. null,
  6684. $sessionId
  6685. );
  6686. $new_comment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
  6687. $new_title = $originalTitle;
  6688. if ($new_comment || $new_title) {
  6689. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6690. $ct = '';
  6691. if ($new_comment) {
  6692. $ct .= ", comment='".Database::escape_string($new_comment)."'";
  6693. }
  6694. if ($new_title) {
  6695. $ct .= ", title='".Database::escape_string($new_title)."' ";
  6696. }
  6697. $sql = "UPDATE ".$tbl_doc." SET ".substr($ct, 1)."
  6698. WHERE c_id = ".$course_id." AND id = ".$document_id;
  6699. Database::query($sql);
  6700. }
  6701. }
  6702. return $document_id;
  6703. }
  6704. }
  6705. }
  6706. /**
  6707. * Edit a document based on $_POST and $_GET parameters 'dir' and 'path'.
  6708. *
  6709. * @param array $_course array
  6710. */
  6711. public function edit_document($_course)
  6712. {
  6713. $course_id = api_get_course_int_id();
  6714. $urlAppend = api_get_configuration_value('url_append');
  6715. // Please, do not modify this dirname formatting.
  6716. $postDir = isset($_POST['dir']) ? $_POST['dir'] : '';
  6717. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir;
  6718. if (strstr($dir, '..')) {
  6719. $dir = '/';
  6720. }
  6721. if (isset($dir[0]) && $dir[0] == '.') {
  6722. $dir = substr($dir, 1);
  6723. }
  6724. if (isset($dir[0]) && $dir[0] != '/') {
  6725. $dir = '/'.$dir;
  6726. }
  6727. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  6728. $dir .= '/';
  6729. }
  6730. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.$dir;
  6731. if (!is_dir($filepath)) {
  6732. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  6733. }
  6734. $table_doc = Database::get_course_table(TABLE_DOCUMENT);
  6735. if (isset($_POST['path']) && !empty($_POST['path'])) {
  6736. $document_id = (int) $_POST['path'];
  6737. $documentInfo = DocumentManager::get_document_data_by_id($document_id, api_get_course_id(), false, null, true);
  6738. if (empty($documentInfo)) {
  6739. // Try with iid
  6740. $table = Database::get_course_table(TABLE_DOCUMENT);
  6741. $sql = "SELECT id, path FROM $table
  6742. WHERE c_id = $course_id AND iid = $document_id AND path NOT LIKE '%_DELETED_%' ";
  6743. $res_doc = Database::query($sql);
  6744. $row = Database::fetch_array($res_doc);
  6745. if ($row) {
  6746. $document_id = $row['id'];
  6747. $documentPath = $row['path'];
  6748. }
  6749. } else {
  6750. $documentPath = $documentInfo['path'];
  6751. }
  6752. $content = stripslashes($_POST['content_lp']);
  6753. $file = $filepath.$documentPath;
  6754. if (!file_exists($file)) {
  6755. return false;
  6756. }
  6757. if ($fp = @fopen($file, 'w')) {
  6758. $content = str_replace(
  6759. api_get_path(WEB_COURSE_PATH),
  6760. $urlAppend.api_get_path(REL_COURSE_PATH),
  6761. $content
  6762. );
  6763. // Change the path of mp3 to absolute.
  6764. // The first regexp deals with :// urls.
  6765. $content = preg_replace(
  6766. "|(flashvars=\"file=)([^:/]+)/|",
  6767. "$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/',
  6768. $content
  6769. );
  6770. // The second regexp deals with audio/ urls.
  6771. $content = preg_replace(
  6772. "|(flashvars=\"file=)([^:/]+)/|",
  6773. "$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/$2/',
  6774. $content
  6775. );
  6776. fputs($fp, $content);
  6777. fclose($fp);
  6778. $sql = "UPDATE $table_doc SET
  6779. title='".Database::escape_string($_POST['title'])."'
  6780. WHERE c_id = $course_id AND id = ".$document_id;
  6781. Database::query($sql);
  6782. }
  6783. }
  6784. }
  6785. /**
  6786. * Displays the selected item, with a panel for manipulating the item.
  6787. *
  6788. * @param int $item_id
  6789. * @param string $msg
  6790. * @param bool $show_actions
  6791. *
  6792. * @return string
  6793. */
  6794. public function display_item($item_id, $msg = null, $show_actions = true)
  6795. {
  6796. $course_id = api_get_course_int_id();
  6797. $return = '';
  6798. if (is_numeric($item_id)) {
  6799. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  6800. $sql = "SELECT lp.* FROM $tbl_lp_item as lp
  6801. WHERE lp.iid = ".intval($item_id);
  6802. $result = Database::query($sql);
  6803. while ($row = Database::fetch_array($result, 'ASSOC')) {
  6804. $_SESSION['parent_item_id'] = $row['item_type'] == 'dir' ? $item_id : 0;
  6805. // Prevents wrong parent selection for document, see Bug#1251.
  6806. if ($row['item_type'] != 'dir') {
  6807. $_SESSION['parent_item_id'] = $row['parent_item_id'];
  6808. }
  6809. if ($show_actions) {
  6810. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6811. }
  6812. $return .= '<div style="padding:10px;">';
  6813. if ($msg != '') {
  6814. $return .= $msg;
  6815. }
  6816. $return .= '<h3>'.$row['title'].'</h3>';
  6817. switch ($row['item_type']) {
  6818. case TOOL_THREAD:
  6819. $link = $this->rl_get_resource_link_for_learnpath(
  6820. $course_id,
  6821. $row['lp_id'],
  6822. $item_id,
  6823. 0
  6824. );
  6825. $return .= Display::url(
  6826. get_lang('GoToThread'),
  6827. $link,
  6828. ['class' => 'btn btn-primary']
  6829. );
  6830. break;
  6831. case TOOL_FORUM:
  6832. $return .= Display::url(
  6833. get_lang('GoToForum'),
  6834. api_get_path(WEB_CODE_PATH).'forum/viewforum.php?'.api_get_cidreq().'&forum='.$row['path'],
  6835. ['class' => 'btn btn-primary']
  6836. );
  6837. break;
  6838. case TOOL_QUIZ:
  6839. if (!empty($row['path'])) {
  6840. $exercise = new Exercise();
  6841. $exercise->read($row['path']);
  6842. $return .= $exercise->description.'<br />';
  6843. $return .= Display::url(
  6844. get_lang('GoToExercise'),
  6845. api_get_path(WEB_CODE_PATH).'exercise/overview.php?'.api_get_cidreq().'&exerciseId='.$exercise->id,
  6846. ['class' => 'btn btn-primary']
  6847. );
  6848. }
  6849. break;
  6850. case TOOL_LP_FINAL_ITEM:
  6851. $return .= $this->getSavedFinalItem();
  6852. break;
  6853. case TOOL_DOCUMENT:
  6854. case TOOL_READOUT_TEXT:
  6855. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6856. $sql_doc = "SELECT path FROM $tbl_doc
  6857. WHERE c_id = $course_id AND iid = ".intval($row['path']);
  6858. $result = Database::query($sql_doc);
  6859. $path_file = Database::result($result, 0, 0);
  6860. $path_parts = pathinfo($path_file);
  6861. // TODO: Correct the following naive comparisons.
  6862. if (in_array($path_parts['extension'], [
  6863. 'html',
  6864. 'txt',
  6865. 'png',
  6866. 'jpg',
  6867. 'JPG',
  6868. 'jpeg',
  6869. 'JPEG',
  6870. 'gif',
  6871. 'swf',
  6872. 'pdf',
  6873. 'htm',
  6874. ])) {
  6875. $return .= $this->display_document($row['path'], true, true);
  6876. }
  6877. break;
  6878. case TOOL_HOTPOTATOES:
  6879. $return .= $this->display_document($row['path'], false, true);
  6880. break;
  6881. }
  6882. $return .= '</div>';
  6883. }
  6884. }
  6885. return $return;
  6886. }
  6887. /**
  6888. * Shows the needed forms for editing a specific item.
  6889. *
  6890. * @param int $item_id
  6891. *
  6892. * @throws Exception
  6893. * @throws HTML_QuickForm_Error
  6894. *
  6895. * @return string
  6896. */
  6897. public function display_edit_item($item_id)
  6898. {
  6899. $course_id = api_get_course_int_id();
  6900. $return = '';
  6901. $item_id = (int) $item_id;
  6902. if (empty($item_id)) {
  6903. return '';
  6904. }
  6905. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  6906. $sql = "SELECT * FROM $tbl_lp_item
  6907. WHERE iid = ".$item_id;
  6908. $res = Database::query($sql);
  6909. $row = Database::fetch_array($res);
  6910. switch ($row['item_type']) {
  6911. case 'dir':
  6912. case 'asset':
  6913. case 'sco':
  6914. if (isset($_GET['view']) && $_GET['view'] == 'build') {
  6915. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6916. $return .= $this->display_item_form(
  6917. $row['item_type'],
  6918. get_lang('EditCurrentChapter').' :',
  6919. 'edit',
  6920. $item_id,
  6921. $row
  6922. );
  6923. } else {
  6924. $return .= $this->display_item_form(
  6925. $row['item_type'],
  6926. get_lang('EditCurrentChapter').' :',
  6927. 'edit_item',
  6928. $item_id,
  6929. $row
  6930. );
  6931. }
  6932. break;
  6933. case TOOL_DOCUMENT:
  6934. case TOOL_READOUT_TEXT:
  6935. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6936. $sql = "SELECT lp.*, doc.path as dir
  6937. FROM $tbl_lp_item as lp
  6938. LEFT JOIN $tbl_doc as doc
  6939. ON (doc.iid = lp.path AND lp.c_id = doc.c_id)
  6940. WHERE
  6941. doc.c_id = $course_id AND
  6942. lp.iid = ".$item_id;
  6943. $res_step = Database::query($sql);
  6944. $row_step = Database::fetch_array($res_step, 'ASSOC');
  6945. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6946. if ($row['item_type'] === TOOL_DOCUMENT) {
  6947. $return .= $this->display_document_form('edit', $item_id, $row_step);
  6948. }
  6949. if ($row['item_type'] === TOOL_READOUT_TEXT) {
  6950. $return .= $this->displayFrmReadOutText('edit', $item_id, $row_step);
  6951. }
  6952. break;
  6953. case TOOL_LINK:
  6954. $linkId = (int) $row['path'];
  6955. if (!empty($linkId)) {
  6956. $table = Database::get_course_table(TABLE_LINK);
  6957. $sql = 'SELECT url FROM '.$table.'
  6958. WHERE c_id = '.$course_id.' AND iid = '.$linkId;
  6959. $res_link = Database::query($sql);
  6960. $row_link = Database::fetch_array($res_link);
  6961. if (empty($row_link)) {
  6962. // Try with id
  6963. $sql = 'SELECT url FROM '.$table.'
  6964. WHERE c_id = '.$course_id.' AND id = '.$linkId;
  6965. $res_link = Database::query($sql);
  6966. $row_link = Database::fetch_array($res_link);
  6967. }
  6968. if (is_array($row_link)) {
  6969. $row['url'] = $row_link['url'];
  6970. }
  6971. }
  6972. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6973. $return .= $this->display_link_form('edit', $item_id, $row);
  6974. break;
  6975. case TOOL_LP_FINAL_ITEM:
  6976. Session::write('finalItem', true);
  6977. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6978. $sql = "SELECT lp.*, doc.path as dir
  6979. FROM $tbl_lp_item as lp
  6980. LEFT JOIN $tbl_doc as doc
  6981. ON (doc.iid = lp.path AND lp.c_id = doc.c_id)
  6982. WHERE
  6983. doc.c_id = $course_id AND
  6984. lp.iid = ".$item_id;
  6985. $res_step = Database::query($sql);
  6986. $row_step = Database::fetch_array($res_step, 'ASSOC');
  6987. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6988. $return .= $this->display_document_form('edit', $item_id, $row_step);
  6989. break;
  6990. case TOOL_QUIZ:
  6991. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6992. $return .= $this->display_quiz_form('edit', $item_id, $row);
  6993. break;
  6994. case TOOL_HOTPOTATOES:
  6995. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6996. $return .= $this->display_hotpotatoes_form('edit', $item_id, $row);
  6997. break;
  6998. case TOOL_STUDENTPUBLICATION:
  6999. $return .= $this->display_manipulate($item_id, $row['item_type']);
  7000. $return .= $this->display_student_publication_form('edit', $item_id, $row);
  7001. break;
  7002. case TOOL_FORUM:
  7003. $return .= $this->display_manipulate($item_id, $row['item_type']);
  7004. $return .= $this->display_forum_form('edit', $item_id, $row);
  7005. break;
  7006. case TOOL_THREAD:
  7007. $return .= $this->display_manipulate($item_id, $row['item_type']);
  7008. $return .= $this->display_thread_form('edit', $item_id, $row);
  7009. break;
  7010. }
  7011. return $return;
  7012. }
  7013. /**
  7014. * Function that displays a list with al the resources that
  7015. * could be added to the learning path.
  7016. *
  7017. * @throws Exception
  7018. * @throws HTML_QuickForm_Error
  7019. *
  7020. * @return bool
  7021. */
  7022. public function display_resources()
  7023. {
  7024. $course_code = api_get_course_id();
  7025. // Get all the docs.
  7026. $documents = $this->get_documents(true);
  7027. // Get all the exercises.
  7028. $exercises = $this->get_exercises();
  7029. // Get all the links.
  7030. $links = $this->get_links();
  7031. // Get all the student publications.
  7032. $works = $this->get_student_publications();
  7033. // Get all the forums.
  7034. $forums = $this->get_forums(null, $course_code);
  7035. // Get the final item form (see BT#11048) .
  7036. $finish = $this->getFinalItemForm();
  7037. $headers = [
  7038. Display::return_icon('folder_document.png', get_lang('Documents'), [], ICON_SIZE_BIG),
  7039. Display::return_icon('quiz.png', get_lang('Quiz'), [], ICON_SIZE_BIG),
  7040. Display::return_icon('links.png', get_lang('Links'), [], ICON_SIZE_BIG),
  7041. Display::return_icon('works.png', get_lang('Works'), [], ICON_SIZE_BIG),
  7042. Display::return_icon('forum.png', get_lang('Forums'), [], ICON_SIZE_BIG),
  7043. Display::return_icon('add_learnpath_section.png', get_lang('NewChapter'), [], ICON_SIZE_BIG),
  7044. Display::return_icon('certificate.png', get_lang('Certificate'), [], ICON_SIZE_BIG),
  7045. ];
  7046. echo Display::return_message(get_lang('ClickOnTheLearnerViewToSeeYourLearningPath'), 'normal');
  7047. $dir = $this->display_item_form('dir', get_lang('EnterDataNewChapter'), 'add_item');
  7048. echo Display::tabs(
  7049. $headers,
  7050. [
  7051. $documents,
  7052. $exercises,
  7053. $links,
  7054. $works,
  7055. $forums,
  7056. $dir,
  7057. $finish,
  7058. ],
  7059. 'resource_tab'
  7060. );
  7061. return true;
  7062. }
  7063. /**
  7064. * Returns the extension of a document.
  7065. *
  7066. * @param string $filename
  7067. *
  7068. * @return string Extension (part after the last dot)
  7069. */
  7070. public function get_extension($filename)
  7071. {
  7072. $explode = explode('.', $filename);
  7073. return $explode[count($explode) - 1];
  7074. }
  7075. /**
  7076. * Displays a document by id.
  7077. *
  7078. * @param int $id
  7079. * @param bool $show_title
  7080. * @param bool $iframe
  7081. * @param bool $edit_link
  7082. *
  7083. * @return string
  7084. */
  7085. public function display_document($id, $show_title = false, $iframe = true, $edit_link = false)
  7086. {
  7087. $_course = api_get_course_info();
  7088. $course_id = api_get_course_int_id();
  7089. $id = (int) $id;
  7090. $return = '';
  7091. $table = Database::get_course_table(TABLE_DOCUMENT);
  7092. $sql_doc = "SELECT * FROM $table
  7093. WHERE c_id = $course_id AND iid = $id";
  7094. $res_doc = Database::query($sql_doc);
  7095. $row_doc = Database::fetch_array($res_doc);
  7096. // TODO: Add a path filter.
  7097. if ($iframe) {
  7098. $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>';
  7099. } else {
  7100. $return .= file_get_contents(api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/'.$row_doc['path']);
  7101. }
  7102. return $return;
  7103. }
  7104. /**
  7105. * Return HTML form to add/edit a quiz.
  7106. *
  7107. * @param string $action Action (add/edit)
  7108. * @param int $id Item ID if already exists
  7109. * @param mixed $extra_info Extra information (quiz ID if integer)
  7110. *
  7111. * @throws Exception
  7112. *
  7113. * @return string HTML form
  7114. */
  7115. public function display_quiz_form($action = 'add', $id = 0, $extra_info = '')
  7116. {
  7117. $course_id = api_get_course_int_id();
  7118. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7119. $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  7120. if ($id != 0 && is_array($extra_info)) {
  7121. $item_title = $extra_info['title'];
  7122. $item_description = $extra_info['description'];
  7123. } elseif (is_numeric($extra_info)) {
  7124. $sql = "SELECT title, description
  7125. FROM $tbl_quiz
  7126. WHERE c_id = $course_id AND iid = ".$extra_info;
  7127. $result = Database::query($sql);
  7128. $row = Database::fetch_array($result);
  7129. $item_title = $row['title'];
  7130. $item_description = $row['description'];
  7131. } else {
  7132. $item_title = '';
  7133. $item_description = '';
  7134. }
  7135. $item_title = Security::remove_XSS($item_title);
  7136. $item_description = Security::remove_XSS($item_description);
  7137. if ($id != 0 && is_array($extra_info)) {
  7138. $parent = $extra_info['parent_item_id'];
  7139. } else {
  7140. $parent = 0;
  7141. }
  7142. $sql = "SELECT * FROM $tbl_lp_item
  7143. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  7144. $result = Database::query($sql);
  7145. $arrLP = [];
  7146. while ($row = Database::fetch_array($result)) {
  7147. $arrLP[] = [
  7148. 'id' => $row['iid'],
  7149. 'item_type' => $row['item_type'],
  7150. 'title' => $row['title'],
  7151. 'path' => $row['path'],
  7152. 'description' => $row['description'],
  7153. 'parent_item_id' => $row['parent_item_id'],
  7154. 'previous_item_id' => $row['previous_item_id'],
  7155. 'next_item_id' => $row['next_item_id'],
  7156. 'display_order' => $row['display_order'],
  7157. 'max_score' => $row['max_score'],
  7158. 'min_score' => $row['min_score'],
  7159. 'mastery_score' => $row['mastery_score'],
  7160. 'prerequisite' => $row['prerequisite'],
  7161. 'max_time_allowed' => $row['max_time_allowed'],
  7162. ];
  7163. }
  7164. $this->tree_array($arrLP);
  7165. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7166. unset($this->arrMenu);
  7167. $form = new FormValidator(
  7168. 'quiz_form',
  7169. 'POST',
  7170. $this->getCurrentBuildingModeURL()
  7171. );
  7172. $defaults = [];
  7173. if ($action == 'add') {
  7174. $legend = get_lang('CreateTheExercise');
  7175. } elseif ($action == 'move') {
  7176. $legend = get_lang('MoveTheCurrentExercise');
  7177. } else {
  7178. $legend = get_lang('EditCurrentExecice');
  7179. }
  7180. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  7181. $legend .= Display::return_message(get_lang('Warning').' ! '.get_lang('WarningEditingDocument'));
  7182. }
  7183. $form->addHeader($legend);
  7184. if ($action != 'move') {
  7185. $form->addText('title', get_lang('Title'), true, ['id' => 'idTitle']);
  7186. $defaults['title'] = $item_title;
  7187. }
  7188. // Select for Parent item, root or chapter
  7189. $selectParent = $form->addSelect(
  7190. 'parent',
  7191. get_lang('Parent'),
  7192. [],
  7193. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);']
  7194. );
  7195. $selectParent->addOption($this->name, 0);
  7196. $arrHide = [
  7197. $id,
  7198. ];
  7199. for ($i = 0; $i < count($arrLP); $i++) {
  7200. if ($action != 'add') {
  7201. if (
  7202. ($arrLP[$i]['item_type'] == 'dir') &&
  7203. !in_array($arrLP[$i]['id'], $arrHide) &&
  7204. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7205. ) {
  7206. $selectParent->addOption(
  7207. $arrLP[$i]['title'],
  7208. $arrLP[$i]['id'],
  7209. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7210. );
  7211. if ($parent == $arrLP[$i]['id']) {
  7212. $selectParent->setSelected($arrLP[$i]['id']);
  7213. }
  7214. } else {
  7215. $arrHide[] = $arrLP[$i]['id'];
  7216. }
  7217. } else {
  7218. if ($arrLP[$i]['item_type'] == 'dir') {
  7219. $selectParent->addOption(
  7220. $arrLP[$i]['title'],
  7221. $arrLP[$i]['id'],
  7222. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7223. );
  7224. if ($parent == $arrLP[$i]['id']) {
  7225. $selectParent->setSelected($arrLP[$i]['id']);
  7226. }
  7227. }
  7228. }
  7229. }
  7230. if (is_array($arrLP)) {
  7231. reset($arrLP);
  7232. }
  7233. $selectPrevious = $form->addSelect(
  7234. 'previous',
  7235. get_lang('Position'),
  7236. [],
  7237. ['id' => 'previous']
  7238. );
  7239. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  7240. for ($i = 0; $i < count($arrLP); $i++) {
  7241. if ($arrLP[$i]['parent_item_id'] == $parent &&
  7242. $arrLP[$i]['id'] != $id
  7243. ) {
  7244. $selectPrevious->addOption(
  7245. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  7246. $arrLP[$i]['id']
  7247. );
  7248. if (is_array($extra_info)) {
  7249. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7250. $selectPrevious->setSelected($arrLP[$i]['id']);
  7251. }
  7252. } elseif ($action == 'add') {
  7253. $selectPrevious->setSelected($arrLP[$i]['id']);
  7254. }
  7255. }
  7256. }
  7257. if ($action != 'move') {
  7258. $arrHide = [];
  7259. for ($i = 0; $i < count($arrLP); $i++) {
  7260. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7261. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7262. }
  7263. }
  7264. }
  7265. if ($action == 'add') {
  7266. $form->addButtonSave(get_lang('AddExercise'), 'submit_button');
  7267. } else {
  7268. $form->addButtonSave(get_lang('EditCurrentExecice'), 'submit_button');
  7269. }
  7270. if ($action == 'move') {
  7271. $form->addHidden('title', $item_title);
  7272. $form->addHidden('description', $item_description);
  7273. }
  7274. if (is_numeric($extra_info)) {
  7275. $form->addHidden('path', $extra_info);
  7276. } elseif (is_array($extra_info)) {
  7277. $form->addHidden('path', $extra_info['path']);
  7278. }
  7279. $form->addHidden('type', TOOL_QUIZ);
  7280. $form->addHidden('post_time', time());
  7281. $form->setDefaults($defaults);
  7282. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  7283. }
  7284. /**
  7285. * Addition of Hotpotatoes tests.
  7286. *
  7287. * @param string $action
  7288. * @param int $id Internal ID of the item
  7289. * @param string $extra_info
  7290. *
  7291. * @return string HTML structure to display the hotpotatoes addition formular
  7292. */
  7293. public function display_hotpotatoes_form($action = 'add', $id = 0, $extra_info = '')
  7294. {
  7295. $course_id = api_get_course_int_id();
  7296. $uploadPath = DIR_HOTPOTATOES; //defined in main_api
  7297. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7298. if ($id != 0 && is_array($extra_info)) {
  7299. $item_title = stripslashes($extra_info['title']);
  7300. $item_description = stripslashes($extra_info['description']);
  7301. } elseif (is_numeric($extra_info)) {
  7302. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  7303. $sql = "SELECT * FROM ".$TBL_DOCUMENT."
  7304. WHERE
  7305. c_id = ".$course_id." AND
  7306. path LIKE '".$uploadPath."/%/%htm%' AND
  7307. iid = ".(int) $extra_info."
  7308. ORDER BY iid ASC";
  7309. $res_hot = Database::query($sql);
  7310. $row = Database::fetch_array($res_hot);
  7311. $item_title = $row['title'];
  7312. $item_description = $row['description'];
  7313. if (!empty($row['comment'])) {
  7314. $item_title = $row['comment'];
  7315. }
  7316. } else {
  7317. $item_title = '';
  7318. $item_description = '';
  7319. }
  7320. if ($id != 0 && is_array($extra_info)) {
  7321. $parent = $extra_info['parent_item_id'];
  7322. } else {
  7323. $parent = 0;
  7324. }
  7325. $sql = "SELECT * FROM $tbl_lp_item
  7326. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  7327. $result = Database::query($sql);
  7328. $arrLP = [];
  7329. while ($row = Database::fetch_array($result)) {
  7330. $arrLP[] = [
  7331. 'id' => $row['id'],
  7332. 'item_type' => $row['item_type'],
  7333. 'title' => $row['title'],
  7334. 'path' => $row['path'],
  7335. 'description' => $row['description'],
  7336. 'parent_item_id' => $row['parent_item_id'],
  7337. 'previous_item_id' => $row['previous_item_id'],
  7338. 'next_item_id' => $row['next_item_id'],
  7339. 'display_order' => $row['display_order'],
  7340. 'max_score' => $row['max_score'],
  7341. 'min_score' => $row['min_score'],
  7342. 'mastery_score' => $row['mastery_score'],
  7343. 'prerequisite' => $row['prerequisite'],
  7344. 'max_time_allowed' => $row['max_time_allowed'],
  7345. ];
  7346. }
  7347. $legend = '<legend>';
  7348. if ($action == 'add') {
  7349. $legend .= get_lang('CreateTheExercise');
  7350. } elseif ($action == 'move') {
  7351. $legend .= get_lang('MoveTheCurrentExercise');
  7352. } else {
  7353. $legend .= get_lang('EditCurrentExecice');
  7354. }
  7355. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  7356. $legend .= Display:: return_message(
  7357. get_lang('Warning').' ! '.get_lang('WarningEditingDocument')
  7358. );
  7359. }
  7360. $legend .= '</legend>';
  7361. $return = '<form method="POST">';
  7362. $return .= $legend;
  7363. $return .= '<table cellpadding="0" cellspacing="0" class="lp_form">';
  7364. $return .= '<tr>';
  7365. $return .= '<td class="label"><label for="idParent">'.get_lang('Parent').' :</label></td>';
  7366. $return .= '<td class="input">';
  7367. $return .= '<select id="idParent" name="parent" onChange="javascript: load_cbo(this.value);" size="1">';
  7368. $return .= '<option class="top" value="0">'.$this->name.'</option>';
  7369. $arrHide = [
  7370. $id,
  7371. ];
  7372. if (count($arrLP) > 0) {
  7373. for ($i = 0; $i < count($arrLP); $i++) {
  7374. if ($action != 'add') {
  7375. if ($arrLP[$i]['item_type'] == 'dir' &&
  7376. !in_array($arrLP[$i]['id'], $arrHide) &&
  7377. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7378. ) {
  7379. $return .= '<option '.(($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '').'style="padding-left:'.($arrLP[$i]['depth'] * 10).'px;" value="'.$arrLP[$i]['id'].'">'.$arrLP[$i]['title'].'</option>';
  7380. } else {
  7381. $arrHide[] = $arrLP[$i]['id'];
  7382. }
  7383. } else {
  7384. if ($arrLP[$i]['item_type'] == 'dir') {
  7385. $return .= '<option '.(($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '').'style="padding-left:'.($arrLP[$i]['depth'] * 10).'px;" value="'.$arrLP[$i]['id'].'">'.$arrLP[$i]['title'].'</option>';
  7386. }
  7387. }
  7388. }
  7389. reset($arrLP);
  7390. }
  7391. $return .= '</select>';
  7392. $return .= '</td>';
  7393. $return .= '</tr>';
  7394. $return .= '<tr>';
  7395. $return .= '<td class="label"><label for="previous">'.get_lang('Position').' :</label></td>';
  7396. $return .= '<td class="input">';
  7397. $return .= '<select id="previous" name="previous" size="1">';
  7398. $return .= '<option class="top" value="0">'.get_lang('FirstPosition').'</option>';
  7399. for ($i = 0; $i < count($arrLP); $i++) {
  7400. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  7401. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7402. $selected = 'selected="selected" ';
  7403. } elseif ($action == 'add') {
  7404. $selected = 'selected="selected" ';
  7405. } else {
  7406. $selected = '';
  7407. }
  7408. $return .= '<option '.$selected.'value="'.$arrLP[$i]['id'].'">'.get_lang('After').' "'.$arrLP[$i]['title'].'"</option>';
  7409. }
  7410. }
  7411. $return .= '</select>';
  7412. $return .= '</td>';
  7413. $return .= '</tr>';
  7414. if ($action != 'move') {
  7415. $return .= '<tr>';
  7416. $return .= '<td class="label"><label for="idTitle">'.get_lang('Title').' :</label></td>';
  7417. $return .= '<td class="input"><input id="idTitle" name="title" type="text" value="'.$item_title.'" /></td>';
  7418. $return .= '</tr>';
  7419. $id_prerequisite = 0;
  7420. if (is_array($arrLP) && count($arrLP) > 0) {
  7421. foreach ($arrLP as $key => $value) {
  7422. if ($value['id'] == $id) {
  7423. $id_prerequisite = $value['prerequisite'];
  7424. break;
  7425. }
  7426. }
  7427. $arrHide = [];
  7428. for ($i = 0; $i < count($arrLP); $i++) {
  7429. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7430. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7431. }
  7432. }
  7433. }
  7434. }
  7435. $return .= '<tr>';
  7436. $return .= '<td>&nbsp; </td><td><button class="save" name="submit_button" action="edit" type="submit">'.
  7437. get_lang('SaveHotpotatoes').'</button></td>';
  7438. $return .= '</tr>';
  7439. $return .= '</table>';
  7440. if ($action == 'move') {
  7441. $return .= '<input name="title" type="hidden" value="'.$item_title.'" />';
  7442. $return .= '<input name="description" type="hidden" value="'.$item_description.'" />';
  7443. }
  7444. if (is_numeric($extra_info)) {
  7445. $return .= '<input name="path" type="hidden" value="'.$extra_info.'" />';
  7446. } elseif (is_array($extra_info)) {
  7447. $return .= '<input name="path" type="hidden" value="'.$extra_info['path'].'" />';
  7448. }
  7449. $return .= '<input name="type" type="hidden" value="'.TOOL_HOTPOTATOES.'" />';
  7450. $return .= '<input name="post_time" type="hidden" value="'.time().'" />';
  7451. $return .= '</form>';
  7452. return $return;
  7453. }
  7454. /**
  7455. * Return the form to display the forum edit/add option.
  7456. *
  7457. * @param string $action
  7458. * @param int $id ID of the lp_item if already exists
  7459. * @param string $extra_info
  7460. *
  7461. * @throws Exception
  7462. *
  7463. * @return string HTML form
  7464. */
  7465. public function display_forum_form($action = 'add', $id = 0, $extra_info = '')
  7466. {
  7467. $course_id = api_get_course_int_id();
  7468. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7469. $tbl_forum = Database::get_course_table(TABLE_FORUM);
  7470. if ($id != 0 && is_array($extra_info)) {
  7471. $item_title = stripslashes($extra_info['title']);
  7472. } elseif (is_numeric($extra_info)) {
  7473. $sql = "SELECT forum_title as title, forum_comment as comment
  7474. FROM $tbl_forum
  7475. WHERE c_id = $course_id AND forum_id = ".$extra_info;
  7476. $result = Database::query($sql);
  7477. $row = Database::fetch_array($result);
  7478. $item_title = $row['title'];
  7479. $item_description = $row['comment'];
  7480. } else {
  7481. $item_title = '';
  7482. $item_description = '';
  7483. }
  7484. if ($id != 0 && is_array($extra_info)) {
  7485. $parent = $extra_info['parent_item_id'];
  7486. } else {
  7487. $parent = 0;
  7488. }
  7489. $sql = "SELECT * FROM $tbl_lp_item
  7490. WHERE
  7491. c_id = $course_id AND
  7492. lp_id = ".$this->lp_id;
  7493. $result = Database::query($sql);
  7494. $arrLP = [];
  7495. while ($row = Database::fetch_array($result)) {
  7496. $arrLP[] = [
  7497. 'id' => $row['iid'],
  7498. 'item_type' => $row['item_type'],
  7499. 'title' => $row['title'],
  7500. 'path' => $row['path'],
  7501. 'description' => $row['description'],
  7502. 'parent_item_id' => $row['parent_item_id'],
  7503. 'previous_item_id' => $row['previous_item_id'],
  7504. 'next_item_id' => $row['next_item_id'],
  7505. 'display_order' => $row['display_order'],
  7506. 'max_score' => $row['max_score'],
  7507. 'min_score' => $row['min_score'],
  7508. 'mastery_score' => $row['mastery_score'],
  7509. 'prerequisite' => $row['prerequisite'],
  7510. ];
  7511. }
  7512. $this->tree_array($arrLP);
  7513. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7514. unset($this->arrMenu);
  7515. if ($action == 'add') {
  7516. $legend = get_lang('CreateTheForum');
  7517. } elseif ($action == 'move') {
  7518. $legend = get_lang('MoveTheCurrentForum');
  7519. } else {
  7520. $legend = get_lang('EditCurrentForum');
  7521. }
  7522. $form = new FormValidator(
  7523. 'forum_form',
  7524. 'POST',
  7525. $this->getCurrentBuildingModeURL()
  7526. );
  7527. $defaults = [];
  7528. $form->addHeader($legend);
  7529. if ($action != 'move') {
  7530. $form->addText(
  7531. 'title',
  7532. get_lang('Title'),
  7533. true,
  7534. ['id' => 'idTitle', 'class' => 'learnpath_item_form']
  7535. );
  7536. $defaults['title'] = $item_title;
  7537. }
  7538. $selectParent = $form->addSelect(
  7539. 'parent',
  7540. get_lang('Parent'),
  7541. [],
  7542. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);', 'class' => 'learnpath_item_form']
  7543. );
  7544. $selectParent->addOption($this->name, 0);
  7545. $arrHide = [
  7546. $id,
  7547. ];
  7548. for ($i = 0; $i < count($arrLP); $i++) {
  7549. if ($action != 'add') {
  7550. if ($arrLP[$i]['item_type'] == 'dir' &&
  7551. !in_array($arrLP[$i]['id'], $arrHide) &&
  7552. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7553. ) {
  7554. $selectParent->addOption(
  7555. $arrLP[$i]['title'],
  7556. $arrLP[$i]['id'],
  7557. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7558. );
  7559. if ($parent == $arrLP[$i]['id']) {
  7560. $selectParent->setSelected($arrLP[$i]['id']);
  7561. }
  7562. } else {
  7563. $arrHide[] = $arrLP[$i]['id'];
  7564. }
  7565. } else {
  7566. if ($arrLP[$i]['item_type'] == 'dir') {
  7567. $selectParent->addOption(
  7568. $arrLP[$i]['title'],
  7569. $arrLP[$i]['id'],
  7570. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7571. );
  7572. if ($parent == $arrLP[$i]['id']) {
  7573. $selectParent->setSelected($arrLP[$i]['id']);
  7574. }
  7575. }
  7576. }
  7577. }
  7578. if (is_array($arrLP)) {
  7579. reset($arrLP);
  7580. }
  7581. $selectPrevious = $form->addSelect(
  7582. 'previous',
  7583. get_lang('Position'),
  7584. [],
  7585. ['id' => 'previous', 'class' => 'learnpath_item_form']
  7586. );
  7587. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  7588. for ($i = 0; $i < count($arrLP); $i++) {
  7589. if ($arrLP[$i]['parent_item_id'] == $parent &&
  7590. $arrLP[$i]['id'] != $id
  7591. ) {
  7592. $selectPrevious->addOption(
  7593. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  7594. $arrLP[$i]['id']
  7595. );
  7596. if (isset($extra_info['previous_item_id']) &&
  7597. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7598. ) {
  7599. $selectPrevious->setSelected($arrLP[$i]['id']);
  7600. } elseif ($action == 'add') {
  7601. $selectPrevious->setSelected($arrLP[$i]['id']);
  7602. }
  7603. }
  7604. }
  7605. if ($action != 'move') {
  7606. $id_prerequisite = 0;
  7607. if (is_array($arrLP)) {
  7608. foreach ($arrLP as $key => $value) {
  7609. if ($value['id'] == $id) {
  7610. $id_prerequisite = $value['prerequisite'];
  7611. break;
  7612. }
  7613. }
  7614. }
  7615. $arrHide = [];
  7616. for ($i = 0; $i < count($arrLP); $i++) {
  7617. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7618. if (isset($extra_info['previous_item_id']) &&
  7619. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7620. ) {
  7621. $s_selected_position = $arrLP[$i]['id'];
  7622. } elseif ($action == 'add') {
  7623. $s_selected_position = 0;
  7624. }
  7625. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7626. }
  7627. }
  7628. }
  7629. if ($action == 'add') {
  7630. $form->addButtonSave(get_lang('AddForumToCourse'), 'submit_button');
  7631. } else {
  7632. $form->addButtonSave(get_lang('EditCurrentForum'), 'submit_button');
  7633. }
  7634. if ($action == 'move') {
  7635. $form->addHidden('title', $item_title);
  7636. $form->addHidden('description', $item_description);
  7637. }
  7638. if (is_numeric($extra_info)) {
  7639. $form->addHidden('path', $extra_info);
  7640. } elseif (is_array($extra_info)) {
  7641. $form->addHidden('path', $extra_info['path']);
  7642. }
  7643. $form->addHidden('type', TOOL_FORUM);
  7644. $form->addHidden('post_time', time());
  7645. $form->setDefaults($defaults);
  7646. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  7647. }
  7648. /**
  7649. * Return HTML form to add/edit forum threads.
  7650. *
  7651. * @param string $action
  7652. * @param int $id Item ID if already exists in learning path
  7653. * @param string $extra_info
  7654. *
  7655. * @throws Exception
  7656. *
  7657. * @return string HTML form
  7658. */
  7659. public function display_thread_form($action = 'add', $id = 0, $extra_info = '')
  7660. {
  7661. $course_id = api_get_course_int_id();
  7662. if (empty($course_id)) {
  7663. return null;
  7664. }
  7665. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7666. $tbl_forum = Database::get_course_table(TABLE_FORUM_THREAD);
  7667. if ($id != 0 && is_array($extra_info)) {
  7668. $item_title = stripslashes($extra_info['title']);
  7669. } elseif (is_numeric($extra_info)) {
  7670. $sql = "SELECT thread_title as title FROM $tbl_forum
  7671. WHERE c_id = $course_id AND thread_id = ".$extra_info;
  7672. $result = Database::query($sql);
  7673. $row = Database::fetch_array($result);
  7674. $item_title = $row['title'];
  7675. $item_description = '';
  7676. } else {
  7677. $item_title = '';
  7678. $item_description = '';
  7679. }
  7680. if ($id != 0 && is_array($extra_info)) {
  7681. $parent = $extra_info['parent_item_id'];
  7682. } else {
  7683. $parent = 0;
  7684. }
  7685. $sql = "SELECT * FROM $tbl_lp_item
  7686. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  7687. $result = Database::query($sql);
  7688. $arrLP = [];
  7689. while ($row = Database::fetch_array($result)) {
  7690. $arrLP[] = [
  7691. 'id' => $row['iid'],
  7692. 'item_type' => $row['item_type'],
  7693. 'title' => $row['title'],
  7694. 'path' => $row['path'],
  7695. 'description' => $row['description'],
  7696. 'parent_item_id' => $row['parent_item_id'],
  7697. 'previous_item_id' => $row['previous_item_id'],
  7698. 'next_item_id' => $row['next_item_id'],
  7699. 'display_order' => $row['display_order'],
  7700. 'max_score' => $row['max_score'],
  7701. 'min_score' => $row['min_score'],
  7702. 'mastery_score' => $row['mastery_score'],
  7703. 'prerequisite' => $row['prerequisite'],
  7704. ];
  7705. }
  7706. $this->tree_array($arrLP);
  7707. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7708. unset($this->arrMenu);
  7709. $form = new FormValidator(
  7710. 'thread_form',
  7711. 'POST',
  7712. $this->getCurrentBuildingModeURL()
  7713. );
  7714. $defaults = [];
  7715. if ($action == 'add') {
  7716. $legend = get_lang('CreateTheForum');
  7717. } elseif ($action == 'move') {
  7718. $legend = get_lang('MoveTheCurrentForum');
  7719. } else {
  7720. $legend = get_lang('EditCurrentForum');
  7721. }
  7722. $form->addHeader($legend);
  7723. $selectParent = $form->addSelect(
  7724. 'parent',
  7725. get_lang('Parent'),
  7726. [],
  7727. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);']
  7728. );
  7729. $selectParent->addOption($this->name, 0);
  7730. $arrHide = [
  7731. $id,
  7732. ];
  7733. for ($i = 0; $i < count($arrLP); $i++) {
  7734. if ($action != 'add') {
  7735. if (
  7736. ($arrLP[$i]['item_type'] == 'dir') &&
  7737. !in_array($arrLP[$i]['id'], $arrHide) &&
  7738. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7739. ) {
  7740. $selectParent->addOption(
  7741. $arrLP[$i]['title'],
  7742. $arrLP[$i]['id'],
  7743. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7744. );
  7745. if ($parent == $arrLP[$i]['id']) {
  7746. $selectParent->setSelected($arrLP[$i]['id']);
  7747. }
  7748. } else {
  7749. $arrHide[] = $arrLP[$i]['id'];
  7750. }
  7751. } else {
  7752. if ($arrLP[$i]['item_type'] == 'dir') {
  7753. $selectParent->addOption(
  7754. $arrLP[$i]['title'],
  7755. $arrLP[$i]['id'],
  7756. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7757. );
  7758. if ($parent == $arrLP[$i]['id']) {
  7759. $selectParent->setSelected($arrLP[$i]['id']);
  7760. }
  7761. }
  7762. }
  7763. }
  7764. if ($arrLP != null) {
  7765. reset($arrLP);
  7766. }
  7767. $selectPrevious = $form->addSelect(
  7768. 'previous',
  7769. get_lang('Position'),
  7770. [],
  7771. ['id' => 'previous']
  7772. );
  7773. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  7774. for ($i = 0; $i < count($arrLP); $i++) {
  7775. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  7776. $selectPrevious->addOption(
  7777. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  7778. $arrLP[$i]['id']
  7779. );
  7780. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7781. $selectPrevious->setSelected($arrLP[$i]['id']);
  7782. } elseif ($action == 'add') {
  7783. $selectPrevious->setSelected($arrLP[$i]['id']);
  7784. }
  7785. }
  7786. }
  7787. if ($action != 'move') {
  7788. $form->addText(
  7789. 'title',
  7790. get_lang('Title'),
  7791. true,
  7792. ['id' => 'idTitle']
  7793. );
  7794. $defaults['title'] = $item_title;
  7795. $id_prerequisite = 0;
  7796. if ($arrLP != null) {
  7797. foreach ($arrLP as $key => $value) {
  7798. if ($value['id'] == $id) {
  7799. $id_prerequisite = $value['prerequisite'];
  7800. break;
  7801. }
  7802. }
  7803. }
  7804. $arrHide = [];
  7805. $s_selected_position = 0;
  7806. for ($i = 0; $i < count($arrLP); $i++) {
  7807. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7808. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7809. $s_selected_position = $arrLP[$i]['id'];
  7810. } elseif ($action == 'add') {
  7811. $s_selected_position = 0;
  7812. }
  7813. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7814. }
  7815. }
  7816. $selectPrerequisites = $form->addSelect(
  7817. 'prerequisites',
  7818. get_lang('LearnpathPrerequisites'),
  7819. [],
  7820. ['id' => 'prerequisites']
  7821. );
  7822. $selectPrerequisites->addOption(get_lang('NoPrerequisites'), 0);
  7823. foreach ($arrHide as $key => $value) {
  7824. $selectPrerequisites->addOption($value['value'], $key);
  7825. if ($key == $s_selected_position && $action == 'add') {
  7826. $selectPrerequisites->setSelected($key);
  7827. } elseif ($key == $id_prerequisite && $action == 'edit') {
  7828. $selectPrerequisites->setSelected($key);
  7829. }
  7830. }
  7831. }
  7832. $form->addButtonSave(get_lang('Ok'), 'submit_button');
  7833. if ($action == 'move') {
  7834. $form->addHidden('title', $item_title);
  7835. $form->addHidden('description', $item_description);
  7836. }
  7837. if (is_numeric($extra_info)) {
  7838. $form->addHidden('path', $extra_info);
  7839. } elseif (is_array($extra_info)) {
  7840. $form->addHidden('path', $extra_info['path']);
  7841. }
  7842. $form->addHidden('type', TOOL_THREAD);
  7843. $form->addHidden('post_time', time());
  7844. $form->setDefaults($defaults);
  7845. return $form->returnForm();
  7846. }
  7847. /**
  7848. * Return the HTML form to display an item (generally a dir item).
  7849. *
  7850. * @param string $item_type
  7851. * @param string $title
  7852. * @param string $action
  7853. * @param int $id
  7854. * @param string $extra_info
  7855. *
  7856. * @throws Exception
  7857. * @throws HTML_QuickForm_Error
  7858. *
  7859. * @return string HTML form
  7860. */
  7861. public function display_item_form(
  7862. $item_type,
  7863. $title = '',
  7864. $action = 'add_item',
  7865. $id = 0,
  7866. $extra_info = 'new'
  7867. ) {
  7868. $_course = api_get_course_info();
  7869. global $charset;
  7870. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7871. $item_title = '';
  7872. $item_description = '';
  7873. $item_path_fck = '';
  7874. if ($id != 0 && is_array($extra_info)) {
  7875. $item_title = $extra_info['title'];
  7876. $item_description = $extra_info['description'];
  7877. $item_path = api_get_path(WEB_COURSE_PATH).$_course['path'].'/scorm/'.$this->path.'/'.stripslashes($extra_info['path']);
  7878. $item_path_fck = '/scorm/'.$this->path.'/'.stripslashes($extra_info['path']);
  7879. }
  7880. $parent = 0;
  7881. if ($id != 0 && is_array($extra_info)) {
  7882. $parent = $extra_info['parent_item_id'];
  7883. }
  7884. $id = (int) $id;
  7885. $sql = "SELECT * FROM $tbl_lp_item
  7886. WHERE
  7887. lp_id = ".$this->lp_id." AND
  7888. iid != $id";
  7889. if ($item_type == 'dir') {
  7890. $sql .= " AND parent_item_id = 0";
  7891. }
  7892. $result = Database::query($sql);
  7893. $arrLP = [];
  7894. while ($row = Database::fetch_array($result)) {
  7895. $arrLP[] = [
  7896. 'id' => $row['iid'],
  7897. 'item_type' => $row['item_type'],
  7898. 'title' => $row['title'],
  7899. 'path' => $row['path'],
  7900. 'description' => $row['description'],
  7901. 'parent_item_id' => $row['parent_item_id'],
  7902. 'previous_item_id' => $row['previous_item_id'],
  7903. 'next_item_id' => $row['next_item_id'],
  7904. 'max_score' => $row['max_score'],
  7905. 'min_score' => $row['min_score'],
  7906. 'mastery_score' => $row['mastery_score'],
  7907. 'prerequisite' => $row['prerequisite'],
  7908. 'display_order' => $row['display_order'],
  7909. ];
  7910. }
  7911. $this->tree_array($arrLP);
  7912. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7913. unset($this->arrMenu);
  7914. $url = api_get_self().'?'.api_get_cidreq().'&action='.$action.'&type='.$item_type.'&lp_id='.$this->lp_id;
  7915. $form = new FormValidator('form', 'POST', $url);
  7916. $defaults['title'] = api_html_entity_decode(
  7917. $item_title,
  7918. ENT_QUOTES,
  7919. $charset
  7920. );
  7921. $defaults['description'] = $item_description;
  7922. $form->addHeader($title);
  7923. $arrHide[0]['value'] = Security::remove_XSS($this->name);
  7924. $arrHide[0]['padding'] = 20;
  7925. $charset = api_get_system_encoding();
  7926. for ($i = 0; $i < count($arrLP); $i++) {
  7927. if ($action != 'add') {
  7928. if ($arrLP[$i]['item_type'] == 'dir' && !in_array($arrLP[$i]['id'], $arrHide) &&
  7929. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7930. ) {
  7931. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7932. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7933. if ($parent == $arrLP[$i]['id']) {
  7934. $s_selected_parent = $arrHide[$arrLP[$i]['id']];
  7935. }
  7936. }
  7937. } else {
  7938. if ($arrLP[$i]['item_type'] == 'dir') {
  7939. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7940. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7941. if ($parent == $arrLP[$i]['id']) {
  7942. $s_selected_parent = $arrHide[$arrLP[$i]['id']];
  7943. }
  7944. }
  7945. }
  7946. }
  7947. if ($action != 'move') {
  7948. $form->addElement('text', 'title', get_lang('Title'));
  7949. $form->applyFilter('title', 'html_filter');
  7950. $form->addRule('title', get_lang('ThisFieldIsRequired'), 'required');
  7951. } else {
  7952. $form->addElement('hidden', 'title');
  7953. }
  7954. $parentSelect = $form->addElement(
  7955. 'select',
  7956. 'parent',
  7957. get_lang('Parent'),
  7958. '',
  7959. [
  7960. 'id' => 'idParent',
  7961. 'onchange' => "javascript: load_cbo(this.value);",
  7962. ]
  7963. );
  7964. foreach ($arrHide as $key => $value) {
  7965. $parentSelect->addOption(
  7966. $value['value'],
  7967. $key,
  7968. 'style="padding-left:'.$value['padding'].'px;"'
  7969. );
  7970. $lastPosition = $key;
  7971. }
  7972. if (!empty($s_selected_parent)) {
  7973. $parentSelect->setSelected($s_selected_parent);
  7974. }
  7975. if (is_array($arrLP)) {
  7976. reset($arrLP);
  7977. }
  7978. $arrHide = [];
  7979. // POSITION
  7980. for ($i = 0; $i < count($arrLP); $i++) {
  7981. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id &&
  7982. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM) {
  7983. //this is the same!
  7984. if (isset($extra_info['previous_item_id']) &&
  7985. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7986. ) {
  7987. $s_selected_position = $arrLP[$i]['id'];
  7988. } elseif ($action == 'add') {
  7989. $s_selected_position = $arrLP[$i]['id'];
  7990. }
  7991. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  7992. }
  7993. }
  7994. $position = $form->addElement(
  7995. 'select',
  7996. 'previous',
  7997. get_lang('Position'),
  7998. '',
  7999. ['id' => 'previous']
  8000. );
  8001. $padding = isset($value['padding']) ? $value['padding'] : 0;
  8002. $position->addOption(get_lang('FirstPosition'), 0, 'style="padding-left:'.$padding.'px;"');
  8003. $lastPosition = null;
  8004. foreach ($arrHide as $key => $value) {
  8005. $position->addOption($value['value'], $key, 'style="padding-left:'.$padding.'px;"');
  8006. $lastPosition = $key;
  8007. }
  8008. if (!empty($s_selected_position)) {
  8009. $position->setSelected($s_selected_position);
  8010. }
  8011. // When new chapter add at the end
  8012. if ($action == 'add_item') {
  8013. $position->setSelected($lastPosition);
  8014. }
  8015. if (is_array($arrLP)) {
  8016. reset($arrLP);
  8017. }
  8018. $form->addButtonSave(get_lang('SaveSection'), 'submit_button');
  8019. //fix in order to use the tab
  8020. if ($item_type == 'dir') {
  8021. $form->addElement('hidden', 'type', 'dir');
  8022. }
  8023. $extension = null;
  8024. if (!empty($item_path)) {
  8025. $extension = pathinfo($item_path, PATHINFO_EXTENSION);
  8026. }
  8027. //assets can't be modified
  8028. //$item_type == 'asset' ||
  8029. if (($item_type == 'sco') && ($extension == 'html' || $extension == 'htm')) {
  8030. if ($item_type == 'sco') {
  8031. $form->addElement(
  8032. 'html',
  8033. '<script>alert("'.get_lang('WarningWhenEditingScorm').'")</script>'
  8034. );
  8035. }
  8036. $renderer = $form->defaultRenderer();
  8037. $renderer->setElementTemplate(
  8038. '<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{label}<br />{element}',
  8039. 'content_lp'
  8040. );
  8041. $relative_prefix = '';
  8042. $editor_config = [
  8043. 'ToolbarSet' => 'LearningPathDocuments',
  8044. 'Width' => '100%',
  8045. 'Height' => '500',
  8046. 'FullPage' => true,
  8047. 'CreateDocumentDir' => $relative_prefix,
  8048. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/scorm/',
  8049. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().$item_path_fck,
  8050. ];
  8051. $form->addElement('html_editor', 'content_lp', '', null, $editor_config);
  8052. $content_path = api_get_path(SYS_COURSE_PATH).api_get_course_path().$item_path_fck;
  8053. $defaults['content_lp'] = file_get_contents($content_path);
  8054. }
  8055. if (!empty($id)) {
  8056. $form->addHidden('id', $id);
  8057. }
  8058. $form->addElement('hidden', 'type', $item_type);
  8059. $form->addElement('hidden', 'post_time', time());
  8060. $form->setDefaults($defaults);
  8061. return $form->returnForm();
  8062. }
  8063. /**
  8064. * @return string
  8065. */
  8066. public function getCurrentBuildingModeURL()
  8067. {
  8068. $pathItem = isset($_GET['path_item']) ? (int) $_GET['path_item'] : '';
  8069. $action = isset($_GET['action']) ? Security::remove_XSS($_GET['action']) : '';
  8070. $id = isset($_GET['id']) ? (int) $_GET['id'] : '';
  8071. $view = isset($_GET['view']) ? Security::remove_XSS($_GET['view']) : '';
  8072. $currentUrl = api_get_self().'?'.api_get_cidreq().
  8073. '&action='.$action.'&lp_id='.$this->lp_id.'&path_item='.$pathItem.'&view='.$view.'&id='.$id;
  8074. return $currentUrl;
  8075. }
  8076. /**
  8077. * Returns the form to update or create a document.
  8078. *
  8079. * @param string $action (add/edit)
  8080. * @param int $id ID of the lp_item (if already exists)
  8081. * @param mixed $extra_info Integer if document ID, string if info ('new')
  8082. *
  8083. * @throws Exception
  8084. * @throws HTML_QuickForm_Error
  8085. *
  8086. * @return string HTML form
  8087. */
  8088. public function display_document_form($action = 'add', $id = 0, $extra_info = 'new')
  8089. {
  8090. $course_id = api_get_course_int_id();
  8091. $_course = api_get_course_info();
  8092. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8093. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  8094. $no_display_edit_textarea = false;
  8095. $item_description = '';
  8096. //If action==edit document
  8097. //We don't display the document form if it's not an editable document (html or txt file)
  8098. if ($action === 'edit') {
  8099. if (is_array($extra_info)) {
  8100. $path_parts = pathinfo($extra_info['dir']);
  8101. if ($path_parts['extension'] != 'txt' && $path_parts['extension'] != 'html') {
  8102. $no_display_edit_textarea = true;
  8103. }
  8104. }
  8105. }
  8106. $no_display_add = false;
  8107. // If action==add an existing document
  8108. // We don't display the document form if it's not an editable document (html or txt file).
  8109. if ($action === 'add') {
  8110. if (is_numeric($extra_info)) {
  8111. $extra_info = (int) $extra_info;
  8112. $sql_doc = "SELECT path FROM $tbl_doc
  8113. WHERE c_id = $course_id AND iid = ".$extra_info;
  8114. $result = Database::query($sql_doc);
  8115. $path_file = Database::result($result, 0, 0);
  8116. $path_parts = pathinfo($path_file);
  8117. if ($path_parts['extension'] != 'txt' && $path_parts['extension'] != 'html') {
  8118. $no_display_add = true;
  8119. }
  8120. }
  8121. }
  8122. if ($id != 0 && is_array($extra_info)) {
  8123. $item_title = stripslashes($extra_info['title']);
  8124. $item_description = stripslashes($extra_info['description']);
  8125. if (empty($item_title)) {
  8126. $path_parts = pathinfo($extra_info['path']);
  8127. $item_title = stripslashes($path_parts['filename']);
  8128. }
  8129. } elseif (is_numeric($extra_info)) {
  8130. $sql = "SELECT path, title FROM $tbl_doc
  8131. WHERE
  8132. c_id = ".$course_id." AND
  8133. iid = ".intval($extra_info);
  8134. $result = Database::query($sql);
  8135. $row = Database::fetch_array($result);
  8136. $item_title = $row['title'];
  8137. $item_title = str_replace('_', ' ', $item_title);
  8138. if (empty($item_title)) {
  8139. $path_parts = pathinfo($row['path']);
  8140. $item_title = stripslashes($path_parts['filename']);
  8141. }
  8142. } else {
  8143. $item_title = '';
  8144. $item_description = '';
  8145. }
  8146. $return = '<legend>';
  8147. $parent = 0;
  8148. if ($id != 0 && is_array($extra_info)) {
  8149. $parent = $extra_info['parent_item_id'];
  8150. }
  8151. $sql = "SELECT * FROM $tbl_lp_item
  8152. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8153. $result = Database::query($sql);
  8154. $arrLP = [];
  8155. while ($row = Database::fetch_array($result)) {
  8156. $arrLP[] = [
  8157. 'id' => $row['iid'],
  8158. 'item_type' => $row['item_type'],
  8159. 'title' => $row['title'],
  8160. 'path' => $row['path'],
  8161. 'description' => $row['description'],
  8162. 'parent_item_id' => $row['parent_item_id'],
  8163. 'previous_item_id' => $row['previous_item_id'],
  8164. 'next_item_id' => $row['next_item_id'],
  8165. 'display_order' => $row['display_order'],
  8166. 'max_score' => $row['max_score'],
  8167. 'min_score' => $row['min_score'],
  8168. 'mastery_score' => $row['mastery_score'],
  8169. 'prerequisite' => $row['prerequisite'],
  8170. ];
  8171. }
  8172. $this->tree_array($arrLP);
  8173. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  8174. unset($this->arrMenu);
  8175. if ($action == 'add') {
  8176. $return .= get_lang('CreateTheDocument');
  8177. } elseif ($action == 'move') {
  8178. $return .= get_lang('MoveTheCurrentDocument');
  8179. } else {
  8180. $return .= get_lang('EditTheCurrentDocument');
  8181. }
  8182. $return .= '</legend>';
  8183. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  8184. $return .= Display::return_message(
  8185. '<strong>'.get_lang('Warning').' !</strong><br />'.get_lang('WarningEditingDocument'),
  8186. false
  8187. );
  8188. }
  8189. $form = new FormValidator(
  8190. 'form',
  8191. 'POST',
  8192. $this->getCurrentBuildingModeURL(),
  8193. '',
  8194. ['enctype' => 'multipart/form-data']
  8195. );
  8196. $defaults['title'] = Security::remove_XSS($item_title);
  8197. if (empty($item_title)) {
  8198. $defaults['title'] = Security::remove_XSS($item_title);
  8199. }
  8200. $defaults['description'] = $item_description;
  8201. $form->addElement('html', $return);
  8202. if ($action != 'move') {
  8203. $data = $this->generate_lp_folder($_course);
  8204. if ($action != 'edit') {
  8205. $folders = DocumentManager::get_all_document_folders(
  8206. $_course,
  8207. 0,
  8208. true
  8209. );
  8210. DocumentManager::build_directory_selector(
  8211. $folders,
  8212. '',
  8213. [],
  8214. true,
  8215. $form,
  8216. 'directory_parent_id'
  8217. );
  8218. }
  8219. if (isset($data['id'])) {
  8220. $defaults['directory_parent_id'] = $data['id'];
  8221. }
  8222. $form->addElement(
  8223. 'text',
  8224. 'title',
  8225. get_lang('Title'),
  8226. ['id' => 'idTitle', 'class' => 'col-md-4']
  8227. );
  8228. $form->applyFilter('title', 'html_filter');
  8229. }
  8230. $arrHide[0]['value'] = $this->name;
  8231. $arrHide[0]['padding'] = 20;
  8232. for ($i = 0; $i < count($arrLP); $i++) {
  8233. if ($action != 'add') {
  8234. if ($arrLP[$i]['item_type'] == 'dir' &&
  8235. !in_array($arrLP[$i]['id'], $arrHide) &&
  8236. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8237. ) {
  8238. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8239. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  8240. }
  8241. } else {
  8242. if ($arrLP[$i]['item_type'] == 'dir') {
  8243. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8244. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  8245. }
  8246. }
  8247. }
  8248. $parentSelect = $form->addSelect(
  8249. 'parent',
  8250. get_lang('Parent'),
  8251. [],
  8252. [
  8253. 'id' => 'idParent',
  8254. 'onchange' => 'javascript: load_cbo(this.value);',
  8255. ]
  8256. );
  8257. $my_count = 0;
  8258. foreach ($arrHide as $key => $value) {
  8259. if ($my_count != 0) {
  8260. // The LP name is also the first section and is not in the same charset like the other sections.
  8261. $value['value'] = Security::remove_XSS($value['value']);
  8262. $parentSelect->addOption(
  8263. $value['value'],
  8264. $key,
  8265. 'style="padding-left:'.$value['padding'].'px;"'
  8266. );
  8267. } else {
  8268. $value['value'] = Security::remove_XSS($value['value']);
  8269. $parentSelect->addOption(
  8270. $value['value'],
  8271. $key,
  8272. 'style="padding-left:'.$value['padding'].'px;"'
  8273. );
  8274. }
  8275. $my_count++;
  8276. }
  8277. if (!empty($id)) {
  8278. $parentSelect->setSelected($parent);
  8279. } else {
  8280. $parent_item_id = Session::read('parent_item_id', 0);
  8281. $parentSelect->setSelected($parent_item_id);
  8282. }
  8283. if (is_array($arrLP)) {
  8284. reset($arrLP);
  8285. }
  8286. $arrHide = [];
  8287. // POSITION
  8288. for ($i = 0; $i < count($arrLP); $i++) {
  8289. if (($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) ||
  8290. $arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM
  8291. ) {
  8292. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  8293. }
  8294. }
  8295. $selectedPosition = isset($extra_info['previous_item_id']) ? $extra_info['previous_item_id'] : 0;
  8296. $position = $form->addSelect(
  8297. 'previous',
  8298. get_lang('Position'),
  8299. [],
  8300. ['id' => 'previous']
  8301. );
  8302. $position->addOption(get_lang('FirstPosition'), 0);
  8303. foreach ($arrHide as $key => $value) {
  8304. $padding = isset($value['padding']) ? $value['padding'] : 20;
  8305. $position->addOption(
  8306. $value['value'],
  8307. $key,
  8308. 'style="padding-left:'.$padding.'px;"'
  8309. );
  8310. }
  8311. $position->setSelected($selectedPosition);
  8312. if (is_array($arrLP)) {
  8313. reset($arrLP);
  8314. }
  8315. if ($action != 'move') {
  8316. $arrHide = [];
  8317. for ($i = 0; $i < count($arrLP); $i++) {
  8318. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir' &&
  8319. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM
  8320. ) {
  8321. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8322. }
  8323. }
  8324. if (!$no_display_add) {
  8325. $item_type = isset($extra_info['item_type']) ? $extra_info['item_type'] : null;
  8326. $edit = isset($_GET['edit']) ? $_GET['edit'] : null;
  8327. if ($extra_info == 'new' || $item_type == TOOL_DOCUMENT ||
  8328. $item_type == TOOL_LP_FINAL_ITEM || $edit == 'true'
  8329. ) {
  8330. if (isset($_POST['content'])) {
  8331. $content = stripslashes($_POST['content']);
  8332. } elseif (is_array($extra_info)) {
  8333. //If it's an html document or a text file
  8334. if (!$no_display_edit_textarea) {
  8335. $content = $this->display_document(
  8336. $extra_info['path'],
  8337. false,
  8338. false
  8339. );
  8340. }
  8341. } elseif (is_numeric($extra_info)) {
  8342. $content = $this->display_document(
  8343. $extra_info,
  8344. false,
  8345. false
  8346. );
  8347. } else {
  8348. $content = '';
  8349. }
  8350. if (!$no_display_edit_textarea) {
  8351. // We need to calculate here some specific settings for the online editor.
  8352. // The calculated settings work for documents in the Documents tool
  8353. // (on the root or in subfolders).
  8354. // For documents in native scorm packages it is unclear whether the
  8355. // online editor should be activated or not.
  8356. // A new document, it is in the root of the repository.
  8357. $relative_path = '';
  8358. $relative_prefix = '';
  8359. if (is_array($extra_info) && $extra_info != 'new') {
  8360. // The document already exists. Whe have to determine its relative path towards the repository root.
  8361. $relative_path = explode('/', $extra_info['dir']);
  8362. $cnt = count($relative_path) - 2;
  8363. if ($cnt < 0) {
  8364. $cnt = 0;
  8365. }
  8366. $relative_prefix = str_repeat('../', $cnt);
  8367. $relative_path = array_slice($relative_path, 1, $cnt);
  8368. $relative_path = implode('/', $relative_path);
  8369. if (strlen($relative_path) > 0) {
  8370. $relative_path = $relative_path.'/';
  8371. }
  8372. } else {
  8373. $result = $this->generate_lp_folder($_course);
  8374. $relative_path = api_substr($result['dir'], 1, strlen($result['dir']));
  8375. $relative_prefix = '../../';
  8376. }
  8377. $editor_config = [
  8378. 'ToolbarSet' => 'LearningPathDocuments',
  8379. 'Width' => '100%',
  8380. 'Height' => '500',
  8381. 'FullPage' => true,
  8382. 'CreateDocumentDir' => $relative_prefix,
  8383. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/',
  8384. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/'.$relative_path,
  8385. ];
  8386. if ($_GET['action'] == 'add_item') {
  8387. $class = 'add';
  8388. $text = get_lang('LPCreateDocument');
  8389. } else {
  8390. if ($_GET['action'] == 'edit_item') {
  8391. $class = 'save';
  8392. $text = get_lang('SaveDocument');
  8393. }
  8394. }
  8395. $form->addButtonSave($text, 'submit_button');
  8396. $renderer = $form->defaultRenderer();
  8397. $renderer->setElementTemplate('&nbsp;{label}{element}', 'content_lp');
  8398. $form->addElement('html', '<div class="editor-lp">');
  8399. $form->addHtmlEditor('content_lp', null, null, true, $editor_config, true);
  8400. $form->addElement('html', '</div>');
  8401. $defaults['content_lp'] = $content;
  8402. }
  8403. } elseif (is_numeric($extra_info)) {
  8404. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  8405. $return = $this->display_document($extra_info, true, true, true);
  8406. $form->addElement('html', $return);
  8407. }
  8408. }
  8409. }
  8410. if (isset($extra_info['item_type']) &&
  8411. $extra_info['item_type'] == TOOL_LP_FINAL_ITEM
  8412. ) {
  8413. $parentSelect->freeze();
  8414. $position->freeze();
  8415. }
  8416. if ($action == 'move') {
  8417. $form->addElement('hidden', 'title', $item_title);
  8418. $form->addElement('hidden', 'description', $item_description);
  8419. }
  8420. if (is_numeric($extra_info)) {
  8421. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  8422. $form->addElement('hidden', 'path', $extra_info);
  8423. } elseif (is_array($extra_info)) {
  8424. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  8425. $form->addElement('hidden', 'path', $extra_info['path']);
  8426. }
  8427. $form->addElement('hidden', 'type', TOOL_DOCUMENT);
  8428. $form->addElement('hidden', 'post_time', time());
  8429. $form->setDefaults($defaults);
  8430. return $form->returnForm();
  8431. }
  8432. /**
  8433. * Returns the form to update or create a read-out text.
  8434. *
  8435. * @param string $action "add" or "edit"
  8436. * @param int $id ID of the lp_item (if already exists)
  8437. * @param mixed $extra_info Integer if document ID, string if info ('new')
  8438. *
  8439. * @throws Exception
  8440. * @throws HTML_QuickForm_Error
  8441. *
  8442. * @return string HTML form
  8443. */
  8444. public function displayFrmReadOutText($action = 'add', $id = 0, $extra_info = 'new')
  8445. {
  8446. $course_id = api_get_course_int_id();
  8447. $_course = api_get_course_info();
  8448. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8449. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  8450. $no_display_edit_textarea = false;
  8451. $item_description = '';
  8452. //If action==edit document
  8453. //We don't display the document form if it's not an editable document (html or txt file)
  8454. if ($action == 'edit') {
  8455. if (is_array($extra_info)) {
  8456. $path_parts = pathinfo($extra_info['dir']);
  8457. if ($path_parts['extension'] != "txt" && $path_parts['extension'] != "html") {
  8458. $no_display_edit_textarea = true;
  8459. }
  8460. }
  8461. }
  8462. $no_display_add = false;
  8463. if ($id != 0 && is_array($extra_info)) {
  8464. $item_title = stripslashes($extra_info['title']);
  8465. $item_description = stripslashes($extra_info['description']);
  8466. $item_terms = stripslashes($extra_info['terms']);
  8467. if (empty($item_title)) {
  8468. $path_parts = pathinfo($extra_info['path']);
  8469. $item_title = stripslashes($path_parts['filename']);
  8470. }
  8471. } elseif (is_numeric($extra_info)) {
  8472. $sql = "SELECT path, title FROM $tbl_doc WHERE c_id = ".$course_id." AND iid = ".intval($extra_info);
  8473. $result = Database::query($sql);
  8474. $row = Database::fetch_array($result);
  8475. $item_title = $row['title'];
  8476. $item_title = str_replace('_', ' ', $item_title);
  8477. if (empty($item_title)) {
  8478. $path_parts = pathinfo($row['path']);
  8479. $item_title = stripslashes($path_parts['filename']);
  8480. }
  8481. } else {
  8482. $item_title = '';
  8483. $item_description = '';
  8484. }
  8485. if ($id != 0 && is_array($extra_info)) {
  8486. $parent = $extra_info['parent_item_id'];
  8487. } else {
  8488. $parent = 0;
  8489. }
  8490. $sql = "SELECT * FROM $tbl_lp_item WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8491. $result = Database::query($sql);
  8492. $arrLP = [];
  8493. while ($row = Database::fetch_array($result)) {
  8494. $arrLP[] = [
  8495. 'id' => $row['iid'],
  8496. 'item_type' => $row['item_type'],
  8497. 'title' => $row['title'],
  8498. 'path' => $row['path'],
  8499. 'description' => $row['description'],
  8500. 'parent_item_id' => $row['parent_item_id'],
  8501. 'previous_item_id' => $row['previous_item_id'],
  8502. 'next_item_id' => $row['next_item_id'],
  8503. 'display_order' => $row['display_order'],
  8504. 'max_score' => $row['max_score'],
  8505. 'min_score' => $row['min_score'],
  8506. 'mastery_score' => $row['mastery_score'],
  8507. 'prerequisite' => $row['prerequisite'],
  8508. ];
  8509. }
  8510. $this->tree_array($arrLP);
  8511. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  8512. unset($this->arrMenu);
  8513. if ($action == 'add') {
  8514. $formHeader = get_lang('CreateTheDocument');
  8515. } else {
  8516. $formHeader = get_lang('EditTheCurrentDocument');
  8517. }
  8518. if ('edit' === $action) {
  8519. $urlAudioIcon = Display::url(
  8520. Display::return_icon('audio.png', get_lang('CreateReadOutText'), [], ICON_SIZE_TINY),
  8521. api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq().'&lp_id='.$this->lp_id.'&'
  8522. .http_build_query(['view' => 'build', 'id' => $id, 'action' => 'add_audio'])
  8523. );
  8524. } else {
  8525. $urlAudioIcon = Display::return_icon('audio.png', get_lang('CreateReadOutText'), [], ICON_SIZE_TINY);
  8526. }
  8527. $form = new FormValidator(
  8528. 'frm_add_reading',
  8529. 'POST',
  8530. $this->getCurrentBuildingModeURL(),
  8531. '',
  8532. ['enctype' => 'multipart/form-data']
  8533. );
  8534. $form->addHeader($formHeader);
  8535. $form->addHtml(
  8536. Display::return_message(
  8537. sprintf(get_lang('FrmReadOutTextIntro'), $urlAudioIcon),
  8538. 'normal',
  8539. false
  8540. )
  8541. );
  8542. $defaults['title'] = !empty($item_title) ? Security::remove_XSS($item_title) : '';
  8543. $defaults['description'] = $item_description;
  8544. $data = $this->generate_lp_folder($_course);
  8545. if ($action != 'edit') {
  8546. $folders = DocumentManager::get_all_document_folders($_course, 0, true);
  8547. DocumentManager::build_directory_selector(
  8548. $folders,
  8549. '',
  8550. [],
  8551. true,
  8552. $form,
  8553. 'directory_parent_id'
  8554. );
  8555. }
  8556. if (isset($data['id'])) {
  8557. $defaults['directory_parent_id'] = $data['id'];
  8558. }
  8559. $form->addElement(
  8560. 'text',
  8561. 'title',
  8562. get_lang('Title')
  8563. );
  8564. $form->applyFilter('title', 'trim');
  8565. $form->applyFilter('title', 'html_filter');
  8566. $arrHide[0]['value'] = $this->name;
  8567. $arrHide[0]['padding'] = 20;
  8568. for ($i = 0; $i < count($arrLP); $i++) {
  8569. if ($action != 'add') {
  8570. if ($arrLP[$i]['item_type'] == 'dir' &&
  8571. !in_array($arrLP[$i]['id'], $arrHide) &&
  8572. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8573. ) {
  8574. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8575. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  8576. }
  8577. } else {
  8578. if ($arrLP[$i]['item_type'] == 'dir') {
  8579. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8580. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  8581. }
  8582. }
  8583. }
  8584. $parent_select = $form->addSelect(
  8585. 'parent',
  8586. get_lang('Parent'),
  8587. [],
  8588. ['onchange' => "javascript: load_cbo(this.value, 'frm_add_reading_previous');"]
  8589. );
  8590. $my_count = 0;
  8591. foreach ($arrHide as $key => $value) {
  8592. if ($my_count != 0) {
  8593. // The LP name is also the first section and is not in the same charset like the other sections.
  8594. $value['value'] = Security::remove_XSS($value['value']);
  8595. $parent_select->addOption(
  8596. $value['value'],
  8597. $key,
  8598. 'style="padding-left:'.$value['padding'].'px;"'
  8599. );
  8600. } else {
  8601. $value['value'] = Security::remove_XSS($value['value']);
  8602. $parent_select->addOption(
  8603. $value['value'],
  8604. $key,
  8605. 'style="padding-left:'.$value['padding'].'px;"'
  8606. );
  8607. }
  8608. $my_count++;
  8609. }
  8610. if (!empty($id)) {
  8611. $parent_select->setSelected($parent);
  8612. } else {
  8613. $parent_item_id = Session::read('parent_item_id', 0);
  8614. $parent_select->setSelected($parent_item_id);
  8615. }
  8616. if (is_array($arrLP)) {
  8617. reset($arrLP);
  8618. }
  8619. $arrHide = [];
  8620. $s_selected_position = null;
  8621. // POSITION
  8622. $lastPosition = null;
  8623. for ($i = 0; $i < count($arrLP); $i++) {
  8624. if (($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) &&
  8625. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM
  8626. ) {
  8627. if ((isset($extra_info['previous_item_id']) &&
  8628. $extra_info['previous_item_id'] == $arrLP[$i]['id']) || $action == 'add'
  8629. ) {
  8630. $s_selected_position = $arrLP[$i]['id'];
  8631. }
  8632. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  8633. }
  8634. $lastPosition = $arrLP[$i]['id'];
  8635. }
  8636. if (empty($s_selected_position)) {
  8637. $s_selected_position = $lastPosition;
  8638. }
  8639. $position = $form->addSelect(
  8640. 'previous',
  8641. get_lang('Position'),
  8642. []
  8643. );
  8644. $position->addOption(get_lang('FirstPosition'), 0);
  8645. foreach ($arrHide as $key => $value) {
  8646. $padding = isset($value['padding']) ? $value['padding'] : 20;
  8647. $position->addOption(
  8648. $value['value'],
  8649. $key,
  8650. 'style="padding-left:'.$padding.'px;"'
  8651. );
  8652. }
  8653. $position->setSelected($s_selected_position);
  8654. if (is_array($arrLP)) {
  8655. reset($arrLP);
  8656. }
  8657. $arrHide = [];
  8658. for ($i = 0; $i < count($arrLP); $i++) {
  8659. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir' &&
  8660. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM
  8661. ) {
  8662. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8663. }
  8664. }
  8665. if (!$no_display_add) {
  8666. $item_type = isset($extra_info['item_type']) ? $extra_info['item_type'] : null;
  8667. $edit = isset($_GET['edit']) ? $_GET['edit'] : null;
  8668. if ($extra_info == 'new' || $item_type == TOOL_READOUT_TEXT || $edit == 'true') {
  8669. if (!$no_display_edit_textarea) {
  8670. $content = '';
  8671. if (isset($_POST['content'])) {
  8672. $content = stripslashes($_POST['content']);
  8673. } elseif (is_array($extra_info)) {
  8674. $content = $this->display_document($extra_info['path'], false, false);
  8675. } elseif (is_numeric($extra_info)) {
  8676. $content = $this->display_document($extra_info, false, false);
  8677. }
  8678. // A new document, it is in the root of the repository.
  8679. if (is_array($extra_info) && $extra_info != 'new') {
  8680. } else {
  8681. $this->generate_lp_folder($_course);
  8682. }
  8683. if ($_GET['action'] == 'add_item') {
  8684. $text = get_lang('LPCreateDocument');
  8685. } else {
  8686. $text = get_lang('SaveDocument');
  8687. }
  8688. $form->addTextarea('content_lp', get_lang('Content'), ['rows' => 20]);
  8689. $form
  8690. ->defaultRenderer()
  8691. ->setElementTemplate($form->getDefaultElementTemplate(), 'content_lp');
  8692. $form->addButtonSave($text, 'submit_button');
  8693. $defaults['content_lp'] = $content;
  8694. }
  8695. } elseif (is_numeric($extra_info)) {
  8696. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  8697. $return = $this->display_document($extra_info, true, true, true);
  8698. $form->addElement('html', $return);
  8699. }
  8700. }
  8701. if (is_numeric($extra_info)) {
  8702. $form->addElement('hidden', 'path', $extra_info);
  8703. } elseif (is_array($extra_info)) {
  8704. $form->addElement('hidden', 'path', $extra_info['path']);
  8705. }
  8706. $form->addElement('hidden', 'type', TOOL_READOUT_TEXT);
  8707. $form->addElement('hidden', 'post_time', time());
  8708. $form->setDefaults($defaults);
  8709. return $form->returnForm();
  8710. }
  8711. /**
  8712. * @param array $courseInfo
  8713. * @param string $content
  8714. * @param string $title
  8715. * @param int $parentId
  8716. *
  8717. * @throws \Doctrine\ORM\ORMException
  8718. * @throws \Doctrine\ORM\OptimisticLockException
  8719. * @throws \Doctrine\ORM\TransactionRequiredException
  8720. *
  8721. * @return int
  8722. */
  8723. public function createReadOutText($courseInfo, $content = '', $title = '', $parentId = 0)
  8724. {
  8725. $creatorId = api_get_user_id();
  8726. $sessionId = api_get_session_id();
  8727. // Generates folder
  8728. $result = $this->generate_lp_folder($courseInfo);
  8729. $dir = $result['dir'];
  8730. if (empty($parentId) || $parentId == '/') {
  8731. $postDir = isset($_POST['dir']) ? $_POST['dir'] : $dir;
  8732. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir; // Please, do not modify this dirname formatting.
  8733. if ($parentId === '/') {
  8734. $dir = '/';
  8735. }
  8736. // Please, do not modify this dirname formatting.
  8737. if (strstr($dir, '..')) {
  8738. $dir = '/';
  8739. }
  8740. if (!empty($dir[0]) && $dir[0] == '.') {
  8741. $dir = substr($dir, 1);
  8742. }
  8743. if (!empty($dir[0]) && $dir[0] != '/') {
  8744. $dir = '/'.$dir;
  8745. }
  8746. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  8747. $dir .= '/';
  8748. }
  8749. } else {
  8750. $parentInfo = DocumentManager::get_document_data_by_id(
  8751. $parentId,
  8752. $courseInfo['code']
  8753. );
  8754. if (!empty($parentInfo)) {
  8755. $dir = $parentInfo['path'].'/';
  8756. }
  8757. }
  8758. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  8759. if (!is_dir($filepath)) {
  8760. $dir = '/';
  8761. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  8762. }
  8763. $originalTitle = !empty($title) ? $title : $_POST['title'];
  8764. if (!empty($title)) {
  8765. $title = api_replace_dangerous_char(stripslashes($title));
  8766. } else {
  8767. $title = api_replace_dangerous_char(stripslashes($_POST['title']));
  8768. }
  8769. $title = disable_dangerous_file($title);
  8770. $filename = $title;
  8771. $content = !empty($content) ? $content : $_POST['content_lp'];
  8772. $tmpFileName = $filename;
  8773. $i = 0;
  8774. while (file_exists($filepath.$tmpFileName.'.html')) {
  8775. $tmpFileName = $filename.'_'.++$i;
  8776. }
  8777. $filename = $tmpFileName.'.html';
  8778. $content = stripslashes($content);
  8779. if (file_exists($filepath.$filename)) {
  8780. return 0;
  8781. }
  8782. $putContent = file_put_contents($filepath.$filename, $content);
  8783. if ($putContent === false) {
  8784. return 0;
  8785. }
  8786. $fileSize = filesize($filepath.$filename);
  8787. $saveFilePath = $dir.$filename;
  8788. $documentId = add_document(
  8789. $courseInfo,
  8790. $saveFilePath,
  8791. 'file',
  8792. $fileSize,
  8793. $tmpFileName,
  8794. '',
  8795. 0, //readonly
  8796. true,
  8797. null,
  8798. $sessionId,
  8799. $creatorId
  8800. );
  8801. if (!$documentId) {
  8802. return 0;
  8803. }
  8804. api_item_property_update(
  8805. $courseInfo,
  8806. TOOL_DOCUMENT,
  8807. $documentId,
  8808. 'DocumentAdded',
  8809. $creatorId,
  8810. null,
  8811. null,
  8812. null,
  8813. null,
  8814. $sessionId
  8815. );
  8816. $newComment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
  8817. $newTitle = $originalTitle;
  8818. if ($newComment || $newTitle) {
  8819. $em = Database::getManager();
  8820. /** @var CDocument $doc */
  8821. $doc = $em->find('ChamiloCourseBundle:CDocument', $documentId);
  8822. if ($newComment) {
  8823. $doc->setComment($newComment);
  8824. }
  8825. if ($newTitle) {
  8826. $doc->setTitle($newTitle);
  8827. }
  8828. $em->persist($doc);
  8829. $em->flush();
  8830. }
  8831. return $documentId;
  8832. }
  8833. /**
  8834. * Return HTML form to add/edit a link item.
  8835. *
  8836. * @param string $action (add/edit)
  8837. * @param int $id Item ID if exists
  8838. * @param mixed $extra_info
  8839. *
  8840. * @throws Exception
  8841. * @throws HTML_QuickForm_Error
  8842. *
  8843. * @return string HTML form
  8844. */
  8845. public function display_link_form($action = 'add', $id = 0, $extra_info = '')
  8846. {
  8847. $course_id = api_get_course_int_id();
  8848. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8849. $tbl_link = Database::get_course_table(TABLE_LINK);
  8850. $item_title = '';
  8851. $item_description = '';
  8852. $item_url = '';
  8853. if ($id != 0 && is_array($extra_info)) {
  8854. $item_title = stripslashes($extra_info['title']);
  8855. $item_description = stripslashes($extra_info['description']);
  8856. $item_url = stripslashes($extra_info['url']);
  8857. } elseif (is_numeric($extra_info)) {
  8858. $extra_info = (int) $extra_info;
  8859. $sql = "SELECT title, description, url
  8860. FROM $tbl_link
  8861. WHERE c_id = $course_id AND iid = $extra_info";
  8862. $result = Database::query($sql);
  8863. $row = Database::fetch_array($result);
  8864. $item_title = $row['title'];
  8865. $item_description = $row['description'];
  8866. $item_url = $row['url'];
  8867. }
  8868. $form = new FormValidator(
  8869. 'edit_link',
  8870. 'POST',
  8871. $this->getCurrentBuildingModeURL()
  8872. );
  8873. $defaults = [];
  8874. $parent = 0;
  8875. if ($id != 0 && is_array($extra_info)) {
  8876. $parent = $extra_info['parent_item_id'];
  8877. }
  8878. $sql = "SELECT * FROM $tbl_lp_item
  8879. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8880. $result = Database::query($sql);
  8881. $arrLP = [];
  8882. while ($row = Database::fetch_array($result)) {
  8883. $arrLP[] = [
  8884. 'id' => $row['id'],
  8885. 'item_type' => $row['item_type'],
  8886. 'title' => $row['title'],
  8887. 'path' => $row['path'],
  8888. 'description' => $row['description'],
  8889. 'parent_item_id' => $row['parent_item_id'],
  8890. 'previous_item_id' => $row['previous_item_id'],
  8891. 'next_item_id' => $row['next_item_id'],
  8892. 'display_order' => $row['display_order'],
  8893. 'max_score' => $row['max_score'],
  8894. 'min_score' => $row['min_score'],
  8895. 'mastery_score' => $row['mastery_score'],
  8896. 'prerequisite' => $row['prerequisite'],
  8897. ];
  8898. }
  8899. $this->tree_array($arrLP);
  8900. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  8901. unset($this->arrMenu);
  8902. if ($action == 'add') {
  8903. $legend = get_lang('CreateTheLink');
  8904. } elseif ($action == 'move') {
  8905. $legend = get_lang('MoveCurrentLink');
  8906. } else {
  8907. $legend = get_lang('EditCurrentLink');
  8908. }
  8909. $form->addHeader($legend);
  8910. if ($action != 'move') {
  8911. $form->addText('title', get_lang('Title'), true, ['class' => 'learnpath_item_form']);
  8912. $defaults['title'] = $item_title;
  8913. }
  8914. $selectParent = $form->addSelect(
  8915. 'parent',
  8916. get_lang('Parent'),
  8917. [],
  8918. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);', 'class' => 'learnpath_item_form']
  8919. );
  8920. $selectParent->addOption($this->name, 0);
  8921. $arrHide = [
  8922. $id,
  8923. ];
  8924. $parent_item_id = Session::read('parent_item_id', 0);
  8925. for ($i = 0; $i < count($arrLP); $i++) {
  8926. if ($action != 'add') {
  8927. if (
  8928. ($arrLP[$i]['item_type'] == 'dir') &&
  8929. !in_array($arrLP[$i]['id'], $arrHide) &&
  8930. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8931. ) {
  8932. $selectParent->addOption(
  8933. $arrLP[$i]['title'],
  8934. $arrLP[$i]['id'],
  8935. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px;']
  8936. );
  8937. if ($parent == $arrLP[$i]['id']) {
  8938. $selectParent->setSelected($arrLP[$i]['id']);
  8939. }
  8940. } else {
  8941. $arrHide[] = $arrLP[$i]['id'];
  8942. }
  8943. } else {
  8944. if ($arrLP[$i]['item_type'] == 'dir') {
  8945. $selectParent->addOption(
  8946. $arrLP[$i]['title'],
  8947. $arrLP[$i]['id'],
  8948. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  8949. );
  8950. if ($parent_item_id == $arrLP[$i]['id']) {
  8951. $selectParent->setSelected($arrLP[$i]['id']);
  8952. }
  8953. }
  8954. }
  8955. }
  8956. if (is_array($arrLP)) {
  8957. reset($arrLP);
  8958. }
  8959. $selectPrevious = $form->addSelect(
  8960. 'previous',
  8961. get_lang('Position'),
  8962. [],
  8963. ['id' => 'previous', 'class' => 'learnpath_item_form']
  8964. );
  8965. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  8966. for ($i = 0; $i < count($arrLP); $i++) {
  8967. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  8968. $selectPrevious->addOption(
  8969. $arrLP[$i]['title'],
  8970. $arrLP[$i]['id']
  8971. );
  8972. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  8973. $selectPrevious->setSelected($arrLP[$i]['id']);
  8974. } elseif ($action == 'add') {
  8975. $selectPrevious->setSelected($arrLP[$i]['id']);
  8976. }
  8977. }
  8978. }
  8979. if ($action != 'move') {
  8980. $urlAttributes = ['class' => 'learnpath_item_form'];
  8981. if (is_numeric($extra_info)) {
  8982. $urlAttributes['disabled'] = 'disabled';
  8983. }
  8984. $form->addElement('url', 'url', get_lang('Url'), $urlAttributes);
  8985. $defaults['url'] = $item_url;
  8986. $arrHide = [];
  8987. for ($i = 0; $i < count($arrLP); $i++) {
  8988. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  8989. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8990. }
  8991. }
  8992. }
  8993. if ($action == 'add') {
  8994. $form->addButtonSave(get_lang('AddLinkToCourse'), 'submit_button');
  8995. } else {
  8996. $form->addButtonSave(get_lang('EditCurrentLink'), 'submit_button');
  8997. }
  8998. if ($action == 'move') {
  8999. $form->addHidden('title', $item_title);
  9000. $form->addHidden('description', $item_description);
  9001. }
  9002. if (is_numeric($extra_info)) {
  9003. $form->addHidden('path', $extra_info);
  9004. } elseif (is_array($extra_info)) {
  9005. $form->addHidden('path', $extra_info['path']);
  9006. }
  9007. $form->addHidden('type', TOOL_LINK);
  9008. $form->addHidden('post_time', time());
  9009. $form->setDefaults($defaults);
  9010. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  9011. }
  9012. /**
  9013. * Return HTML form to add/edit a student publication (work).
  9014. *
  9015. * @param string $action
  9016. * @param int $id Item ID if already exists
  9017. * @param string $extra_info
  9018. *
  9019. * @throws Exception
  9020. *
  9021. * @return string HTML form
  9022. */
  9023. public function display_student_publication_form(
  9024. $action = 'add',
  9025. $id = 0,
  9026. $extra_info = ''
  9027. ) {
  9028. $course_id = api_get_course_int_id();
  9029. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  9030. $tbl_publication = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  9031. $item_title = get_lang('Student_publication');
  9032. if ($id != 0 && is_array($extra_info)) {
  9033. $item_title = stripslashes($extra_info['title']);
  9034. $item_description = stripslashes($extra_info['description']);
  9035. } elseif (is_numeric($extra_info)) {
  9036. $extra_info = (int) $extra_info;
  9037. $sql = "SELECT title, description
  9038. FROM $tbl_publication
  9039. WHERE c_id = $course_id AND id = ".$extra_info;
  9040. $result = Database::query($sql);
  9041. $row = Database::fetch_array($result);
  9042. if ($row) {
  9043. $item_title = $row['title'];
  9044. }
  9045. }
  9046. $parent = 0;
  9047. if ($id != 0 && is_array($extra_info)) {
  9048. $parent = $extra_info['parent_item_id'];
  9049. }
  9050. $sql = "SELECT * FROM $tbl_lp_item
  9051. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  9052. $result = Database::query($sql);
  9053. $arrLP = [];
  9054. while ($row = Database::fetch_array($result)) {
  9055. $arrLP[] = [
  9056. 'id' => $row['iid'],
  9057. 'item_type' => $row['item_type'],
  9058. 'title' => $row['title'],
  9059. 'path' => $row['path'],
  9060. 'description' => $row['description'],
  9061. 'parent_item_id' => $row['parent_item_id'],
  9062. 'previous_item_id' => $row['previous_item_id'],
  9063. 'next_item_id' => $row['next_item_id'],
  9064. 'display_order' => $row['display_order'],
  9065. 'max_score' => $row['max_score'],
  9066. 'min_score' => $row['min_score'],
  9067. 'mastery_score' => $row['mastery_score'],
  9068. 'prerequisite' => $row['prerequisite'],
  9069. ];
  9070. }
  9071. $this->tree_array($arrLP);
  9072. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  9073. unset($this->arrMenu);
  9074. $form = new FormValidator('frm_student_publication', 'post', '#');
  9075. if ($action == 'add') {
  9076. $form->addHeader(get_lang('Student_publication'));
  9077. } elseif ($action == 'move') {
  9078. $form->addHeader(get_lang('MoveCurrentStudentPublication'));
  9079. } else {
  9080. $form->addHeader(get_lang('EditCurrentStudentPublication'));
  9081. }
  9082. if ($action != 'move') {
  9083. $form->addText(
  9084. 'title',
  9085. get_lang('Title'),
  9086. true,
  9087. ['class' => 'learnpath_item_form', 'id' => 'idTitle']
  9088. );
  9089. }
  9090. $parentSelect = $form->addSelect(
  9091. 'parent',
  9092. get_lang('Parent'),
  9093. ['0' => $this->name],
  9094. [
  9095. 'onchange' => 'javascript: load_cbo(this.value);',
  9096. 'class' => 'learnpath_item_form',
  9097. 'id' => 'idParent',
  9098. ]
  9099. );
  9100. $arrHide = [$id];
  9101. for ($i = 0; $i < count($arrLP); $i++) {
  9102. if ($action != 'add') {
  9103. if (
  9104. ($arrLP[$i]['item_type'] == 'dir') &&
  9105. !in_array($arrLP[$i]['id'], $arrHide) &&
  9106. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  9107. ) {
  9108. $parentSelect->addOption(
  9109. $arrLP[$i]['title'],
  9110. $arrLP[$i]['id'],
  9111. ['style' => 'padding-left: '.(($arrLP[$i]['depth'] * 10) + 20).'px;']
  9112. );
  9113. if ($parent == $arrLP[$i]['id']) {
  9114. $parentSelect->setSelected($arrLP[$i]['id']);
  9115. }
  9116. } else {
  9117. $arrHide[] = $arrLP[$i]['id'];
  9118. }
  9119. } else {
  9120. if ($arrLP[$i]['item_type'] == 'dir') {
  9121. $parentSelect->addOption(
  9122. $arrLP[$i]['title'],
  9123. $arrLP[$i]['id'],
  9124. ['style' => 'padding-left: '.(($arrLP[$i]['depth'] * 10) + 20).'px;']
  9125. );
  9126. if ($parent == $arrLP[$i]['id']) {
  9127. $parentSelect->setSelected($arrLP[$i]['id']);
  9128. }
  9129. }
  9130. }
  9131. }
  9132. if (is_array($arrLP)) {
  9133. reset($arrLP);
  9134. }
  9135. $previousSelect = $form->addSelect(
  9136. 'previous',
  9137. get_lang('Position'),
  9138. ['0' => get_lang('FirstPosition')],
  9139. ['id' => 'previous', 'class' => 'learnpath_item_form']
  9140. );
  9141. for ($i = 0; $i < count($arrLP); $i++) {
  9142. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  9143. $previousSelect->addOption(
  9144. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  9145. $arrLP[$i]['id']
  9146. );
  9147. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  9148. $previousSelect->setSelected($arrLP[$i]['id']);
  9149. } elseif ($action == 'add') {
  9150. $previousSelect->setSelected($arrLP[$i]['id']);
  9151. }
  9152. }
  9153. }
  9154. if ($action == 'add') {
  9155. $form->addButtonCreate(get_lang('AddAssignmentToCourse'), 'submit_button');
  9156. } else {
  9157. $form->addButtonCreate(get_lang('EditCurrentStudentPublication'), 'submit_button');
  9158. }
  9159. if ($action == 'move') {
  9160. $form->addHidden('title', $item_title);
  9161. $form->addHidden('description', $item_description);
  9162. }
  9163. if (is_numeric($extra_info)) {
  9164. $form->addHidden('path', $extra_info);
  9165. } elseif (is_array($extra_info)) {
  9166. $form->addHidden('path', $extra_info['path']);
  9167. }
  9168. $form->addHidden('type', TOOL_STUDENTPUBLICATION);
  9169. $form->addHidden('post_time', time());
  9170. $form->setDefaults(['title' => $item_title]);
  9171. $return = '<div class="sectioncomment">';
  9172. $return .= $form->returnForm();
  9173. $return .= '</div>';
  9174. return $return;
  9175. }
  9176. /**
  9177. * Displays the menu for manipulating a step.
  9178. *
  9179. * @param id $item_id
  9180. * @param string $item_type
  9181. *
  9182. * @return string
  9183. */
  9184. public function display_manipulate($item_id, $item_type = TOOL_DOCUMENT)
  9185. {
  9186. $_course = api_get_course_info();
  9187. $course_code = api_get_course_id();
  9188. $return = '<div class="actions">';
  9189. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  9190. $item_id = (int) $item_id;
  9191. $sql = "SELECT * FROM $tbl_lp_item
  9192. WHERE iid = ".$item_id;
  9193. $result = Database::query($sql);
  9194. $row = Database::fetch_assoc($result);
  9195. $audio_player = null;
  9196. // We display an audio player if needed.
  9197. if (!empty($row['audio'])) {
  9198. $webAudioPath = '../..'.api_get_path(REL_COURSE_PATH).$_course['path'].'/document/audio/'.$row['audio'];
  9199. $audio_player .= '<div class="lp_mediaplayer" id="container">'
  9200. .'<audio src="'.$webAudioPath.'" controls>'
  9201. .'</div><br>';
  9202. }
  9203. $url = api_get_self().'?'.api_get_cidreq().'&view=build&id='.$item_id.'&lp_id='.$this->lp_id;
  9204. if ($item_type != TOOL_LP_FINAL_ITEM) {
  9205. $return .= Display::url(
  9206. Display::return_icon(
  9207. 'edit.png',
  9208. get_lang('Edit'),
  9209. [],
  9210. ICON_SIZE_SMALL
  9211. ),
  9212. $url.'&action=edit_item&path_item='.$row['path']
  9213. );
  9214. $return .= Display::url(
  9215. Display::return_icon(
  9216. 'move.png',
  9217. get_lang('Move'),
  9218. [],
  9219. ICON_SIZE_SMALL
  9220. ),
  9221. $url.'&action=move_item'
  9222. );
  9223. }
  9224. // Commented for now as prerequisites cannot be added to chapters.
  9225. if ($item_type != 'dir') {
  9226. $return .= Display::url(
  9227. Display::return_icon(
  9228. 'accept.png',
  9229. get_lang('LearnpathPrerequisites'),
  9230. [],
  9231. ICON_SIZE_SMALL
  9232. ),
  9233. $url.'&action=edit_item_prereq'
  9234. );
  9235. }
  9236. $return .= Display::url(
  9237. Display::return_icon(
  9238. 'delete.png',
  9239. get_lang('Delete'),
  9240. [],
  9241. ICON_SIZE_SMALL
  9242. ),
  9243. $url.'&action=delete_item'
  9244. );
  9245. if (in_array($item_type, [TOOL_DOCUMENT, TOOL_LP_FINAL_ITEM, TOOL_HOTPOTATOES])) {
  9246. $documentData = DocumentManager::get_document_data_by_id($row['path'], $course_code);
  9247. if (empty($documentData)) {
  9248. // Try with iid
  9249. $table = Database::get_course_table(TABLE_DOCUMENT);
  9250. $sql = "SELECT path FROM $table
  9251. WHERE
  9252. c_id = ".api_get_course_int_id()." AND
  9253. iid = ".$row['path']." AND
  9254. path NOT LIKE '%_DELETED_%'";
  9255. $result = Database::query($sql);
  9256. $documentData = Database::fetch_array($result);
  9257. if ($documentData) {
  9258. $documentData['absolute_path_from_document'] = '/document'.$documentData['path'];
  9259. }
  9260. }
  9261. if (isset($documentData['absolute_path_from_document'])) {
  9262. $return .= get_lang('File').': '.$documentData['absolute_path_from_document'];
  9263. }
  9264. }
  9265. $return .= '</div>';
  9266. if (!empty($audio_player)) {
  9267. $return .= $audio_player;
  9268. }
  9269. return $return;
  9270. }
  9271. /**
  9272. * Creates the javascript needed for filling up the checkboxes without page reload.
  9273. *
  9274. * @return string
  9275. */
  9276. public function get_js_dropdown_array()
  9277. {
  9278. $course_id = api_get_course_int_id();
  9279. $return = 'var child_name = new Array();'."\n";
  9280. $return .= 'var child_value = new Array();'."\n\n";
  9281. $return .= 'child_name[0] = new Array();'."\n";
  9282. $return .= 'child_value[0] = new Array();'."\n\n";
  9283. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  9284. $sql = "SELECT * FROM ".$tbl_lp_item."
  9285. WHERE
  9286. c_id = $course_id AND
  9287. lp_id = ".$this->lp_id." AND
  9288. parent_item_id = 0
  9289. ORDER BY display_order ASC";
  9290. $res_zero = Database::query($sql);
  9291. $i = 0;
  9292. while ($row_zero = Database::fetch_array($res_zero)) {
  9293. if ($row_zero['item_type'] !== TOOL_LP_FINAL_ITEM) {
  9294. if ($row_zero['item_type'] == TOOL_QUIZ) {
  9295. $row_zero['title'] = Exercise::get_formated_title_variable($row_zero['title']);
  9296. }
  9297. $js_var = json_encode(get_lang('After').' '.$row_zero['title']);
  9298. $return .= 'child_name[0]['.$i.'] = '.$js_var.' ;'."\n";
  9299. $return .= 'child_value[0]['.$i++.'] = "'.$row_zero['iid'].'";'."\n";
  9300. }
  9301. }
  9302. $return .= "\n";
  9303. $sql = "SELECT * FROM $tbl_lp_item
  9304. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  9305. $res = Database::query($sql);
  9306. while ($row = Database::fetch_array($res)) {
  9307. $sql_parent = "SELECT * FROM ".$tbl_lp_item."
  9308. WHERE
  9309. c_id = ".$course_id." AND
  9310. parent_item_id = ".$row['iid']."
  9311. ORDER BY display_order ASC";
  9312. $res_parent = Database::query($sql_parent);
  9313. $i = 0;
  9314. $return .= 'child_name['.$row['iid'].'] = new Array();'."\n";
  9315. $return .= 'child_value['.$row['iid'].'] = new Array();'."\n\n";
  9316. while ($row_parent = Database::fetch_array($res_parent)) {
  9317. $js_var = json_encode(get_lang('After').' '.$row_parent['title']);
  9318. $return .= 'child_name['.$row['iid'].']['.$i.'] = '.$js_var.' ;'."\n";
  9319. $return .= 'child_value['.$row['iid'].']['.$i++.'] = "'.$row_parent['iid'].'";'."\n";
  9320. }
  9321. $return .= "\n";
  9322. }
  9323. $return .= "
  9324. function load_cbo(id) {
  9325. if (!id) {
  9326. return false;
  9327. }
  9328. var cbo = document.getElementById('previous');
  9329. for(var i = cbo.length - 1; i > 0; i--) {
  9330. cbo.options[i] = null;
  9331. }
  9332. var k=0;
  9333. for(var i = 1; i <= child_name[id].length; i++){
  9334. var option = new Option(child_name[id][i - 1], child_value[id][i - 1]);
  9335. option.style.paddingLeft = '40px';
  9336. cbo.options[i] = option;
  9337. k = i;
  9338. }
  9339. cbo.options[k].selected = true;
  9340. $('#previous').selectpicker('refresh');
  9341. }";
  9342. return $return;
  9343. }
  9344. /**
  9345. * Display the form to allow moving an item.
  9346. *
  9347. * @param int $item_id Item ID
  9348. *
  9349. * @throws Exception
  9350. * @throws HTML_QuickForm_Error
  9351. *
  9352. * @return string HTML form
  9353. */
  9354. public function display_move_item($item_id)
  9355. {
  9356. $return = '';
  9357. if (is_numeric($item_id)) {
  9358. $item_id = (int) $item_id;
  9359. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  9360. $sql = "SELECT * FROM $tbl_lp_item
  9361. WHERE iid = $item_id";
  9362. $res = Database::query($sql);
  9363. $row = Database::fetch_array($res);
  9364. switch ($row['item_type']) {
  9365. case 'dir':
  9366. case 'asset':
  9367. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9368. $return .= $this->display_item_form(
  9369. $row['item_type'],
  9370. get_lang('MoveCurrentChapter'),
  9371. 'move',
  9372. $item_id,
  9373. $row
  9374. );
  9375. break;
  9376. case TOOL_DOCUMENT:
  9377. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9378. $return .= $this->display_document_form('move', $item_id, $row);
  9379. break;
  9380. case TOOL_LINK:
  9381. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9382. $return .= $this->display_link_form('move', $item_id, $row);
  9383. break;
  9384. case TOOL_HOTPOTATOES:
  9385. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9386. $return .= $this->display_link_form('move', $item_id, $row);
  9387. break;
  9388. case TOOL_QUIZ:
  9389. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9390. $return .= $this->display_quiz_form('move', $item_id, $row);
  9391. break;
  9392. case TOOL_STUDENTPUBLICATION:
  9393. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9394. $return .= $this->display_student_publication_form('move', $item_id, $row);
  9395. break;
  9396. case TOOL_FORUM:
  9397. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9398. $return .= $this->display_forum_form('move', $item_id, $row);
  9399. break;
  9400. case TOOL_THREAD:
  9401. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9402. $return .= $this->display_forum_form('move', $item_id, $row);
  9403. break;
  9404. }
  9405. }
  9406. return $return;
  9407. }
  9408. /**
  9409. * Return HTML form to allow prerequisites selection.
  9410. *
  9411. * @todo use FormValidator
  9412. *
  9413. * @param int Item ID
  9414. *
  9415. * @return string HTML form
  9416. */
  9417. public function display_item_prerequisites_form($item_id = 0)
  9418. {
  9419. $course_id = api_get_course_int_id();
  9420. $item_id = (int) $item_id;
  9421. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  9422. /* Current prerequisite */
  9423. $sql = "SELECT * FROM $tbl_lp_item
  9424. WHERE iid = $item_id";
  9425. $result = Database::query($sql);
  9426. $row = Database::fetch_array($result);
  9427. $prerequisiteId = $row['prerequisite'];
  9428. $return = '<legend>';
  9429. $return .= get_lang('AddEditPrerequisites');
  9430. $return .= '</legend>';
  9431. $return .= '<form method="POST">';
  9432. $return .= '<div class="table-responsive">';
  9433. $return .= '<table class="table table-hover">';
  9434. $return .= '<thead>';
  9435. $return .= '<tr>';
  9436. $return .= '<th>'.get_lang('LearnpathPrerequisites').'</th>';
  9437. $return .= '<th width="140">'.get_lang('Minimum').'</th>';
  9438. $return .= '<th width="140">'.get_lang('Maximum').'</th>';
  9439. $return .= '</tr>';
  9440. $return .= '</thead>';
  9441. // Adding the none option to the prerequisites see http://www.chamilo.org/es/node/146
  9442. $return .= '<tbody>';
  9443. $return .= '<tr>';
  9444. $return .= '<td colspan="3">';
  9445. $return .= '<div class="radio learnpath"><label for="idNone">';
  9446. $return .= '<input checked="checked" id="idNone" name="prerequisites" type="radio" />';
  9447. $return .= get_lang('None').'</label>';
  9448. $return .= '</div>';
  9449. $return .= '</tr>';
  9450. $sql = "SELECT * FROM $tbl_lp_item
  9451. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  9452. $result = Database::query($sql);
  9453. $arrLP = [];
  9454. $selectedMinScore = [];
  9455. $selectedMaxScore = [];
  9456. $masteryScore = [];
  9457. while ($row = Database::fetch_array($result)) {
  9458. if ($row['iid'] == $item_id) {
  9459. $selectedMinScore[$row['prerequisite']] = $row['prerequisite_min_score'];
  9460. $selectedMaxScore[$row['prerequisite']] = $row['prerequisite_max_score'];
  9461. }
  9462. $masteryScore[$row['iid']] = $row['mastery_score'];
  9463. $arrLP[] = [
  9464. 'id' => $row['iid'],
  9465. 'item_type' => $row['item_type'],
  9466. 'title' => $row['title'],
  9467. 'ref' => $row['ref'],
  9468. 'description' => $row['description'],
  9469. 'parent_item_id' => $row['parent_item_id'],
  9470. 'previous_item_id' => $row['previous_item_id'],
  9471. 'next_item_id' => $row['next_item_id'],
  9472. 'max_score' => $row['max_score'],
  9473. 'min_score' => $row['min_score'],
  9474. 'mastery_score' => $row['mastery_score'],
  9475. 'prerequisite' => $row['prerequisite'],
  9476. 'display_order' => $row['display_order'],
  9477. 'prerequisite_min_score' => $row['prerequisite_min_score'],
  9478. 'prerequisite_max_score' => $row['prerequisite_max_score'],
  9479. ];
  9480. }
  9481. $this->tree_array($arrLP);
  9482. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  9483. unset($this->arrMenu);
  9484. for ($i = 0; $i < count($arrLP); $i++) {
  9485. $item = $arrLP[$i];
  9486. if ($item['id'] == $item_id) {
  9487. break;
  9488. }
  9489. $selectedMaxScoreValue = isset($selectedMaxScore[$item['id']]) ? $selectedMaxScore[$item['id']] : $item['max_score'];
  9490. $selectedMinScoreValue = isset($selectedMinScore[$item['id']]) ? $selectedMinScore[$item['id']] : 0;
  9491. $masteryScoreAsMinValue = isset($masteryScore[$item['id']]) ? $masteryScore[$item['id']] : 0;
  9492. $return .= '<tr>';
  9493. $return .= '<td '.(($item['item_type'] != TOOL_QUIZ && $item['item_type'] != TOOL_HOTPOTATOES) ? ' colspan="3"' : '').'>';
  9494. $return .= '<div style="margin-left:'.($item['depth'] * 20).'px;" class="radio learnpath">';
  9495. $return .= '<label for="id'.$item['id'].'">';
  9496. $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'].'" />';
  9497. $icon_name = str_replace(' ', '', $item['item_type']);
  9498. if (file_exists('../img/lp_'.$icon_name.'.png')) {
  9499. $return .= Display::return_icon('lp_'.$icon_name.'.png');
  9500. } else {
  9501. if (file_exists('../img/lp_'.$icon_name.'.png')) {
  9502. $return .= Display::return_icon('lp_'.$icon_name.'.png');
  9503. } else {
  9504. $return .= Display::return_icon('folder_document.png');
  9505. }
  9506. }
  9507. $return .= $item['title'].'</label>';
  9508. $return .= '</div>';
  9509. $return .= '</td>';
  9510. if ($item['item_type'] == TOOL_QUIZ) {
  9511. // lets update max_score Quiz information depending of the Quiz Advanced properties
  9512. $lpItemObj = new LpItem($course_id, $item['id']);
  9513. $exercise = new Exercise($course_id);
  9514. $exercise->read($lpItemObj->path);
  9515. $lpItemObj->max_score = $exercise->get_max_score();
  9516. $lpItemObj->update();
  9517. $item['max_score'] = $lpItemObj->max_score;
  9518. if (empty($selectedMinScoreValue) && !empty($masteryScoreAsMinValue)) {
  9519. // Backwards compatibility with 1.9.x use mastery_score as min value
  9520. $selectedMinScoreValue = $masteryScoreAsMinValue;
  9521. }
  9522. $return .= '<td>';
  9523. $return .= '<input
  9524. class="form-control"
  9525. size="4" maxlength="3"
  9526. name="min_'.$item['id'].'"
  9527. type="number"
  9528. min="0"
  9529. step="1"
  9530. max="'.$item['max_score'].'"
  9531. value="'.$selectedMinScoreValue.'"
  9532. />';
  9533. $return .= '</td>';
  9534. $return .= '<td>';
  9535. $return .= '<input
  9536. class="form-control"
  9537. size="4"
  9538. maxlength="3"
  9539. name="max_'.$item['id'].'"
  9540. type="number"
  9541. min="0"
  9542. step="1"
  9543. max="'.$item['max_score'].'"
  9544. value="'.$selectedMaxScoreValue.'"
  9545. />';
  9546. $return .= '</td>';
  9547. }
  9548. if ($item['item_type'] == TOOL_HOTPOTATOES) {
  9549. $return .= '<td>';
  9550. $return .= '<input
  9551. size="4"
  9552. maxlength="3"
  9553. name="min_'.$item['id'].'"
  9554. type="number"
  9555. min="0"
  9556. step="1"
  9557. max="'.$item['max_score'].'"
  9558. value="'.$selectedMinScoreValue.'"
  9559. />';
  9560. $return .= '</td>';
  9561. $return .= '<td>';
  9562. $return .= '<input
  9563. size="4"
  9564. maxlength="3"
  9565. name="max_'.$item['id'].'"
  9566. type="number"
  9567. min="0"
  9568. step="1"
  9569. max="'.$item['max_score'].'"
  9570. value="'.$selectedMaxScoreValue.'"
  9571. />';
  9572. $return .= '</td>';
  9573. }
  9574. $return .= '</tr>';
  9575. }
  9576. $return .= '<tr>';
  9577. $return .= '</tr>';
  9578. $return .= '</tbody>';
  9579. $return .= '</table>';
  9580. $return .= '</div>';
  9581. $return .= '<div class="form-group">';
  9582. $return .= '<button class="btn btn-primary" name="submit_button" type="submit">'.
  9583. get_lang('ModifyPrerequisites').'</button>';
  9584. $return .= '</form>';
  9585. return $return;
  9586. }
  9587. /**
  9588. * Return HTML list to allow prerequisites selection for lp.
  9589. *
  9590. * @return string HTML form
  9591. */
  9592. public function display_lp_prerequisites_list()
  9593. {
  9594. $course_id = api_get_course_int_id();
  9595. $lp_id = $this->lp_id;
  9596. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  9597. // get current prerequisite
  9598. $sql = "SELECT * FROM $tbl_lp WHERE iid = $lp_id ";
  9599. $result = Database::query($sql);
  9600. $row = Database::fetch_array($result);
  9601. $prerequisiteId = $row['prerequisite'];
  9602. $session_id = api_get_session_id();
  9603. $session_condition = api_get_session_condition($session_id, true, true);
  9604. $sql = "SELECT * FROM $tbl_lp
  9605. WHERE c_id = $course_id $session_condition
  9606. ORDER BY display_order ";
  9607. $rs = Database::query($sql);
  9608. $return = '';
  9609. $return .= '<select name="prerequisites" class="form-control">';
  9610. $return .= '<option value="0">'.get_lang('None').'</option>';
  9611. if (Database::num_rows($rs) > 0) {
  9612. while ($row = Database::fetch_array($rs)) {
  9613. if ($row['id'] == $lp_id) {
  9614. continue;
  9615. }
  9616. $return .= '<option value="'.$row['id'].'" '.(($row['id'] == $prerequisiteId) ? ' selected ' : '').'>'.$row['name'].'</option>';
  9617. }
  9618. }
  9619. $return .= '</select>';
  9620. return $return;
  9621. }
  9622. /**
  9623. * Creates a list with all the documents in it.
  9624. *
  9625. * @param bool $showInvisibleFiles
  9626. *
  9627. * @throws Exception
  9628. * @throws HTML_QuickForm_Error
  9629. *
  9630. * @return string
  9631. */
  9632. public function get_documents($showInvisibleFiles = false)
  9633. {
  9634. $course_info = api_get_course_info();
  9635. $sessionId = api_get_session_id();
  9636. $documentTree = DocumentManager::get_document_preview(
  9637. $course_info,
  9638. $this->lp_id,
  9639. null,
  9640. $sessionId,
  9641. true,
  9642. null,
  9643. null,
  9644. $showInvisibleFiles,
  9645. true
  9646. );
  9647. $headers = [
  9648. get_lang('Files'),
  9649. get_lang('CreateTheDocument'),
  9650. get_lang('CreateReadOutText'),
  9651. get_lang('Upload'),
  9652. ];
  9653. $form = new FormValidator(
  9654. 'form_upload',
  9655. 'POST',
  9656. $this->getCurrentBuildingModeURL(),
  9657. '',
  9658. ['enctype' => 'multipart/form-data']
  9659. );
  9660. $folders = DocumentManager::get_all_document_folders(
  9661. api_get_course_info(),
  9662. 0,
  9663. true
  9664. );
  9665. $lpPathInfo = $this->generate_lp_folder(api_get_course_info());
  9666. DocumentManager::build_directory_selector(
  9667. $folders,
  9668. $lpPathInfo['id'],
  9669. [],
  9670. true,
  9671. $form,
  9672. 'directory_parent_id'
  9673. );
  9674. $group = [
  9675. $form->createElement(
  9676. 'radio',
  9677. 'if_exists',
  9678. get_lang('UplWhatIfFileExists'),
  9679. get_lang('UplDoNothing'),
  9680. 'nothing'
  9681. ),
  9682. $form->createElement(
  9683. 'radio',
  9684. 'if_exists',
  9685. null,
  9686. get_lang('UplOverwriteLong'),
  9687. 'overwrite'
  9688. ),
  9689. $form->createElement(
  9690. 'radio',
  9691. 'if_exists',
  9692. null,
  9693. get_lang('UplRenameLong'),
  9694. 'rename'
  9695. ),
  9696. ];
  9697. $form->addGroup($group, null, get_lang('UplWhatIfFileExists'));
  9698. $fileExistsOption = api_get_setting('document_if_file_exists_option');
  9699. $defaultFileExistsOption = 'rename';
  9700. if (!empty($fileExistsOption)) {
  9701. $defaultFileExistsOption = $fileExistsOption;
  9702. }
  9703. $form->setDefaults(['if_exists' => $defaultFileExistsOption]);
  9704. // Check box options
  9705. $form->addElement(
  9706. 'checkbox',
  9707. 'unzip',
  9708. get_lang('Options'),
  9709. get_lang('Uncompress')
  9710. );
  9711. $url = api_get_path(WEB_AJAX_PATH).'document.ajax.php?'.api_get_cidreq().'&a=upload_file&curdirpath=';
  9712. $form->addMultipleUpload($url);
  9713. $new = $this->display_document_form('add', 0);
  9714. $frmReadOutText = $this->displayFrmReadOutText('add');
  9715. $tabs = Display::tabs(
  9716. $headers,
  9717. [$documentTree, $new, $frmReadOutText, $form->returnForm()],
  9718. 'subtab'
  9719. );
  9720. return $tabs;
  9721. }
  9722. /**
  9723. * Creates a list with all the exercises (quiz) in it.
  9724. *
  9725. * @return string
  9726. */
  9727. public function get_exercises()
  9728. {
  9729. $course_id = api_get_course_int_id();
  9730. $session_id = api_get_session_id();
  9731. $userInfo = api_get_user_info();
  9732. // New for hotpotatoes.
  9733. $uploadPath = DIR_HOTPOTATOES; //defined in main_api
  9734. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  9735. $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  9736. $condition_session = api_get_session_condition($session_id, true, true);
  9737. $setting = api_get_configuration_value('show_invisible_exercise_in_lp_list');
  9738. $activeCondition = ' active <> -1 ';
  9739. if ($setting) {
  9740. $activeCondition = ' active = 1 ';
  9741. }
  9742. $sql_quiz = "SELECT * FROM $tbl_quiz
  9743. WHERE c_id = $course_id AND $activeCondition $condition_session
  9744. ORDER BY title ASC";
  9745. $sql_hot = "SELECT * FROM $tbl_doc
  9746. WHERE c_id = $course_id AND path LIKE '".$uploadPath."/%/%htm%' $condition_session
  9747. ORDER BY id ASC";
  9748. $res_quiz = Database::query($sql_quiz);
  9749. $res_hot = Database::query($sql_hot);
  9750. $return = '<ul class="lp_resource">';
  9751. $return .= '<li class="lp_resource_element">';
  9752. $return .= Display::return_icon('new_exercice.png');
  9753. $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'exercise/exercise_admin.php?'.api_get_cidreq().'&lp_id='.$this->lp_id.'">'.
  9754. get_lang('NewExercise').'</a>';
  9755. $return .= '</li>';
  9756. $previewIcon = Display::return_icon(
  9757. 'preview_view.png',
  9758. get_lang('Preview')
  9759. );
  9760. $quizIcon = Display::return_icon('quiz.png', '', [], ICON_SIZE_TINY);
  9761. $moveIcon = Display::return_icon('move_everywhere.png', get_lang('Move'), [], ICON_SIZE_TINY);
  9762. $exerciseUrl = api_get_path(WEB_CODE_PATH).'exercise/showinframes.php?'.api_get_cidreq();
  9763. // Display hotpotatoes
  9764. while ($row_hot = Database::fetch_array($res_hot)) {
  9765. $link = Display::url(
  9766. $previewIcon,
  9767. $exerciseUrl.'&file='.$row_hot['path'],
  9768. ['target' => '_blank']
  9769. );
  9770. $return .= '<li class="lp_resource_element" data_id="'.$row_hot['id'].'" data_type="hotpotatoes" title="'.$row_hot['title'].'" >';
  9771. $return .= '<a class="moved" href="#">';
  9772. $return .= Display::return_icon(
  9773. 'move_everywhere.png',
  9774. get_lang('Move'),
  9775. [],
  9776. ICON_SIZE_TINY
  9777. );
  9778. $return .= '</a> ';
  9779. $return .= Display::return_icon('hotpotatoes_s.png');
  9780. $return .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_HOTPOTATOES.'&file='.$row_hot['id'].'&lp_id='.$this->lp_id.'">'.
  9781. ((!empty($row_hot['comment'])) ? $row_hot['comment'] : Security::remove_XSS($row_hot['title'])).$link.'</a>';
  9782. $return .= '</li>';
  9783. }
  9784. $exerciseUrl = api_get_path(WEB_CODE_PATH).'exercise/overview.php?'.api_get_cidreq();
  9785. while ($row_quiz = Database::fetch_array($res_quiz)) {
  9786. $title = strip_tags(
  9787. api_html_entity_decode($row_quiz['title'])
  9788. );
  9789. $visibility = api_get_item_visibility(
  9790. ['real_id' => $course_id],
  9791. TOOL_QUIZ,
  9792. $row_quiz['iid'],
  9793. $session_id
  9794. );
  9795. $link = Display::url(
  9796. $previewIcon,
  9797. $exerciseUrl.'&exerciseId='.$row_quiz['id'],
  9798. ['target' => '_blank']
  9799. );
  9800. $return .= '<li class="lp_resource_element" data_id="'.$row_quiz['id'].'" data_type="quiz" title="'.$title.'" >';
  9801. $return .= Display::url($moveIcon, '#', ['class' => 'moved']);
  9802. $return .= $quizIcon;
  9803. $sessionStar = api_get_session_image(
  9804. $row_quiz['session_id'],
  9805. $userInfo['status']
  9806. );
  9807. $return .= Display::url(
  9808. Security::remove_XSS(cut($title, 80)).$link.$sessionStar,
  9809. api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_QUIZ.'&file='.$row_quiz['id'].'&lp_id='.$this->lp_id,
  9810. [
  9811. 'class' => $visibility == 0 ? 'moved text-muted' : 'moved',
  9812. ]
  9813. );
  9814. $return .= '</li>';
  9815. }
  9816. $return .= '</ul>';
  9817. return $return;
  9818. }
  9819. /**
  9820. * Creates a list with all the links in it.
  9821. *
  9822. * @return string
  9823. */
  9824. public function get_links()
  9825. {
  9826. $selfUrl = api_get_self();
  9827. $courseIdReq = api_get_cidreq();
  9828. $course = api_get_course_info();
  9829. $userInfo = api_get_user_info();
  9830. $course_id = $course['real_id'];
  9831. $tbl_link = Database::get_course_table(TABLE_LINK);
  9832. $linkCategoryTable = Database::get_course_table(TABLE_LINK_CATEGORY);
  9833. $moveEverywhereIcon = Display::return_icon(
  9834. 'move_everywhere.png',
  9835. get_lang('Move'),
  9836. [],
  9837. ICON_SIZE_TINY
  9838. );
  9839. $session_id = api_get_session_id();
  9840. $condition_session = api_get_session_condition(
  9841. $session_id,
  9842. true,
  9843. true,
  9844. 'link.session_id'
  9845. );
  9846. $sql = "SELECT
  9847. link.id as link_id,
  9848. link.title as link_title,
  9849. link.session_id as link_session_id,
  9850. link.category_id as category_id,
  9851. link_category.category_title as category_title
  9852. FROM $tbl_link as link
  9853. LEFT JOIN $linkCategoryTable as link_category
  9854. ON (link.category_id = link_category.id AND link.c_id = link_category.c_id)
  9855. WHERE link.c_id = $course_id $condition_session
  9856. ORDER BY link_category.category_title ASC, link.title ASC";
  9857. $result = Database::query($sql);
  9858. $categorizedLinks = [];
  9859. $categories = [];
  9860. while ($link = Database::fetch_array($result)) {
  9861. if (!$link['category_id']) {
  9862. $link['category_title'] = get_lang('Uncategorized');
  9863. }
  9864. $categories[$link['category_id']] = $link['category_title'];
  9865. $categorizedLinks[$link['category_id']][$link['link_id']] = $link;
  9866. }
  9867. $linksHtmlCode =
  9868. '<script>
  9869. function toggle_tool(tool, id) {
  9870. if(document.getElementById(tool+"_"+id+"_content").style.display == "none"){
  9871. document.getElementById(tool+"_"+id+"_content").style.display = "block";
  9872. document.getElementById(tool+"_"+id+"_opener").src = "'.Display::returnIconPath('remove.gif').'";
  9873. } else {
  9874. document.getElementById(tool+"_"+id+"_content").style.display = "none";
  9875. document.getElementById(tool+"_"+id+"_opener").src = "'.Display::returnIconPath('add.gif').'";
  9876. }
  9877. }
  9878. </script>
  9879. <ul class="lp_resource">
  9880. <li class="lp_resource_element">
  9881. '.Display::return_icon('linksnew.gif').'
  9882. <a href="'.api_get_path(WEB_CODE_PATH).'link/link.php?'.$courseIdReq.'&action=addlink&lp_id='.$this->lp_id.'" title="'.get_lang('LinkAdd').'">'.
  9883. get_lang('LinkAdd').'
  9884. </a>
  9885. </li>';
  9886. foreach ($categorizedLinks as $categoryId => $links) {
  9887. $linkNodes = null;
  9888. foreach ($links as $key => $linkInfo) {
  9889. $title = $linkInfo['link_title'];
  9890. $linkSessionId = $linkInfo['link_session_id'];
  9891. $link = Display::url(
  9892. Display::return_icon('preview_view.png', get_lang('Preview')),
  9893. api_get_path(WEB_CODE_PATH).'link/link_goto.php?'.api_get_cidreq().'&link_id='.$key,
  9894. ['target' => '_blank']
  9895. );
  9896. if (api_get_item_visibility($course, TOOL_LINK, $key, $session_id) != 2) {
  9897. $sessionStar = api_get_session_image($linkSessionId, $userInfo['status']);
  9898. $linkNodes .=
  9899. '<li class="lp_resource_element" data_id="'.$key.'" data_type="'.TOOL_LINK.'" title="'.$title.'" >
  9900. <a class="moved" href="#">'.
  9901. $moveEverywhereIcon.
  9902. '</a>
  9903. '.Display::return_icon('links.png', '', [], ICON_SIZE_TINY).'
  9904. <a class="moved" href="'.$selfUrl.'?'.$courseIdReq.'&action=add_item&type='.
  9905. TOOL_LINK.'&file='.$key.'&lp_id='.$this->lp_id.'">'.
  9906. Security::remove_XSS($title).$sessionStar.$link.
  9907. '</a>
  9908. </li>';
  9909. }
  9910. }
  9911. $linksHtmlCode .=
  9912. '<li>
  9913. <a style="cursor:hand" onclick="javascript: toggle_tool(\''.TOOL_LINK.'\','.$categoryId.')" style="vertical-align:middle">
  9914. <img src="'.Display::returnIconPath('add.gif').'" id="'.TOOL_LINK.'_'.$categoryId.'_opener"
  9915. align="absbottom" />
  9916. </a>
  9917. <span style="vertical-align:middle">'.Security::remove_XSS($categories[$categoryId]).'</span>
  9918. </li>
  9919. <div style="display:none" id="'.TOOL_LINK.'_'.$categoryId.'_content">'.$linkNodes.'</div>';
  9920. }
  9921. $linksHtmlCode .= '</ul>';
  9922. return $linksHtmlCode;
  9923. }
  9924. /**
  9925. * Creates a list with all the student publications in it.
  9926. *
  9927. * @return string
  9928. */
  9929. public function get_student_publications()
  9930. {
  9931. $return = '<ul class="lp_resource">';
  9932. $return .= '<li class="lp_resource_element">';
  9933. $return .= Display::return_icon('works_new.gif');
  9934. $return .= ' <a href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_STUDENTPUBLICATION.'&lp_id='.$this->lp_id.'">'.
  9935. get_lang('AddAssignmentPage').'</a>';
  9936. $return .= '</li>';
  9937. require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
  9938. $works = getWorkListTeacher(0, 100, null, null, null);
  9939. if (!empty($works)) {
  9940. foreach ($works as $work) {
  9941. $link = Display::url(
  9942. Display::return_icon('preview_view.png', get_lang('Preview')),
  9943. api_get_path(WEB_CODE_PATH).'work/work_list_all.php?'.api_get_cidreq().'&id='.$work['iid'],
  9944. ['target' => '_blank']
  9945. );
  9946. $return .= '<li class="lp_resource_element" data_id="'.$work['iid'].'" data_type="'.TOOL_STUDENTPUBLICATION.'" title="'.Security::remove_XSS(cut(strip_tags($work['title']), 80)).'">';
  9947. $return .= '<a class="moved" href="#">';
  9948. $return .= Display::return_icon(
  9949. 'move_everywhere.png',
  9950. get_lang('Move'),
  9951. [],
  9952. ICON_SIZE_TINY
  9953. );
  9954. $return .= '</a> ';
  9955. $return .= Display::return_icon('works.png', '', [], ICON_SIZE_TINY);
  9956. $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.'">'.
  9957. Security::remove_XSS(cut(strip_tags($work['title']), 80)).' '.$link.'
  9958. </a>';
  9959. $return .= '</li>';
  9960. }
  9961. }
  9962. $return .= '</ul>';
  9963. return $return;
  9964. }
  9965. /**
  9966. * Creates a list with all the forums in it.
  9967. *
  9968. * @return string
  9969. */
  9970. public function get_forums()
  9971. {
  9972. require_once '../forum/forumfunction.inc.php';
  9973. $forumCategories = get_forum_categories();
  9974. $forumsInNoCategory = get_forums_in_category(0);
  9975. if (!empty($forumsInNoCategory)) {
  9976. $forumCategories = array_merge(
  9977. $forumCategories,
  9978. [
  9979. [
  9980. 'cat_id' => 0,
  9981. 'session_id' => 0,
  9982. 'visibility' => 1,
  9983. 'cat_comment' => null,
  9984. ],
  9985. ]
  9986. );
  9987. }
  9988. $forumList = get_forums();
  9989. $a_forums = [];
  9990. foreach ($forumCategories as $forumCategory) {
  9991. // The forums in this category.
  9992. $forumsInCategory = get_forums_in_category($forumCategory['cat_id']);
  9993. if (!empty($forumsInCategory)) {
  9994. foreach ($forumList as $forum) {
  9995. if (isset($forum['forum_category']) &&
  9996. $forum['forum_category'] == $forumCategory['cat_id']
  9997. ) {
  9998. $a_forums[] = $forum;
  9999. }
  10000. }
  10001. }
  10002. }
  10003. $return = '<ul class="lp_resource">';
  10004. // First add link
  10005. $return .= '<li class="lp_resource_element">';
  10006. $return .= Display::return_icon('new_forum.png');
  10007. $return .= Display::url(
  10008. get_lang('CreateANewForum'),
  10009. api_get_path(WEB_CODE_PATH).'forum/index.php?'.api_get_cidreq().'&'.http_build_query([
  10010. 'action' => 'add',
  10011. 'content' => 'forum',
  10012. 'lp_id' => $this->lp_id,
  10013. ]),
  10014. ['title' => get_lang('CreateANewForum')]
  10015. );
  10016. $return .= '</li>';
  10017. $return .= '<script>
  10018. function toggle_forum(forum_id) {
  10019. if (document.getElementById("forum_"+forum_id+"_content").style.display == "none") {
  10020. document.getElementById("forum_"+forum_id+"_content").style.display = "block";
  10021. document.getElementById("forum_"+forum_id+"_opener").src = "'.Display::returnIconPath('remove.gif').'";
  10022. } else {
  10023. document.getElementById("forum_"+forum_id+"_content").style.display = "none";
  10024. document.getElementById("forum_"+forum_id+"_opener").src = "'.Display::returnIconPath('add.gif').'";
  10025. }
  10026. }
  10027. </script>';
  10028. foreach ($a_forums as $forum) {
  10029. if (!empty($forum['forum_id'])) {
  10030. $link = Display::url(
  10031. Display::return_icon('preview_view.png', get_lang('Preview')),
  10032. api_get_path(WEB_CODE_PATH).'forum/viewforum.php?'.api_get_cidreq().'&forum='.$forum['forum_id'],
  10033. ['target' => '_blank']
  10034. );
  10035. $return .= '<li class="lp_resource_element" data_id="'.$forum['forum_id'].'" data_type="'.TOOL_FORUM.'" title="'.$forum['forum_title'].'" >';
  10036. $return .= '<a class="moved" href="#">';
  10037. $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), [], ICON_SIZE_TINY);
  10038. $return .= ' </a>';
  10039. $return .= Display::return_icon('forum.png', '', [], ICON_SIZE_TINY);
  10040. $return .= '<a onclick="javascript:toggle_forum('.$forum['forum_id'].');" style="cursor:hand; vertical-align:middle">
  10041. <img src="'.Display::returnIconPath('add.gif').'" id="forum_'.$forum['forum_id'].'_opener" align="absbottom" />
  10042. </a>
  10043. <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">'.
  10044. Security::remove_XSS($forum['forum_title']).' '.$link.'</a>';
  10045. $return .= '</li>';
  10046. $return .= '<div style="display:none" id="forum_'.$forum['forum_id'].'_content">';
  10047. $a_threads = get_threads($forum['forum_id']);
  10048. if (is_array($a_threads)) {
  10049. foreach ($a_threads as $thread) {
  10050. $link = Display::url(
  10051. Display::return_icon('preview_view.png', get_lang('Preview')),
  10052. api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.api_get_cidreq().'&forum='.$forum['forum_id'].'&thread='.$thread['thread_id'],
  10053. ['target' => '_blank']
  10054. );
  10055. $return .= '<li class="lp_resource_element" data_id="'.$thread['thread_id'].'" data_type="'.TOOL_THREAD.'" title="'.$thread['thread_title'].'" >';
  10056. $return .= '&nbsp;<a class="moved" href="#">';
  10057. $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), [], ICON_SIZE_TINY);
  10058. $return .= ' </a>';
  10059. $return .= Display::return_icon('forumthread.png', get_lang('Thread'), [], ICON_SIZE_TINY);
  10060. $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.'">'.
  10061. Security::remove_XSS($thread['thread_title']).' '.$link.'</a>';
  10062. $return .= '</li>';
  10063. }
  10064. }
  10065. $return .= '</div>';
  10066. }
  10067. }
  10068. $return .= '</ul>';
  10069. return $return;
  10070. }
  10071. /**
  10072. * // TODO: The output encoding should be equal to the system encoding.
  10073. *
  10074. * Exports the learning path as a SCORM package. This is the main function that
  10075. * gathers the content, transforms it, writes the imsmanifest.xml file, zips the
  10076. * whole thing and returns the zip.
  10077. *
  10078. * This method needs to be called in PHP5, as it will fail with non-adequate
  10079. * XML package (like the ones for PHP4), and it is *not* a static method, so
  10080. * you need to call it on a learnpath object.
  10081. *
  10082. * @TODO The method might be redefined later on in the scorm class itself to avoid
  10083. * creating a SCORM structure if there is one already. However, if the initial SCORM
  10084. * path has been modified, it should use the generic method here below.
  10085. *
  10086. * @return string Returns the zip package string, or null if error
  10087. */
  10088. public function scormExport()
  10089. {
  10090. api_set_more_memory_and_time_limits();
  10091. $_course = api_get_course_info();
  10092. $course_id = $_course['real_id'];
  10093. // Create the zip handler (this will remain available throughout the method).
  10094. $archivePath = api_get_path(SYS_ARCHIVE_PATH);
  10095. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  10096. $temp_dir_short = uniqid('scorm_export', true);
  10097. $temp_zip_dir = $archivePath.'/'.$temp_dir_short;
  10098. $temp_zip_file = $temp_zip_dir.'/'.md5(time()).'.zip';
  10099. $zip_folder = new PclZip($temp_zip_file);
  10100. $current_course_path = api_get_path(SYS_COURSE_PATH).api_get_course_path();
  10101. $root_path = $main_path = api_get_path(SYS_PATH);
  10102. $files_cleanup = [];
  10103. // Place to temporarily stash the zip file.
  10104. // create the temp dir if it doesn't exist
  10105. // or do a cleanup before creating the zip file.
  10106. if (!is_dir($temp_zip_dir)) {
  10107. mkdir($temp_zip_dir, api_get_permissions_for_new_directories());
  10108. } else {
  10109. // Cleanup: Check the temp dir for old files and delete them.
  10110. $handle = opendir($temp_zip_dir);
  10111. while (false !== ($file = readdir($handle))) {
  10112. if ($file != '.' && $file != '..') {
  10113. unlink("$temp_zip_dir/$file");
  10114. }
  10115. }
  10116. closedir($handle);
  10117. }
  10118. $zip_files = $zip_files_abs = $zip_files_dist = [];
  10119. if (is_dir($current_course_path.'/scorm/'.$this->path) &&
  10120. is_file($current_course_path.'/scorm/'.$this->path.'/imsmanifest.xml')
  10121. ) {
  10122. // Remove the possible . at the end of the path.
  10123. $dest_path_to_lp = substr($this->path, -1) == '.' ? substr($this->path, 0, -1) : $this->path;
  10124. $dest_path_to_scorm_folder = str_replace('//', '/', $temp_zip_dir.'/scorm/'.$dest_path_to_lp);
  10125. mkdir(
  10126. $dest_path_to_scorm_folder,
  10127. api_get_permissions_for_new_directories(),
  10128. true
  10129. );
  10130. copyr(
  10131. $current_course_path.'/scorm/'.$this->path,
  10132. $dest_path_to_scorm_folder,
  10133. ['imsmanifest'],
  10134. $zip_files
  10135. );
  10136. }
  10137. // Build a dummy imsmanifest structure.
  10138. // Do not add to the zip yet (we still need it).
  10139. // This structure is developed following regulations for SCORM 1.2 packaging in the SCORM 1.2 Content
  10140. // Aggregation Model official document, section "2.3 Content Packaging".
  10141. // We are going to build a UTF-8 encoded manifest.
  10142. // Later we will recode it to the desired (and supported) encoding.
  10143. $xmldoc = new DOMDocument('1.0');
  10144. $root = $xmldoc->createElement('manifest');
  10145. $root->setAttribute('identifier', 'SingleCourseManifest');
  10146. $root->setAttribute('version', '1.1');
  10147. $root->setAttribute('xmlns', 'http://www.imsproject.org/xsd/imscp_rootv1p1p2');
  10148. $root->setAttribute('xmlns:adlcp', 'http://www.adlnet.org/xsd/adlcp_rootv1p2');
  10149. $root->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
  10150. $root->setAttribute(
  10151. 'xsi:schemaLocation',
  10152. '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'
  10153. );
  10154. // Build mandatory sub-root container elements.
  10155. $metadata = $xmldoc->createElement('metadata');
  10156. $md_schema = $xmldoc->createElement('schema', 'ADL SCORM');
  10157. $metadata->appendChild($md_schema);
  10158. $md_schemaversion = $xmldoc->createElement('schemaversion', '1.2');
  10159. $metadata->appendChild($md_schemaversion);
  10160. $root->appendChild($metadata);
  10161. $organizations = $xmldoc->createElement('organizations');
  10162. $resources = $xmldoc->createElement('resources');
  10163. // Build the only organization we will use in building our learnpaths.
  10164. $organizations->setAttribute('default', 'chamilo_scorm_export');
  10165. $organization = $xmldoc->createElement('organization');
  10166. $organization->setAttribute('identifier', 'chamilo_scorm_export');
  10167. // To set the title of the SCORM entity (=organization), we take the name given
  10168. // in Chamilo and convert it to HTML entities using the Chamilo charset (not the
  10169. // learning path charset) as it is the encoding that defines how it is stored
  10170. // in the database. Then we convert it to HTML entities again as the "&" character
  10171. // alone is not authorized in XML (must be &amp;).
  10172. // The title is then decoded twice when extracting (see scorm::parse_manifest).
  10173. $org_title = $xmldoc->createElement('title', api_utf8_encode($this->get_name()));
  10174. $organization->appendChild($org_title);
  10175. $folder_name = 'document';
  10176. // Removes the learning_path/scorm_folder path when exporting see #4841
  10177. $path_to_remove = '';
  10178. $path_to_replace = '';
  10179. $result = $this->generate_lp_folder($_course);
  10180. if (isset($result['dir']) && strpos($result['dir'], 'learning_path')) {
  10181. $path_to_remove = 'document'.$result['dir'];
  10182. $path_to_replace = $folder_name.'/';
  10183. }
  10184. // Fixes chamilo scorm exports
  10185. if ($this->ref === 'chamilo_scorm_export') {
  10186. $path_to_remove = 'scorm/'.$this->path.'/document/';
  10187. }
  10188. // For each element, add it to the imsmanifest structure, then add it to the zip.
  10189. $link_updates = [];
  10190. $links_to_create = [];
  10191. foreach ($this->ordered_items as $index => $itemId) {
  10192. /** @var learnpathItem $item */
  10193. $item = $this->items[$itemId];
  10194. if (!in_array($item->type, [TOOL_QUIZ, TOOL_FORUM, TOOL_THREAD, TOOL_LINK, TOOL_STUDENTPUBLICATION])) {
  10195. // Get included documents from this item.
  10196. if ($item->type === 'sco') {
  10197. $inc_docs = $item->get_resources_from_source(
  10198. null,
  10199. $current_course_path.'/scorm/'.$this->path.'/'.$item->get_path()
  10200. );
  10201. } else {
  10202. $inc_docs = $item->get_resources_from_source();
  10203. }
  10204. // Give a child element <item> to the <organization> element.
  10205. $my_item_id = $item->get_id();
  10206. $my_item = $xmldoc->createElement('item');
  10207. $my_item->setAttribute('identifier', 'ITEM_'.$my_item_id);
  10208. $my_item->setAttribute('identifierref', 'RESOURCE_'.$my_item_id);
  10209. $my_item->setAttribute('isvisible', 'true');
  10210. // Give a child element <title> to the <item> element.
  10211. $my_title = $xmldoc->createElement(
  10212. 'title',
  10213. htmlspecialchars(
  10214. api_utf8_encode($item->get_title()),
  10215. ENT_QUOTES,
  10216. 'UTF-8'
  10217. )
  10218. );
  10219. $my_item->appendChild($my_title);
  10220. // Give a child element <adlcp:prerequisites> to the <item> element.
  10221. $my_prereqs = $xmldoc->createElement(
  10222. 'adlcp:prerequisites',
  10223. $this->get_scorm_prereq_string($my_item_id)
  10224. );
  10225. $my_prereqs->setAttribute('type', 'aicc_script');
  10226. $my_item->appendChild($my_prereqs);
  10227. // Give a child element <adlcp:maxtimeallowed> to the <item> element - not yet supported.
  10228. //$xmldoc->createElement('adlcp:maxtimeallowed','');
  10229. // Give a child element <adlcp:timelimitaction> to the <item> element - not yet supported.
  10230. //$xmldoc->createElement('adlcp:timelimitaction','');
  10231. // Give a child element <adlcp:datafromlms> to the <item> element - not yet supported.
  10232. //$xmldoc->createElement('adlcp:datafromlms','');
  10233. // Give a child element <adlcp:masteryscore> to the <item> element.
  10234. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  10235. $my_item->appendChild($my_masteryscore);
  10236. // Attach this item to the organization element or hits parent if there is one.
  10237. if (!empty($item->parent) && $item->parent != 0) {
  10238. $children = $organization->childNodes;
  10239. $possible_parent = $this->get_scorm_xml_node($children, 'ITEM_'.$item->parent);
  10240. if (is_object($possible_parent)) {
  10241. $possible_parent->appendChild($my_item);
  10242. } else {
  10243. if ($this->debug > 0) {
  10244. error_log('Parent ITEM_'.$item->parent.' of item ITEM_'.$my_item_id.' not found');
  10245. }
  10246. }
  10247. } else {
  10248. if ($this->debug > 0) {
  10249. error_log('No parent');
  10250. }
  10251. $organization->appendChild($my_item);
  10252. }
  10253. // Get the path of the file(s) from the course directory root.
  10254. $my_file_path = $item->get_file_path('scorm/'.$this->path.'/');
  10255. $my_xml_file_path = $my_file_path;
  10256. if (!empty($path_to_remove)) {
  10257. // From docs
  10258. $my_xml_file_path = str_replace($path_to_remove, $path_to_replace, $my_file_path);
  10259. // From quiz
  10260. if ($this->ref === 'chamilo_scorm_export') {
  10261. $path_to_remove = 'scorm/'.$this->path.'/';
  10262. $my_xml_file_path = str_replace($path_to_remove, '', $my_file_path);
  10263. }
  10264. }
  10265. $my_sub_dir = dirname($my_file_path);
  10266. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  10267. $my_xml_sub_dir = $my_sub_dir;
  10268. // Give a <resource> child to the <resources> element
  10269. $my_resource = $xmldoc->createElement('resource');
  10270. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  10271. $my_resource->setAttribute('type', 'webcontent');
  10272. $my_resource->setAttribute('href', $my_xml_file_path);
  10273. // adlcp:scormtype can be either 'sco' or 'asset'.
  10274. if ($item->type === 'sco') {
  10275. $my_resource->setAttribute('adlcp:scormtype', 'sco');
  10276. } else {
  10277. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  10278. }
  10279. // xml:base is the base directory to find the files declared in this resource.
  10280. $my_resource->setAttribute('xml:base', '');
  10281. // Give a <file> child to the <resource> element.
  10282. $my_file = $xmldoc->createElement('file');
  10283. $my_file->setAttribute('href', $my_xml_file_path);
  10284. $my_resource->appendChild($my_file);
  10285. // Dependency to other files - not yet supported.
  10286. $i = 1;
  10287. if ($inc_docs) {
  10288. foreach ($inc_docs as $doc_info) {
  10289. if (count($doc_info) < 1 || empty($doc_info[0])) {
  10290. continue;
  10291. }
  10292. $my_dep = $xmldoc->createElement('resource');
  10293. $res_id = 'RESOURCE_'.$item->get_id().'_'.$i;
  10294. $my_dep->setAttribute('identifier', $res_id);
  10295. $my_dep->setAttribute('type', 'webcontent');
  10296. $my_dep->setAttribute('adlcp:scormtype', 'asset');
  10297. $my_dep_file = $xmldoc->createElement('file');
  10298. // Check type of URL.
  10299. if ($doc_info[1] == 'remote') {
  10300. // Remote file. Save url as is.
  10301. $my_dep_file->setAttribute('href', $doc_info[0]);
  10302. $my_dep->setAttribute('xml:base', '');
  10303. } elseif ($doc_info[1] === 'local') {
  10304. switch ($doc_info[2]) {
  10305. case 'url':
  10306. // Local URL - save path as url for now, don't zip file.
  10307. $abs_path = api_get_path(SYS_PATH).
  10308. str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  10309. $current_dir = dirname($abs_path);
  10310. $current_dir = str_replace('\\', '/', $current_dir);
  10311. $file_path = realpath($abs_path);
  10312. $file_path = str_replace('\\', '/', $file_path);
  10313. $my_dep_file->setAttribute('href', $file_path);
  10314. $my_dep->setAttribute('xml:base', '');
  10315. if (strstr($file_path, $main_path) !== false) {
  10316. // The calculated real path is really inside Chamilo's root path.
  10317. // Reduce file path to what's under the DocumentRoot.
  10318. $replace = $file_path;
  10319. $file_path = substr($file_path, strlen($root_path) - 1);
  10320. $destinationFile = $file_path;
  10321. if (strstr($file_path, 'upload/users') !== false) {
  10322. $pos = strpos($file_path, 'my_files/');
  10323. if ($pos !== false) {
  10324. $onlyDirectory = str_replace(
  10325. 'upload/users/',
  10326. '',
  10327. substr($file_path, $pos, strlen($file_path))
  10328. );
  10329. }
  10330. $replace = $onlyDirectory;
  10331. $destinationFile = $replace;
  10332. }
  10333. $zip_files_abs[] = $file_path;
  10334. $link_updates[$my_file_path][] = [
  10335. 'orig' => $doc_info[0],
  10336. 'dest' => $destinationFile,
  10337. 'replace' => $replace,
  10338. ];
  10339. $my_dep_file->setAttribute('href', $file_path);
  10340. $my_dep->setAttribute('xml:base', '');
  10341. } elseif (empty($file_path)) {
  10342. $file_path = $_SERVER['DOCUMENT_ROOT'].$abs_path;
  10343. $file_path = str_replace('//', '/', $file_path);
  10344. if (file_exists($file_path)) {
  10345. // We get the relative path.
  10346. $file_path = substr($file_path, strlen($current_dir));
  10347. $zip_files[] = $my_sub_dir.'/'.$file_path;
  10348. $link_updates[$my_file_path][] = [
  10349. 'orig' => $doc_info[0],
  10350. 'dest' => $file_path,
  10351. ];
  10352. $my_dep_file->setAttribute('href', $file_path);
  10353. $my_dep->setAttribute('xml:base', '');
  10354. }
  10355. }
  10356. break;
  10357. case 'abs':
  10358. // Absolute path from DocumentRoot. Save file and leave path as is in the zip.
  10359. $my_dep_file->setAttribute('href', $doc_info[0]);
  10360. $my_dep->setAttribute('xml:base', '');
  10361. // The next lines fix a bug when using the "subdir" mode of Chamilo, whereas
  10362. // an image path would be constructed as /var/www/subdir/subdir/img/foo.bar
  10363. $abs_img_path_without_subdir = $doc_info[0];
  10364. $relp = api_get_path(REL_PATH); // The url-append config param.
  10365. $pos = strpos($abs_img_path_without_subdir, $relp);
  10366. if ($pos === 0) {
  10367. $abs_img_path_without_subdir = trim('/'.substr($abs_img_path_without_subdir, strlen($relp)));
  10368. }
  10369. $file_path = realpath(api_get_path(SYS_APP_PATH).$abs_img_path_without_subdir);
  10370. $file_path = str_replace(['\\', '//'], '/', $file_path);
  10371. // Prepare the current directory path (until just under 'document') with a trailing slash.
  10372. $cur_path = substr($current_course_path, -1) == '/' ? $current_course_path : $current_course_path.'/';
  10373. // Check if the current document is in that path.
  10374. if (strstr($file_path, $cur_path) !== false) {
  10375. $destinationFile = substr($file_path, strlen($cur_path));
  10376. $filePathNoCoursePart = substr($file_path, strlen($cur_path));
  10377. $fileToTest = $cur_path.$my_file_path;
  10378. if (!empty($path_to_remove)) {
  10379. $fileToTest = str_replace(
  10380. $path_to_remove.'/',
  10381. $path_to_replace,
  10382. $cur_path.$my_file_path
  10383. );
  10384. }
  10385. $relative_path = api_get_relative_path($fileToTest, $file_path);
  10386. // Put the current document in the zip (this array is the array
  10387. // that will manage documents already in the course folder - relative).
  10388. $zip_files[] = $filePathNoCoursePart;
  10389. // Update the links to the current document in the
  10390. // containing document (make them relative).
  10391. $link_updates[$my_file_path][] = [
  10392. 'orig' => $doc_info[0],
  10393. 'dest' => $destinationFile,
  10394. 'replace' => $relative_path,
  10395. ];
  10396. $my_dep_file->setAttribute('href', $file_path);
  10397. $my_dep->setAttribute('xml:base', '');
  10398. } elseif (strstr($file_path, $main_path) !== false) {
  10399. // The calculated real path is really inside Chamilo's root path.
  10400. // Reduce file path to what's under the DocumentRoot.
  10401. $file_path = substr($file_path, strlen($root_path));
  10402. $zip_files_abs[] = $file_path;
  10403. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => $file_path];
  10404. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10405. $my_dep->setAttribute('xml:base', '');
  10406. } elseif (empty($file_path)) {
  10407. // Probably this is an image inside "/main" directory
  10408. $file_path = api_get_path(SYS_PATH).$abs_img_path_without_subdir;
  10409. $abs_path = api_get_path(SYS_PATH).str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  10410. if (file_exists($file_path)) {
  10411. if (strstr($file_path, 'main/default_course_document') !== false) {
  10412. // We get the relative path.
  10413. $pos = strpos($file_path, 'main/default_course_document/');
  10414. if ($pos !== false) {
  10415. $onlyDirectory = str_replace(
  10416. 'main/default_course_document/',
  10417. '',
  10418. substr($file_path, $pos, strlen($file_path))
  10419. );
  10420. }
  10421. $destinationFile = 'default_course_document/'.$onlyDirectory;
  10422. $fileAbs = substr($file_path, strlen(api_get_path(SYS_PATH)));
  10423. $zip_files_abs[] = $fileAbs;
  10424. $link_updates[$my_file_path][] = [
  10425. 'orig' => $doc_info[0],
  10426. 'dest' => $destinationFile,
  10427. ];
  10428. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10429. $my_dep->setAttribute('xml:base', '');
  10430. }
  10431. }
  10432. }
  10433. break;
  10434. case 'rel':
  10435. // Path relative to the current document.
  10436. // Save xml:base as current document's directory and save file in zip as subdir.file_path
  10437. if (substr($doc_info[0], 0, 2) === '..') {
  10438. // Relative path going up.
  10439. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  10440. $current_dir = str_replace('\\', '/', $current_dir);
  10441. $file_path = realpath($current_dir.$doc_info[0]);
  10442. $file_path = str_replace('\\', '/', $file_path);
  10443. if (strstr($file_path, $main_path) !== false) {
  10444. // The calculated real path is really inside Chamilo's root path.
  10445. // Reduce file path to what's under the DocumentRoot.
  10446. $file_path = substr($file_path, strlen($root_path));
  10447. $zip_files_abs[] = $file_path;
  10448. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => $file_path];
  10449. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10450. $my_dep->setAttribute('xml:base', '');
  10451. }
  10452. } else {
  10453. $zip_files[] = $my_sub_dir.'/'.$doc_info[0];
  10454. $my_dep_file->setAttribute('href', $doc_info[0]);
  10455. $my_dep->setAttribute('xml:base', $my_xml_sub_dir);
  10456. }
  10457. break;
  10458. default:
  10459. $my_dep_file->setAttribute('href', $doc_info[0]);
  10460. $my_dep->setAttribute('xml:base', '');
  10461. break;
  10462. }
  10463. }
  10464. $my_dep->appendChild($my_dep_file);
  10465. $resources->appendChild($my_dep);
  10466. $dependency = $xmldoc->createElement('dependency');
  10467. $dependency->setAttribute('identifierref', $res_id);
  10468. $my_resource->appendChild($dependency);
  10469. $i++;
  10470. }
  10471. }
  10472. $resources->appendChild($my_resource);
  10473. $zip_files[] = $my_file_path;
  10474. } else {
  10475. // If the item is a quiz or a link or whatever non-exportable, we include a step indicating it.
  10476. switch ($item->type) {
  10477. case TOOL_LINK:
  10478. $my_item = $xmldoc->createElement('item');
  10479. $my_item->setAttribute('identifier', 'ITEM_'.$item->get_id());
  10480. $my_item->setAttribute('identifierref', 'RESOURCE_'.$item->get_id());
  10481. $my_item->setAttribute('isvisible', 'true');
  10482. // Give a child element <title> to the <item> element.
  10483. $my_title = $xmldoc->createElement(
  10484. 'title',
  10485. htmlspecialchars(
  10486. api_utf8_encode($item->get_title()),
  10487. ENT_QUOTES,
  10488. 'UTF-8'
  10489. )
  10490. );
  10491. $my_item->appendChild($my_title);
  10492. // Give a child element <adlcp:prerequisites> to the <item> element.
  10493. $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $item->get_prereq_string());
  10494. $my_prereqs->setAttribute('type', 'aicc_script');
  10495. $my_item->appendChild($my_prereqs);
  10496. // Give a child element <adlcp:maxtimeallowed> to the <item> element - not yet supported.
  10497. //$xmldoc->createElement('adlcp:maxtimeallowed', '');
  10498. // Give a child element <adlcp:timelimitaction> to the <item> element - not yet supported.
  10499. //$xmldoc->createElement('adlcp:timelimitaction', '');
  10500. // Give a child element <adlcp:datafromlms> to the <item> element - not yet supported.
  10501. //$xmldoc->createElement('adlcp:datafromlms', '');
  10502. // Give a child element <adlcp:masteryscore> to the <item> element.
  10503. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  10504. $my_item->appendChild($my_masteryscore);
  10505. // Attach this item to the organization element or its parent if there is one.
  10506. if (!empty($item->parent) && $item->parent != 0) {
  10507. $children = $organization->childNodes;
  10508. for ($i = 0; $i < $children->length; $i++) {
  10509. $item_temp = $children->item($i);
  10510. if ($item_temp->nodeName == 'item') {
  10511. if ($item_temp->getAttribute('identifier') == 'ITEM_'.$item->parent) {
  10512. $item_temp->appendChild($my_item);
  10513. }
  10514. }
  10515. }
  10516. } else {
  10517. $organization->appendChild($my_item);
  10518. }
  10519. $my_file_path = 'link_'.$item->get_id().'.html';
  10520. $sql = 'SELECT url, title FROM '.Database::get_course_table(TABLE_LINK).'
  10521. WHERE c_id = '.$course_id.' AND id = '.$item->path;
  10522. $rs = Database::query($sql);
  10523. if ($link = Database::fetch_array($rs)) {
  10524. $url = $link['url'];
  10525. $title = stripslashes($link['title']);
  10526. $links_to_create[$my_file_path] = ['title' => $title, 'url' => $url];
  10527. $my_xml_file_path = $my_file_path;
  10528. $my_sub_dir = dirname($my_file_path);
  10529. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  10530. $my_xml_sub_dir = $my_sub_dir;
  10531. // Give a <resource> child to the <resources> element.
  10532. $my_resource = $xmldoc->createElement('resource');
  10533. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  10534. $my_resource->setAttribute('type', 'webcontent');
  10535. $my_resource->setAttribute('href', $my_xml_file_path);
  10536. // adlcp:scormtype can be either 'sco' or 'asset'.
  10537. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  10538. // xml:base is the base directory to find the files declared in this resource.
  10539. $my_resource->setAttribute('xml:base', '');
  10540. // give a <file> child to the <resource> element.
  10541. $my_file = $xmldoc->createElement('file');
  10542. $my_file->setAttribute('href', $my_xml_file_path);
  10543. $my_resource->appendChild($my_file);
  10544. $resources->appendChild($my_resource);
  10545. }
  10546. break;
  10547. case TOOL_QUIZ:
  10548. $exe_id = $item->path;
  10549. // Should be using ref when everything will be cleaned up in this regard.
  10550. $exe = new Exercise();
  10551. $exe->read($exe_id);
  10552. $my_item = $xmldoc->createElement('item');
  10553. $my_item->setAttribute('identifier', 'ITEM_'.$item->get_id());
  10554. $my_item->setAttribute('identifierref', 'RESOURCE_'.$item->get_id());
  10555. $my_item->setAttribute('isvisible', 'true');
  10556. // Give a child element <title> to the <item> element.
  10557. $my_title = $xmldoc->createElement(
  10558. 'title',
  10559. htmlspecialchars(
  10560. api_utf8_encode($item->get_title()),
  10561. ENT_QUOTES,
  10562. 'UTF-8'
  10563. )
  10564. );
  10565. $my_item->appendChild($my_title);
  10566. $my_max_score = $xmldoc->createElement('max_score', $item->get_max());
  10567. $my_item->appendChild($my_max_score);
  10568. // Give a child element <adlcp:prerequisites> to the <item> element.
  10569. $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $item->get_prereq_string());
  10570. $my_prereqs->setAttribute('type', 'aicc_script');
  10571. $my_item->appendChild($my_prereqs);
  10572. // Give a child element <adlcp:masteryscore> to the <item> element.
  10573. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  10574. $my_item->appendChild($my_masteryscore);
  10575. // Attach this item to the organization element or hits parent if there is one.
  10576. if (!empty($item->parent) && $item->parent != 0) {
  10577. $children = $organization->childNodes;
  10578. $possible_parent = $this->get_scorm_xml_node($children, 'ITEM_'.$item->parent);
  10579. if ($possible_parent) {
  10580. if ($possible_parent->getAttribute('identifier') === 'ITEM_'.$item->parent) {
  10581. $possible_parent->appendChild($my_item);
  10582. }
  10583. }
  10584. } else {
  10585. $organization->appendChild($my_item);
  10586. }
  10587. // Get the path of the file(s) from the course directory root
  10588. //$my_file_path = $item->get_file_path('scorm/'.$this->path.'/');
  10589. $my_file_path = 'quiz_'.$item->get_id().'.html';
  10590. // Write the contents of the exported exercise into a (big) html file
  10591. // to later pack it into the exported SCORM. The file will be removed afterwards.
  10592. $scormExercise = new ScormExercise($exe, true);
  10593. $contents = $scormExercise->export();
  10594. $tmp_file_path = $archivePath.$temp_dir_short.'/'.$my_file_path;
  10595. $res = file_put_contents($tmp_file_path, $contents);
  10596. if ($res === false) {
  10597. error_log('Could not write into file '.$tmp_file_path.' '.__FILE__.' '.__LINE__, 0);
  10598. }
  10599. $files_cleanup[] = $tmp_file_path;
  10600. $my_xml_file_path = $my_file_path;
  10601. $my_sub_dir = dirname($my_file_path);
  10602. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  10603. $my_xml_sub_dir = $my_sub_dir;
  10604. // Give a <resource> child to the <resources> element.
  10605. $my_resource = $xmldoc->createElement('resource');
  10606. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  10607. $my_resource->setAttribute('type', 'webcontent');
  10608. $my_resource->setAttribute('href', $my_xml_file_path);
  10609. // adlcp:scormtype can be either 'sco' or 'asset'.
  10610. $my_resource->setAttribute('adlcp:scormtype', 'sco');
  10611. // xml:base is the base directory to find the files declared in this resource.
  10612. $my_resource->setAttribute('xml:base', '');
  10613. // Give a <file> child to the <resource> element.
  10614. $my_file = $xmldoc->createElement('file');
  10615. $my_file->setAttribute('href', $my_xml_file_path);
  10616. $my_resource->appendChild($my_file);
  10617. // Get included docs.
  10618. $inc_docs = $item->get_resources_from_source(null, $tmp_file_path);
  10619. // Dependency to other files - not yet supported.
  10620. $i = 1;
  10621. foreach ($inc_docs as $doc_info) {
  10622. if (count($doc_info) < 1 || empty($doc_info[0])) {
  10623. continue;
  10624. }
  10625. $my_dep = $xmldoc->createElement('resource');
  10626. $res_id = 'RESOURCE_'.$item->get_id().'_'.$i;
  10627. $my_dep->setAttribute('identifier', $res_id);
  10628. $my_dep->setAttribute('type', 'webcontent');
  10629. $my_dep->setAttribute('adlcp:scormtype', 'asset');
  10630. $my_dep_file = $xmldoc->createElement('file');
  10631. // Check type of URL.
  10632. if ($doc_info[1] == 'remote') {
  10633. // Remote file. Save url as is.
  10634. $my_dep_file->setAttribute('href', $doc_info[0]);
  10635. $my_dep->setAttribute('xml:base', '');
  10636. } elseif ($doc_info[1] == 'local') {
  10637. switch ($doc_info[2]) {
  10638. case 'url': // Local URL - save path as url for now, don't zip file.
  10639. // Save file but as local file (retrieve from URL).
  10640. $abs_path = api_get_path(SYS_PATH).
  10641. str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  10642. $current_dir = dirname($abs_path);
  10643. $current_dir = str_replace('\\', '/', $current_dir);
  10644. $file_path = realpath($abs_path);
  10645. $file_path = str_replace('\\', '/', $file_path);
  10646. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10647. $my_dep->setAttribute('xml:base', '');
  10648. if (strstr($file_path, $main_path) !== false) {
  10649. // The calculated real path is really inside the chamilo root path.
  10650. // Reduce file path to what's under the DocumentRoot.
  10651. $file_path = substr($file_path, strlen($root_path));
  10652. $zip_files_abs[] = $file_path;
  10653. $link_updates[$my_file_path][] = [
  10654. 'orig' => $doc_info[0],
  10655. 'dest' => 'document/'.$file_path,
  10656. ];
  10657. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10658. $my_dep->setAttribute('xml:base', '');
  10659. } elseif (empty($file_path)) {
  10660. $file_path = $_SERVER['DOCUMENT_ROOT'].$abs_path;
  10661. $file_path = str_replace('//', '/', $file_path);
  10662. if (file_exists($file_path)) {
  10663. $file_path = substr($file_path, strlen($current_dir));
  10664. // We get the relative path.
  10665. $zip_files[] = $my_sub_dir.'/'.$file_path;
  10666. $link_updates[$my_file_path][] = [
  10667. 'orig' => $doc_info[0],
  10668. 'dest' => 'document/'.$file_path,
  10669. ];
  10670. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10671. $my_dep->setAttribute('xml:base', '');
  10672. }
  10673. }
  10674. break;
  10675. case 'abs':
  10676. // Absolute path from DocumentRoot. Save file and leave path as is in the zip.
  10677. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  10678. $current_dir = str_replace('\\', '/', $current_dir);
  10679. $file_path = realpath($doc_info[0]);
  10680. $file_path = str_replace('\\', '/', $file_path);
  10681. $my_dep_file->setAttribute('href', $file_path);
  10682. $my_dep->setAttribute('xml:base', '');
  10683. if (strstr($file_path, $main_path) !== false) {
  10684. // The calculated real path is really inside the chamilo root path.
  10685. // Reduce file path to what's under the DocumentRoot.
  10686. $file_path = substr($file_path, strlen($root_path));
  10687. $zip_files_abs[] = $file_path;
  10688. $link_updates[$my_file_path][] = [
  10689. 'orig' => $doc_info[0],
  10690. 'dest' => $file_path,
  10691. ];
  10692. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10693. $my_dep->setAttribute('xml:base', '');
  10694. } elseif (empty($file_path)) {
  10695. $docSysPartPath = str_replace(
  10696. api_get_path(REL_COURSE_PATH),
  10697. '',
  10698. $doc_info[0]
  10699. );
  10700. $docSysPartPathNoCourseCode = str_replace(
  10701. $_course['directory'].'/',
  10702. '',
  10703. $docSysPartPath
  10704. );
  10705. $docSysPath = api_get_path(SYS_COURSE_PATH).$docSysPartPath;
  10706. if (file_exists($docSysPath)) {
  10707. $file_path = $docSysPartPathNoCourseCode;
  10708. $zip_files[] = $my_sub_dir.'/'.$file_path;
  10709. $link_updates[$my_file_path][] = [
  10710. 'orig' => $doc_info[0],
  10711. 'dest' => $file_path,
  10712. ];
  10713. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10714. $my_dep->setAttribute('xml:base', '');
  10715. }
  10716. }
  10717. break;
  10718. case 'rel':
  10719. // Path relative to the current document. Save xml:base as current document's
  10720. // directory and save file in zip as subdir.file_path
  10721. if (substr($doc_info[0], 0, 2) === '..') {
  10722. // Relative path going up.
  10723. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  10724. $current_dir = str_replace('\\', '/', $current_dir);
  10725. $file_path = realpath($current_dir.$doc_info[0]);
  10726. $file_path = str_replace('\\', '/', $file_path);
  10727. //error_log($file_path.' <-> '.$main_path, 0);
  10728. if (strstr($file_path, $main_path) !== false) {
  10729. // The calculated real path is really inside Chamilo's root path.
  10730. // Reduce file path to what's under the DocumentRoot.
  10731. $file_path = substr($file_path, strlen($root_path));
  10732. $file_path_dest = $file_path;
  10733. // File path is courses/CHAMILO/document/....
  10734. $info_file_path = explode('/', $file_path);
  10735. if ($info_file_path[0] == 'courses') {
  10736. // Add character "/" in file path.
  10737. $file_path_dest = 'document/'.$file_path;
  10738. }
  10739. $zip_files_abs[] = $file_path;
  10740. $link_updates[$my_file_path][] = [
  10741. 'orig' => $doc_info[0],
  10742. 'dest' => $file_path_dest,
  10743. ];
  10744. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10745. $my_dep->setAttribute('xml:base', '');
  10746. }
  10747. } else {
  10748. $zip_files[] = $my_sub_dir.'/'.$doc_info[0];
  10749. $my_dep_file->setAttribute('href', $doc_info[0]);
  10750. $my_dep->setAttribute('xml:base', $my_xml_sub_dir);
  10751. }
  10752. break;
  10753. default:
  10754. $my_dep_file->setAttribute('href', $doc_info[0]); // ../../courses/
  10755. $my_dep->setAttribute('xml:base', '');
  10756. break;
  10757. }
  10758. }
  10759. $my_dep->appendChild($my_dep_file);
  10760. $resources->appendChild($my_dep);
  10761. $dependency = $xmldoc->createElement('dependency');
  10762. $dependency->setAttribute('identifierref', $res_id);
  10763. $my_resource->appendChild($dependency);
  10764. $i++;
  10765. }
  10766. $resources->appendChild($my_resource);
  10767. $zip_files[] = $my_file_path;
  10768. break;
  10769. default:
  10770. // Get the path of the file(s) from the course directory root
  10771. $my_file_path = 'non_exportable.html';
  10772. //$my_xml_file_path = api_htmlentities(api_utf8_encode($my_file_path), ENT_COMPAT, 'UTF-8');
  10773. $my_xml_file_path = $my_file_path;
  10774. $my_sub_dir = dirname($my_file_path);
  10775. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  10776. //$my_xml_sub_dir = api_htmlentities(api_utf8_encode($my_sub_dir), ENT_COMPAT, 'UTF-8');
  10777. $my_xml_sub_dir = $my_sub_dir;
  10778. // Give a <resource> child to the <resources> element.
  10779. $my_resource = $xmldoc->createElement('resource');
  10780. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  10781. $my_resource->setAttribute('type', 'webcontent');
  10782. $my_resource->setAttribute('href', $folder_name.'/'.$my_xml_file_path);
  10783. // adlcp:scormtype can be either 'sco' or 'asset'.
  10784. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  10785. // xml:base is the base directory to find the files declared in this resource.
  10786. $my_resource->setAttribute('xml:base', '');
  10787. // Give a <file> child to the <resource> element.
  10788. $my_file = $xmldoc->createElement('file');
  10789. $my_file->setAttribute('href', 'document/'.$my_xml_file_path);
  10790. $my_resource->appendChild($my_file);
  10791. $resources->appendChild($my_resource);
  10792. break;
  10793. }
  10794. }
  10795. }
  10796. $organizations->appendChild($organization);
  10797. $root->appendChild($organizations);
  10798. $root->appendChild($resources);
  10799. $xmldoc->appendChild($root);
  10800. $copyAll = api_get_configuration_value('add_all_files_in_lp_export');
  10801. // then add the file to the zip, then destroy the file (this is done automatically).
  10802. // http://www.reload.ac.uk/scormplayer.html - once done, don't forget to close FS#138
  10803. foreach ($zip_files as $file_path) {
  10804. if (empty($file_path)) {
  10805. continue;
  10806. }
  10807. $filePath = $sys_course_path.$_course['path'].'/'.$file_path;
  10808. $dest_file = $archivePath.$temp_dir_short.'/'.$file_path;
  10809. if (!empty($path_to_remove) && !empty($path_to_replace)) {
  10810. $dest_file = str_replace($path_to_remove, $path_to_replace, $dest_file);
  10811. }
  10812. $this->create_path($dest_file);
  10813. @copy($filePath, $dest_file);
  10814. // Check if the file needs a link update.
  10815. if (in_array($file_path, array_keys($link_updates))) {
  10816. $string = file_get_contents($dest_file);
  10817. unlink($dest_file);
  10818. foreach ($link_updates[$file_path] as $old_new) {
  10819. // This is an ugly hack that allows .flv files to be found by the flv player that
  10820. // will be added in document/main/inc/lib/flv_player/flv_player.swf and that needs
  10821. // to find the flv to play in document/main/, so we replace main/ in the flv path by
  10822. // ../../.. to return from inc/lib/flv_player to the document/main path.
  10823. if (substr($old_new['dest'], -3) === 'flv' &&
  10824. substr($old_new['dest'], 0, 5) === 'main/'
  10825. ) {
  10826. $old_new['dest'] = str_replace('main/', '../../../', $old_new['dest']);
  10827. } elseif (substr($old_new['dest'], -3) === 'flv' &&
  10828. substr($old_new['dest'], 0, 6) === 'video/'
  10829. ) {
  10830. $old_new['dest'] = str_replace('video/', '../../../../video/', $old_new['dest']);
  10831. }
  10832. // Fix to avoid problems with default_course_document
  10833. if (strpos('main/default_course_document', $old_new['dest']) === false) {
  10834. $newDestination = $old_new['dest'];
  10835. if (isset($old_new['replace']) && !empty($old_new['replace'])) {
  10836. $newDestination = $old_new['replace'];
  10837. }
  10838. } else {
  10839. $newDestination = str_replace('document/', '', $old_new['dest']);
  10840. }
  10841. $string = str_replace($old_new['orig'], $newDestination, $string);
  10842. // Add files inside the HTMLs
  10843. $new_path = str_replace(api_get_path(REL_COURSE_PATH), '', $old_new['orig']);
  10844. $destinationFile = $archivePath.$temp_dir_short.'/'.$old_new['dest'];
  10845. if (file_exists($sys_course_path.$new_path) && is_file($sys_course_path.$new_path)) {
  10846. copy(
  10847. $sys_course_path.$new_path,
  10848. $destinationFile
  10849. );
  10850. }
  10851. }
  10852. file_put_contents($dest_file, $string);
  10853. }
  10854. if (file_exists($filePath) && $copyAll) {
  10855. $extension = $this->get_extension($filePath);
  10856. if (in_array($extension, ['html', 'html'])) {
  10857. $containerOrigin = dirname($filePath);
  10858. $containerDestination = dirname($dest_file);
  10859. $finder = new Finder();
  10860. $finder->files()->in($containerOrigin)
  10861. ->notName('*_DELETED_*')
  10862. ->exclude('share_folder')
  10863. ->exclude('chat_files')
  10864. ->exclude('certificates')
  10865. ;
  10866. if (is_dir($containerOrigin) &&
  10867. is_dir($containerDestination)
  10868. ) {
  10869. $fs = new Filesystem();
  10870. $fs->mirror(
  10871. $containerOrigin,
  10872. $containerDestination,
  10873. $finder
  10874. );
  10875. }
  10876. }
  10877. }
  10878. }
  10879. foreach ($zip_files_abs as $file_path) {
  10880. if (empty($file_path)) {
  10881. continue;
  10882. }
  10883. if (!is_file($main_path.$file_path) || !is_readable($main_path.$file_path)) {
  10884. continue;
  10885. }
  10886. $dest_file = $archivePath.$temp_dir_short.'/document/'.$file_path;
  10887. if (strstr($file_path, 'upload/users') !== false) {
  10888. $pos = strpos($file_path, 'my_files/');
  10889. if ($pos !== false) {
  10890. $onlyDirectory = str_replace(
  10891. 'upload/users/',
  10892. '',
  10893. substr($file_path, $pos, strlen($file_path))
  10894. );
  10895. $dest_file = $archivePath.$temp_dir_short.'/document/'.$onlyDirectory;
  10896. }
  10897. }
  10898. if (strstr($file_path, 'default_course_document/') !== false) {
  10899. $replace = str_replace('/main', '', $file_path);
  10900. $dest_file = $archivePath.$temp_dir_short.'/document/'.$replace;
  10901. }
  10902. if (empty($dest_file)) {
  10903. continue;
  10904. }
  10905. $this->create_path($dest_file);
  10906. copy($main_path.$file_path, $dest_file);
  10907. // Check if the file needs a link update.
  10908. if (in_array($file_path, array_keys($link_updates))) {
  10909. $string = file_get_contents($dest_file);
  10910. unlink($dest_file);
  10911. foreach ($link_updates[$file_path] as $old_new) {
  10912. // This is an ugly hack that allows .flv files to be found by the flv player that
  10913. // will be added in document/main/inc/lib/flv_player/flv_player.swf and that needs
  10914. // to find the flv to play in document/main/, so we replace main/ in the flv path by
  10915. // ../../.. to return from inc/lib/flv_player to the document/main path.
  10916. if (substr($old_new['dest'], -3) == 'flv' &&
  10917. substr($old_new['dest'], 0, 5) == 'main/'
  10918. ) {
  10919. $old_new['dest'] = str_replace('main/', '../../../', $old_new['dest']);
  10920. }
  10921. $string = str_replace($old_new['orig'], $old_new['dest'], $string);
  10922. }
  10923. file_put_contents($dest_file, $string);
  10924. }
  10925. }
  10926. if (is_array($links_to_create)) {
  10927. foreach ($links_to_create as $file => $link) {
  10928. $content = '<!DOCTYPE html><head>
  10929. <meta charset="'.api_get_language_isocode().'" />
  10930. <title>'.$link['title'].'</title>
  10931. </head>
  10932. <body dir="'.api_get_text_direction().'">
  10933. <div style="text-align:center">
  10934. <a href="'.$link['url'].'">'.$link['title'].'</a></div>
  10935. </body>
  10936. </html>';
  10937. file_put_contents($archivePath.$temp_dir_short.'/'.$file, $content);
  10938. }
  10939. }
  10940. // Add non exportable message explanation.
  10941. $lang_not_exportable = get_lang('ThisItemIsNotExportable');
  10942. $file_content = '<!DOCTYPE html><head>
  10943. <meta charset="'.api_get_language_isocode().'" />
  10944. <title>'.$lang_not_exportable.'</title>
  10945. <meta http-equiv="Content-Type" content="text/html; charset='.api_get_system_encoding().'" />
  10946. </head>
  10947. <body dir="'.api_get_text_direction().'">';
  10948. $file_content .=
  10949. <<<EOD
  10950. <style>
  10951. .error-message {
  10952. font-family: arial, verdana, helvetica, sans-serif;
  10953. border-width: 1px;
  10954. border-style: solid;
  10955. left: 50%;
  10956. margin: 10px auto;
  10957. min-height: 30px;
  10958. padding: 5px;
  10959. right: 50%;
  10960. width: 500px;
  10961. background-color: #FFD1D1;
  10962. border-color: #FF0000;
  10963. color: #000;
  10964. }
  10965. </style>
  10966. <body>
  10967. <div class="error-message">
  10968. $lang_not_exportable
  10969. </div>
  10970. </body>
  10971. </html>
  10972. EOD;
  10973. if (!is_dir($archivePath.$temp_dir_short.'/document')) {
  10974. @mkdir($archivePath.$temp_dir_short.'/document', api_get_permissions_for_new_directories());
  10975. }
  10976. file_put_contents($archivePath.$temp_dir_short.'/document/non_exportable.html', $file_content);
  10977. // Add the extra files that go along with a SCORM package.
  10978. $main_code_path = api_get_path(SYS_CODE_PATH).'lp/packaging/';
  10979. $fs = new Filesystem();
  10980. $fs->mirror($main_code_path, $archivePath.$temp_dir_short);
  10981. // Finalize the imsmanifest structure, add to the zip, then return the zip.
  10982. $manifest = @$xmldoc->saveXML();
  10983. $manifest = api_utf8_decode_xml($manifest); // The manifest gets the system encoding now.
  10984. file_put_contents($archivePath.'/'.$temp_dir_short.'/imsmanifest.xml', $manifest);
  10985. $zip_folder->add(
  10986. $archivePath.'/'.$temp_dir_short,
  10987. PCLZIP_OPT_REMOVE_PATH,
  10988. $archivePath.'/'.$temp_dir_short.'/'
  10989. );
  10990. // Clean possible temporary files.
  10991. foreach ($files_cleanup as $file) {
  10992. $res = unlink($file);
  10993. if ($res === false) {
  10994. error_log(
  10995. 'Could not delete temp file '.$file.' '.__FILE__.' '.__LINE__,
  10996. 0
  10997. );
  10998. }
  10999. }
  11000. $name = api_replace_dangerous_char($this->get_name()).'.zip';
  11001. DocumentManager::file_send_for_download($temp_zip_file, true, $name);
  11002. }
  11003. /**
  11004. * @param int $lp_id
  11005. *
  11006. * @return bool
  11007. */
  11008. public function scorm_export_to_pdf($lp_id)
  11009. {
  11010. $lp_id = (int) $lp_id;
  11011. $files_to_export = [];
  11012. $sessionId = api_get_session_id();
  11013. $course_data = api_get_course_info($this->cc);
  11014. if (!empty($course_data)) {
  11015. $scorm_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/scorm/'.$this->path;
  11016. $list = self::get_flat_ordered_items_list($lp_id);
  11017. if (!empty($list)) {
  11018. foreach ($list as $item_id) {
  11019. $item = $this->items[$item_id];
  11020. switch ($item->type) {
  11021. case 'document':
  11022. // Getting documents from a LP with chamilo documents
  11023. $file_data = DocumentManager::get_document_data_by_id($item->path, $this->cc);
  11024. // Try loading document from the base course.
  11025. if (empty($file_data) && !empty($sessionId)) {
  11026. $file_data = DocumentManager::get_document_data_by_id(
  11027. $item->path,
  11028. $this->cc,
  11029. false,
  11030. 0
  11031. );
  11032. }
  11033. $file_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/document'.$file_data['path'];
  11034. if (file_exists($file_path)) {
  11035. $files_to_export[] = [
  11036. 'title' => $item->get_title(),
  11037. 'path' => $file_path,
  11038. ];
  11039. }
  11040. break;
  11041. case 'asset': //commes from a scorm package generated by chamilo
  11042. case 'sco':
  11043. $file_path = $scorm_path.'/'.$item->path;
  11044. if (file_exists($file_path)) {
  11045. $files_to_export[] = [
  11046. 'title' => $item->get_title(),
  11047. 'path' => $file_path,
  11048. ];
  11049. }
  11050. break;
  11051. case 'dir':
  11052. $files_to_export[] = [
  11053. 'title' => $item->get_title(),
  11054. 'path' => null,
  11055. ];
  11056. break;
  11057. }
  11058. }
  11059. }
  11060. $pdf = new PDF();
  11061. $result = $pdf->html_to_pdf(
  11062. $files_to_export,
  11063. $this->name,
  11064. $this->cc,
  11065. true,
  11066. true,
  11067. true,
  11068. $this->get_name()
  11069. );
  11070. return $result;
  11071. }
  11072. return false;
  11073. }
  11074. /**
  11075. * Temp function to be moved in main_api or the best place around for this.
  11076. * Creates a file path if it doesn't exist.
  11077. *
  11078. * @param string $path
  11079. */
  11080. public function create_path($path)
  11081. {
  11082. $path_bits = explode('/', dirname($path));
  11083. // IS_WINDOWS_OS has been defined in main_api.lib.php
  11084. $path_built = IS_WINDOWS_OS ? '' : '/';
  11085. foreach ($path_bits as $bit) {
  11086. if (!empty($bit)) {
  11087. $new_path = $path_built.$bit;
  11088. if (is_dir($new_path)) {
  11089. $path_built = $new_path.'/';
  11090. } else {
  11091. mkdir($new_path, api_get_permissions_for_new_directories());
  11092. $path_built = $new_path.'/';
  11093. }
  11094. }
  11095. }
  11096. }
  11097. /**
  11098. * Delete the image relative to this learning path. No parameter. Only works on instanciated object.
  11099. *
  11100. * @return bool The results of the unlink function, or false if there was no image to start with
  11101. */
  11102. public function delete_lp_image()
  11103. {
  11104. $img = $this->get_preview_image();
  11105. if ($img != '') {
  11106. $del_file = $this->get_preview_image_path(null, 'sys');
  11107. if (isset($del_file) && file_exists($del_file)) {
  11108. $del_file_2 = $this->get_preview_image_path(64, 'sys');
  11109. if (file_exists($del_file_2)) {
  11110. unlink($del_file_2);
  11111. }
  11112. $this->set_preview_image('');
  11113. return @unlink($del_file);
  11114. }
  11115. }
  11116. return false;
  11117. }
  11118. /**
  11119. * Uploads an author image to the upload/learning_path/images directory.
  11120. *
  11121. * @param array The image array, coming from the $_FILES superglobal
  11122. *
  11123. * @return bool True on success, false on error
  11124. */
  11125. public function upload_image($image_array)
  11126. {
  11127. if (!empty($image_array['name'])) {
  11128. $upload_ok = process_uploaded_file($image_array);
  11129. $has_attachment = true;
  11130. }
  11131. if ($upload_ok && $has_attachment) {
  11132. $courseDir = api_get_course_path().'/upload/learning_path/images';
  11133. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  11134. $updir = $sys_course_path.$courseDir;
  11135. // Try to add an extension to the file if it hasn't one.
  11136. $new_file_name = add_ext_on_mime(stripslashes($image_array['name']), $image_array['type']);
  11137. if (filter_extension($new_file_name)) {
  11138. $file_extension = explode('.', $image_array['name']);
  11139. $file_extension = strtolower($file_extension[sizeof($file_extension) - 1]);
  11140. $filename = uniqid('');
  11141. $new_file_name = $filename.'.'.$file_extension;
  11142. $new_path = $updir.'/'.$new_file_name;
  11143. // Resize the image.
  11144. $temp = new Image($image_array['tmp_name']);
  11145. $temp->resize(104);
  11146. $result = $temp->send_image($new_path);
  11147. // Storing the image filename.
  11148. if ($result) {
  11149. $this->set_preview_image($new_file_name);
  11150. //Resize to 64px to use on course homepage
  11151. $temp->resize(64);
  11152. $temp->send_image($updir.'/'.$filename.'.64.'.$file_extension);
  11153. return true;
  11154. }
  11155. }
  11156. }
  11157. return false;
  11158. }
  11159. /**
  11160. * @param int $lp_id
  11161. * @param string $status
  11162. */
  11163. public function set_autolaunch($lp_id, $status)
  11164. {
  11165. $course_id = api_get_course_int_id();
  11166. $lp_id = (int) $lp_id;
  11167. $status = (int) $status;
  11168. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  11169. // Setting everything to autolaunch = 0
  11170. $attributes['autolaunch'] = 0;
  11171. $where = [
  11172. 'session_id = ? AND c_id = ? ' => [
  11173. api_get_session_id(),
  11174. $course_id,
  11175. ],
  11176. ];
  11177. Database::update($lp_table, $attributes, $where);
  11178. if ($status == 1) {
  11179. //Setting my lp_id to autolaunch = 1
  11180. $attributes['autolaunch'] = 1;
  11181. $where = [
  11182. 'iid = ? AND session_id = ? AND c_id = ?' => [
  11183. $lp_id,
  11184. api_get_session_id(),
  11185. $course_id,
  11186. ],
  11187. ];
  11188. Database::update($lp_table, $attributes, $where);
  11189. }
  11190. }
  11191. /**
  11192. * Gets previous_item_id for the next element of the lp_item table.
  11193. *
  11194. * @author Isaac flores paz
  11195. *
  11196. * @return int Previous item ID
  11197. */
  11198. public function select_previous_item_id()
  11199. {
  11200. $course_id = api_get_course_int_id();
  11201. if ($this->debug > 0) {
  11202. error_log('In learnpath::select_previous_item_id()', 0);
  11203. }
  11204. $table_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  11205. // Get the max order of the items
  11206. $sql = "SELECT max(display_order) AS display_order FROM $table_lp_item
  11207. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  11208. $rs_max_order = Database::query($sql);
  11209. $row_max_order = Database::fetch_object($rs_max_order);
  11210. $max_order = $row_max_order->display_order;
  11211. // Get the previous item ID
  11212. $sql = "SELECT iid as previous FROM $table_lp_item
  11213. WHERE
  11214. c_id = $course_id AND
  11215. lp_id = ".$this->lp_id." AND
  11216. display_order = '$max_order' ";
  11217. $rs_max = Database::query($sql);
  11218. $row_max = Database::fetch_object($rs_max);
  11219. // Return the previous item ID
  11220. return $row_max->previous;
  11221. }
  11222. /**
  11223. * Copies an LP.
  11224. */
  11225. public function copy()
  11226. {
  11227. // Course builder
  11228. $cb = new CourseBuilder();
  11229. //Setting tools that will be copied
  11230. $cb->set_tools_to_build(['learnpaths']);
  11231. //Setting elements that will be copied
  11232. $cb->set_tools_specific_id_list(
  11233. ['learnpaths' => [$this->lp_id]]
  11234. );
  11235. $course = $cb->build();
  11236. //Course restorer
  11237. $course_restorer = new CourseRestorer($course);
  11238. $course_restorer->set_add_text_in_items(true);
  11239. $course_restorer->set_tool_copy_settings(
  11240. ['learnpaths' => ['reset_dates' => true]]
  11241. );
  11242. $course_restorer->restore(
  11243. api_get_course_id(),
  11244. api_get_session_id(),
  11245. false,
  11246. false
  11247. );
  11248. }
  11249. /**
  11250. * Verify document size.
  11251. *
  11252. * @param string $s
  11253. *
  11254. * @return bool
  11255. */
  11256. public static function verify_document_size($s)
  11257. {
  11258. $post_max = ini_get('post_max_size');
  11259. if (substr($post_max, -1, 1) == 'M') {
  11260. $post_max = intval(substr($post_max, 0, -1)) * 1024 * 1024;
  11261. } elseif (substr($post_max, -1, 1) == 'G') {
  11262. $post_max = intval(substr($post_max, 0, -1)) * 1024 * 1024 * 1024;
  11263. }
  11264. $upl_max = ini_get('upload_max_filesize');
  11265. if (substr($upl_max, -1, 1) == 'M') {
  11266. $upl_max = intval(substr($upl_max, 0, -1)) * 1024 * 1024;
  11267. } elseif (substr($upl_max, -1, 1) == 'G') {
  11268. $upl_max = intval(substr($upl_max, 0, -1)) * 1024 * 1024 * 1024;
  11269. }
  11270. $documents_total_space = DocumentManager::documents_total_space();
  11271. $course_max_space = DocumentManager::get_course_quota();
  11272. $total_size = filesize($s) + $documents_total_space;
  11273. if (filesize($s) > $post_max || filesize($s) > $upl_max || $total_size > $course_max_space) {
  11274. return true;
  11275. } else {
  11276. return false;
  11277. }
  11278. }
  11279. /**
  11280. * Clear LP prerequisites.
  11281. */
  11282. public function clear_prerequisites()
  11283. {
  11284. $course_id = $this->get_course_int_id();
  11285. if ($this->debug > 0) {
  11286. error_log('In learnpath::clear_prerequisites()', 0);
  11287. }
  11288. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  11289. $lp_id = $this->get_id();
  11290. //Cleaning prerequisites
  11291. $sql = "UPDATE $tbl_lp_item SET prerequisite = ''
  11292. WHERE c_id = $course_id AND lp_id = $lp_id";
  11293. Database::query($sql);
  11294. //Cleaning mastery score for exercises
  11295. $sql = "UPDATE $tbl_lp_item SET mastery_score = ''
  11296. WHERE c_id = $course_id AND lp_id = $lp_id AND item_type = 'quiz'";
  11297. Database::query($sql);
  11298. }
  11299. public function set_previous_step_as_prerequisite_for_all_items()
  11300. {
  11301. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  11302. $course_id = $this->get_course_int_id();
  11303. $lp_id = $this->get_id();
  11304. if (!empty($this->items)) {
  11305. $previous_item_id = null;
  11306. $previous_item_max = 0;
  11307. $previous_item_type = null;
  11308. $last_item_not_dir = null;
  11309. $last_item_not_dir_type = null;
  11310. $last_item_not_dir_max = null;
  11311. foreach ($this->ordered_items as $itemId) {
  11312. $item = $this->getItem($itemId);
  11313. // if there was a previous item... (otherwise jump to set it)
  11314. if (!empty($previous_item_id)) {
  11315. $current_item_id = $item->get_id(); //save current id
  11316. if ($item->get_type() != 'dir') {
  11317. // Current item is not a folder, so it qualifies to get a prerequisites
  11318. if ($last_item_not_dir_type == 'quiz') {
  11319. // if previous is quiz, mark its max score as default score to be achieved
  11320. $sql = "UPDATE $tbl_lp_item SET mastery_score = '$last_item_not_dir_max'
  11321. WHERE c_id = $course_id AND lp_id = $lp_id AND iid = $last_item_not_dir";
  11322. Database::query($sql);
  11323. }
  11324. // now simply update the prerequisite to set it to the last non-chapter item
  11325. $sql = "UPDATE $tbl_lp_item SET prerequisite = '$last_item_not_dir'
  11326. WHERE c_id = $course_id AND lp_id = $lp_id AND iid = $current_item_id";
  11327. Database::query($sql);
  11328. // record item as 'non-chapter' reference
  11329. $last_item_not_dir = $item->get_id();
  11330. $last_item_not_dir_type = $item->get_type();
  11331. $last_item_not_dir_max = $item->get_max();
  11332. }
  11333. } else {
  11334. if ($item->get_type() != 'dir') {
  11335. // Current item is not a folder (but it is the first item) so record as last "non-chapter" item
  11336. $last_item_not_dir = $item->get_id();
  11337. $last_item_not_dir_type = $item->get_type();
  11338. $last_item_not_dir_max = $item->get_max();
  11339. }
  11340. }
  11341. // Saving the item as "previous item" for the next loop
  11342. $previous_item_id = $item->get_id();
  11343. $previous_item_max = $item->get_max();
  11344. $previous_item_type = $item->get_type();
  11345. }
  11346. }
  11347. }
  11348. /**
  11349. * @param array $params
  11350. *
  11351. * @throws \Doctrine\ORM\OptimisticLockException
  11352. *
  11353. * @return int
  11354. */
  11355. public static function createCategory($params)
  11356. {
  11357. $em = Database::getManager();
  11358. $item = new CLpCategory();
  11359. $item->setName($params['name']);
  11360. $item->setCId($params['c_id']);
  11361. $em->persist($item);
  11362. $em->flush();
  11363. api_item_property_update(
  11364. api_get_course_info(),
  11365. TOOL_LEARNPATH_CATEGORY,
  11366. $item->getId(),
  11367. 'visible',
  11368. api_get_user_id()
  11369. );
  11370. return $item->getId();
  11371. }
  11372. /**
  11373. * @param array $params
  11374. *
  11375. * @throws \Doctrine\ORM\ORMException
  11376. * @throws \Doctrine\ORM\OptimisticLockException
  11377. * @throws \Doctrine\ORM\TransactionRequiredException
  11378. */
  11379. public static function updateCategory($params)
  11380. {
  11381. $em = Database::getManager();
  11382. /** @var CLpCategory $item */
  11383. $item = $em->find('ChamiloCourseBundle:CLpCategory', $params['id']);
  11384. if ($item) {
  11385. $item->setName($params['name']);
  11386. $em->merge($item);
  11387. $em->flush();
  11388. }
  11389. }
  11390. /**
  11391. * @param int $id
  11392. *
  11393. * @throws \Doctrine\ORM\ORMException
  11394. * @throws \Doctrine\ORM\OptimisticLockException
  11395. * @throws \Doctrine\ORM\TransactionRequiredException
  11396. */
  11397. public static function moveUpCategory($id)
  11398. {
  11399. $id = (int) $id;
  11400. $em = Database::getManager();
  11401. /** @var CLpCategory $item */
  11402. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  11403. if ($item) {
  11404. $position = $item->getPosition() - 1;
  11405. $item->setPosition($position);
  11406. $em->persist($item);
  11407. $em->flush();
  11408. }
  11409. }
  11410. /**
  11411. * @param int $id
  11412. *
  11413. * @throws \Doctrine\ORM\ORMException
  11414. * @throws \Doctrine\ORM\OptimisticLockException
  11415. * @throws \Doctrine\ORM\TransactionRequiredException
  11416. */
  11417. public static function moveDownCategory($id)
  11418. {
  11419. $id = (int) $id;
  11420. $em = Database::getManager();
  11421. /** @var CLpCategory $item */
  11422. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  11423. if ($item) {
  11424. $position = $item->getPosition() + 1;
  11425. $item->setPosition($position);
  11426. $em->persist($item);
  11427. $em->flush();
  11428. }
  11429. }
  11430. /**
  11431. * @param int $courseId
  11432. *
  11433. * @throws \Doctrine\ORM\Query\QueryException
  11434. *
  11435. * @return int|mixed
  11436. */
  11437. public static function getCountCategories($courseId)
  11438. {
  11439. if (empty($courseId)) {
  11440. return 0;
  11441. }
  11442. $em = Database::getManager();
  11443. $query = $em->createQuery('SELECT COUNT(u.id) FROM ChamiloCourseBundle:CLpCategory u WHERE u.cId = :id');
  11444. $query->setParameter('id', $courseId);
  11445. return $query->getSingleScalarResult();
  11446. }
  11447. /**
  11448. * @param int $courseId
  11449. *
  11450. * @return mixed
  11451. */
  11452. public static function getCategories($courseId)
  11453. {
  11454. $em = Database::getManager();
  11455. // Using doctrine extensions
  11456. /** @var SortableRepository $repo */
  11457. $repo = $em->getRepository('ChamiloCourseBundle:CLpCategory');
  11458. $items = $repo
  11459. ->getBySortableGroupsQuery(['cId' => $courseId])
  11460. ->getResult();
  11461. return $items;
  11462. }
  11463. /**
  11464. * @param int $id
  11465. *
  11466. * @throws \Doctrine\ORM\ORMException
  11467. * @throws \Doctrine\ORM\OptimisticLockException
  11468. * @throws \Doctrine\ORM\TransactionRequiredException
  11469. *
  11470. * @return CLpCategory
  11471. */
  11472. public static function getCategory($id)
  11473. {
  11474. $id = (int) $id;
  11475. $em = Database::getManager();
  11476. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  11477. return $item;
  11478. }
  11479. /**
  11480. * @param int $courseId
  11481. *
  11482. * @return array
  11483. */
  11484. public static function getCategoryByCourse($courseId)
  11485. {
  11486. $em = Database::getManager();
  11487. $items = $em->getRepository('ChamiloCourseBundle:CLpCategory')->findBy(
  11488. ['cId' => $courseId]
  11489. );
  11490. return $items;
  11491. }
  11492. /**
  11493. * @param int $id
  11494. *
  11495. * @throws \Doctrine\ORM\ORMException
  11496. * @throws \Doctrine\ORM\OptimisticLockException
  11497. * @throws \Doctrine\ORM\TransactionRequiredException
  11498. *
  11499. * @return mixed
  11500. */
  11501. public static function deleteCategory($id)
  11502. {
  11503. $em = Database::getManager();
  11504. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  11505. if ($item) {
  11506. $courseId = $item->getCId();
  11507. $query = $em->createQuery('SELECT u FROM ChamiloCourseBundle:CLp u WHERE u.cId = :id AND u.categoryId = :catId');
  11508. $query->setParameter('id', $courseId);
  11509. $query->setParameter('catId', $item->getId());
  11510. $lps = $query->getResult();
  11511. // Setting category = 0.
  11512. if ($lps) {
  11513. foreach ($lps as $lpItem) {
  11514. $lpItem->setCategoryId(0);
  11515. }
  11516. }
  11517. // Removing category.
  11518. $em->remove($item);
  11519. $em->flush();
  11520. $courseInfo = api_get_course_info_by_id($courseId);
  11521. $sessionId = api_get_session_id();
  11522. // Delete link tool
  11523. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  11524. $link = 'lp/lp_controller.php?cidReq='.$courseInfo['code'].'&id_session='.$sessionId.'&gidReq=0&gradebook=0&origin=&action=view_category&id='.$id;
  11525. // Delete tools
  11526. $sql = "DELETE FROM $tbl_tool
  11527. WHERE c_id = ".$courseId." AND (link LIKE '$link%' AND image='lp_category.gif')";
  11528. Database::query($sql);
  11529. return true;
  11530. }
  11531. return false;
  11532. }
  11533. /**
  11534. * @param int $courseId
  11535. * @param bool $addSelectOption
  11536. *
  11537. * @return mixed
  11538. */
  11539. public static function getCategoryFromCourseIntoSelect($courseId, $addSelectOption = false)
  11540. {
  11541. $items = self::getCategoryByCourse($courseId);
  11542. $cats = [];
  11543. if ($addSelectOption) {
  11544. $cats = [get_lang('SelectACategory')];
  11545. }
  11546. if (!empty($items)) {
  11547. foreach ($items as $cat) {
  11548. $cats[$cat->getId()] = $cat->getName();
  11549. }
  11550. }
  11551. return $cats;
  11552. }
  11553. /**
  11554. * @param string $courseCode
  11555. * @param int $lpId
  11556. * @param int $user_id
  11557. *
  11558. * @return learnpath
  11559. */
  11560. public static function getLpFromSession($courseCode, $lpId, $user_id)
  11561. {
  11562. $debug = 0;
  11563. $learnPath = null;
  11564. $lpObject = Session::read('lpobject');
  11565. if ($lpObject !== null) {
  11566. $learnPath = UnserializeApi::unserialize('lp', $lpObject);
  11567. if ($debug) {
  11568. error_log('getLpFromSession: unserialize');
  11569. error_log('------getLpFromSession------');
  11570. error_log('------unserialize------');
  11571. error_log("lp_view_session_id: ".$learnPath->lp_view_session_id);
  11572. error_log("api_get_sessionid: ".api_get_session_id());
  11573. }
  11574. }
  11575. if (!is_object($learnPath)) {
  11576. $learnPath = new learnpath($courseCode, $lpId, $user_id);
  11577. if ($debug) {
  11578. error_log('------getLpFromSession------');
  11579. error_log('getLpFromSession: create new learnpath');
  11580. error_log("create new LP with $courseCode - $lpId - $user_id");
  11581. error_log("lp_view_session_id: ".$learnPath->lp_view_session_id);
  11582. error_log("api_get_sessionid: ".api_get_session_id());
  11583. }
  11584. }
  11585. return $learnPath;
  11586. }
  11587. /**
  11588. * @param int $itemId
  11589. *
  11590. * @return learnpathItem|false
  11591. */
  11592. public function getItem($itemId)
  11593. {
  11594. if (isset($this->items[$itemId]) && is_object($this->items[$itemId])) {
  11595. return $this->items[$itemId];
  11596. }
  11597. return false;
  11598. }
  11599. /**
  11600. * @return int
  11601. */
  11602. public function getCategoryId()
  11603. {
  11604. return (int) $this->categoryId;
  11605. }
  11606. /**
  11607. * @param int $categoryId
  11608. *
  11609. * @return bool
  11610. */
  11611. public function setCategoryId($categoryId)
  11612. {
  11613. $this->categoryId = (int) $categoryId;
  11614. $table = Database::get_course_table(TABLE_LP_MAIN);
  11615. $lp_id = $this->get_id();
  11616. $sql = "UPDATE $table SET category_id = ".$this->categoryId."
  11617. WHERE iid = $lp_id";
  11618. Database::query($sql);
  11619. return true;
  11620. }
  11621. /**
  11622. * Get whether this is a learning path with the possibility to subscribe
  11623. * users or not.
  11624. *
  11625. * @return int
  11626. */
  11627. public function getSubscribeUsers()
  11628. {
  11629. return $this->subscribeUsers;
  11630. }
  11631. /**
  11632. * Set whether this is a learning path with the possibility to subscribe
  11633. * users or not.
  11634. *
  11635. * @param int $value (0 = false, 1 = true)
  11636. *
  11637. * @return bool
  11638. */
  11639. public function setSubscribeUsers($value)
  11640. {
  11641. if ($this->debug > 0) {
  11642. error_log('In learnpath::set_subscribe_users()', 0);
  11643. }
  11644. $this->subscribeUsers = (int) $value;
  11645. $table = Database::get_course_table(TABLE_LP_MAIN);
  11646. $lp_id = $this->get_id();
  11647. $sql = "UPDATE $table SET subscribe_users = ".$this->subscribeUsers."
  11648. WHERE iid = $lp_id";
  11649. Database::query($sql);
  11650. return true;
  11651. }
  11652. /**
  11653. * Calculate the count of stars for a user in this LP
  11654. * This calculation is based on the following rules:
  11655. * - the student gets one star when he gets to 50% of the learning path
  11656. * - the student gets a second star when the average score of all tests inside the learning path >= 50%
  11657. * - the student gets a third star when the average score of all tests inside the learning path >= 80%
  11658. * - the student gets the final star when the score for the *last* test is >= 80%.
  11659. *
  11660. * @param int $sessionId Optional. The session ID
  11661. *
  11662. * @return int The count of stars
  11663. */
  11664. public function getCalculateStars($sessionId = 0)
  11665. {
  11666. $stars = 0;
  11667. $progress = self::getProgress(
  11668. $this->lp_id,
  11669. $this->user_id,
  11670. $this->course_int_id,
  11671. $sessionId
  11672. );
  11673. if ($progress >= 50) {
  11674. $stars++;
  11675. }
  11676. // Calculate stars chapters evaluation
  11677. $exercisesItems = $this->getExercisesItems();
  11678. if (!empty($exercisesItems)) {
  11679. $totalResult = 0;
  11680. foreach ($exercisesItems as $exerciseItem) {
  11681. $exerciseResultInfo = Event::getExerciseResultsByUser(
  11682. $this->user_id,
  11683. $exerciseItem->path,
  11684. $this->course_int_id,
  11685. $sessionId,
  11686. $this->lp_id,
  11687. $exerciseItem->db_id
  11688. );
  11689. $exerciseResultInfo = end($exerciseResultInfo);
  11690. if (!$exerciseResultInfo) {
  11691. continue;
  11692. }
  11693. if (!empty($exerciseResultInfo['exe_weighting'])) {
  11694. $exerciseResult = $exerciseResultInfo['exe_result'] * 100 / $exerciseResultInfo['exe_weighting'];
  11695. } else {
  11696. $exerciseResult = 0;
  11697. }
  11698. $totalResult += $exerciseResult;
  11699. }
  11700. $totalExerciseAverage = $totalResult / (count($exercisesItems) > 0 ? count($exercisesItems) : 1);
  11701. if ($totalExerciseAverage >= 50) {
  11702. $stars++;
  11703. }
  11704. if ($totalExerciseAverage >= 80) {
  11705. $stars++;
  11706. }
  11707. }
  11708. // Calculate star for final evaluation
  11709. $finalEvaluationItem = $this->getFinalEvaluationItem();
  11710. if (!empty($finalEvaluationItem)) {
  11711. $evaluationResultInfo = Event::getExerciseResultsByUser(
  11712. $this->user_id,
  11713. $finalEvaluationItem->path,
  11714. $this->course_int_id,
  11715. $sessionId,
  11716. $this->lp_id,
  11717. $finalEvaluationItem->db_id
  11718. );
  11719. $evaluationResultInfo = end($evaluationResultInfo);
  11720. if ($evaluationResultInfo) {
  11721. $evaluationResult = $evaluationResultInfo['exe_result'] * 100 / $evaluationResultInfo['exe_weighting'];
  11722. if ($evaluationResult >= 80) {
  11723. $stars++;
  11724. }
  11725. }
  11726. }
  11727. return $stars;
  11728. }
  11729. /**
  11730. * Get the items of exercise type.
  11731. *
  11732. * @return array The items. Otherwise return false
  11733. */
  11734. public function getExercisesItems()
  11735. {
  11736. $exercises = [];
  11737. foreach ($this->items as $item) {
  11738. if ($item->type != 'quiz') {
  11739. continue;
  11740. }
  11741. $exercises[] = $item;
  11742. }
  11743. array_pop($exercises);
  11744. return $exercises;
  11745. }
  11746. /**
  11747. * Get the item of exercise type (evaluation type).
  11748. *
  11749. * @return array The final evaluation. Otherwise return false
  11750. */
  11751. public function getFinalEvaluationItem()
  11752. {
  11753. $exercises = [];
  11754. foreach ($this->items as $item) {
  11755. if ($item->type != 'quiz') {
  11756. continue;
  11757. }
  11758. $exercises[] = $item;
  11759. }
  11760. return array_pop($exercises);
  11761. }
  11762. /**
  11763. * Calculate the total points achieved for the current user in this learning path.
  11764. *
  11765. * @param int $sessionId Optional. The session Id
  11766. *
  11767. * @return int
  11768. */
  11769. public function getCalculateScore($sessionId = 0)
  11770. {
  11771. // Calculate stars chapters evaluation
  11772. $exercisesItems = $this->getExercisesItems();
  11773. $finalEvaluationItem = $this->getFinalEvaluationItem();
  11774. $totalExercisesResult = 0;
  11775. $totalEvaluationResult = 0;
  11776. if ($exercisesItems !== false) {
  11777. foreach ($exercisesItems as $exerciseItem) {
  11778. $exerciseResultInfo = Event::getExerciseResultsByUser(
  11779. $this->user_id,
  11780. $exerciseItem->path,
  11781. $this->course_int_id,
  11782. $sessionId,
  11783. $this->lp_id,
  11784. $exerciseItem->db_id
  11785. );
  11786. $exerciseResultInfo = end($exerciseResultInfo);
  11787. if (!$exerciseResultInfo) {
  11788. continue;
  11789. }
  11790. $totalExercisesResult += $exerciseResultInfo['exe_result'];
  11791. }
  11792. }
  11793. if (!empty($finalEvaluationItem)) {
  11794. $evaluationResultInfo = Event::getExerciseResultsByUser(
  11795. $this->user_id,
  11796. $finalEvaluationItem->path,
  11797. $this->course_int_id,
  11798. $sessionId,
  11799. $this->lp_id,
  11800. $finalEvaluationItem->db_id
  11801. );
  11802. $evaluationResultInfo = end($evaluationResultInfo);
  11803. if ($evaluationResultInfo) {
  11804. $totalEvaluationResult += $evaluationResultInfo['exe_result'];
  11805. }
  11806. }
  11807. return $totalExercisesResult + $totalEvaluationResult;
  11808. }
  11809. /**
  11810. * Check if URL is not allowed to be show in a iframe.
  11811. *
  11812. * @param string $src
  11813. *
  11814. * @return string
  11815. */
  11816. public function fixBlockedLinks($src)
  11817. {
  11818. $urlInfo = parse_url($src);
  11819. $platformProtocol = 'https';
  11820. if (strpos(api_get_path(WEB_CODE_PATH), 'https') === false) {
  11821. $platformProtocol = 'http';
  11822. }
  11823. $protocolFixApplied = false;
  11824. //Scheme validation to avoid "Notices" when the lesson doesn't contain a valid scheme
  11825. $scheme = isset($urlInfo['scheme']) ? $urlInfo['scheme'] : null;
  11826. $host = isset($urlInfo['host']) ? $urlInfo['host'] : null;
  11827. if ($platformProtocol != $scheme) {
  11828. Session::write('x_frame_source', $src);
  11829. $src = 'blank.php?error=x_frames_options';
  11830. $protocolFixApplied = true;
  11831. }
  11832. if ($protocolFixApplied == false) {
  11833. if (strpos(api_get_path(WEB_PATH), $host) === false) {
  11834. // Check X-Frame-Options
  11835. $ch = curl_init();
  11836. $options = [
  11837. CURLOPT_URL => $src,
  11838. CURLOPT_RETURNTRANSFER => true,
  11839. CURLOPT_HEADER => true,
  11840. CURLOPT_FOLLOWLOCATION => true,
  11841. CURLOPT_ENCODING => "",
  11842. CURLOPT_AUTOREFERER => true,
  11843. CURLOPT_CONNECTTIMEOUT => 120,
  11844. CURLOPT_TIMEOUT => 120,
  11845. CURLOPT_MAXREDIRS => 10,
  11846. ];
  11847. $proxySettings = api_get_configuration_value('proxy_settings');
  11848. if (!empty($proxySettings) &&
  11849. isset($proxySettings['curl_setopt_array'])
  11850. ) {
  11851. $options[CURLOPT_PROXY] = $proxySettings['curl_setopt_array']['CURLOPT_PROXY'];
  11852. $options[CURLOPT_PROXYPORT] = $proxySettings['curl_setopt_array']['CURLOPT_PROXYPORT'];
  11853. }
  11854. curl_setopt_array($ch, $options);
  11855. $response = curl_exec($ch);
  11856. $httpCode = curl_getinfo($ch);
  11857. $headers = substr($response, 0, $httpCode['header_size']);
  11858. $error = false;
  11859. if (stripos($headers, 'X-Frame-Options: DENY') > -1
  11860. //|| stripos($headers, 'X-Frame-Options: SAMEORIGIN') > -1
  11861. ) {
  11862. $error = true;
  11863. }
  11864. if ($error) {
  11865. Session::write('x_frame_source', $src);
  11866. $src = 'blank.php?error=x_frames_options';
  11867. }
  11868. }
  11869. }
  11870. return $src;
  11871. }
  11872. /**
  11873. * Check if this LP has a created forum in the basis course.
  11874. *
  11875. * @return bool
  11876. */
  11877. public function lpHasForum()
  11878. {
  11879. $forumTable = Database::get_course_table(TABLE_FORUM);
  11880. $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  11881. $fakeFrom = "
  11882. $forumTable f
  11883. INNER JOIN $itemProperty ip
  11884. ON (f.forum_id = ip.ref AND f.c_id = ip.c_id)
  11885. ";
  11886. $resultData = Database::select(
  11887. 'COUNT(f.iid) AS qty',
  11888. $fakeFrom,
  11889. [
  11890. 'where' => [
  11891. 'ip.visibility != ? AND ' => 2,
  11892. 'ip.tool = ? AND ' => TOOL_FORUM,
  11893. 'f.c_id = ? AND ' => intval($this->course_int_id),
  11894. 'f.lp_id = ?' => intval($this->lp_id),
  11895. ],
  11896. ],
  11897. 'first'
  11898. );
  11899. return $resultData['qty'] > 0;
  11900. }
  11901. /**
  11902. * Get the forum for this learning path.
  11903. *
  11904. * @param int $sessionId
  11905. *
  11906. * @return bool
  11907. */
  11908. public function getForum($sessionId = 0)
  11909. {
  11910. $forumTable = Database::get_course_table(TABLE_FORUM);
  11911. $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  11912. $fakeFrom = "$forumTable f
  11913. INNER JOIN $itemProperty ip ";
  11914. if ($this->lp_session_id == 0) {
  11915. $fakeFrom .= "
  11916. ON (
  11917. f.forum_id = ip.ref AND f.c_id = ip.c_id AND (
  11918. f.session_id = ip.session_id OR ip.session_id IS NULL
  11919. )
  11920. )
  11921. ";
  11922. } else {
  11923. $fakeFrom .= "
  11924. ON (
  11925. f.forum_id = ip.ref AND f.c_id = ip.c_id AND f.session_id = ip.session_id
  11926. )
  11927. ";
  11928. }
  11929. $resultData = Database::select(
  11930. 'f.*',
  11931. $fakeFrom,
  11932. [
  11933. 'where' => [
  11934. 'ip.visibility != ? AND ' => 2,
  11935. 'ip.tool = ? AND ' => TOOL_FORUM,
  11936. 'f.session_id = ? AND ' => $sessionId,
  11937. 'f.c_id = ? AND ' => intval($this->course_int_id),
  11938. 'f.lp_id = ?' => intval($this->lp_id),
  11939. ],
  11940. ],
  11941. 'first'
  11942. );
  11943. if (empty($resultData)) {
  11944. return false;
  11945. }
  11946. return $resultData;
  11947. }
  11948. /**
  11949. * Create a forum for this learning path.
  11950. *
  11951. * @param int $forumCategoryId
  11952. *
  11953. * @return int The forum ID if was created. Otherwise return false
  11954. */
  11955. public function createForum($forumCategoryId)
  11956. {
  11957. require_once api_get_path(SYS_CODE_PATH).'/forum/forumfunction.inc.php';
  11958. $forumId = store_forum(
  11959. [
  11960. 'lp_id' => $this->lp_id,
  11961. 'forum_title' => $this->name,
  11962. 'forum_comment' => null,
  11963. 'forum_category' => (int) $forumCategoryId,
  11964. 'students_can_edit_group' => ['students_can_edit' => 0],
  11965. 'allow_new_threads_group' => ['allow_new_threads' => 0],
  11966. 'default_view_type_group' => ['default_view_type' => 'flat'],
  11967. 'group_forum' => 0,
  11968. 'public_private_group_forum_group' => ['public_private_group_forum' => 'public'],
  11969. ],
  11970. [],
  11971. true
  11972. );
  11973. return $forumId;
  11974. }
  11975. /**
  11976. * Get the LP Final Item form.
  11977. *
  11978. * @throws Exception
  11979. * @throws HTML_QuickForm_Error
  11980. *
  11981. * @return string
  11982. */
  11983. public function getFinalItemForm()
  11984. {
  11985. $finalItem = $this->getFinalItem();
  11986. $title = '';
  11987. if ($finalItem) {
  11988. $title = $finalItem->get_title();
  11989. $buttonText = get_lang('Save');
  11990. $content = $this->getSavedFinalItem();
  11991. } else {
  11992. $buttonText = get_lang('LPCreateDocument');
  11993. $content = $this->getFinalItemTemplate();
  11994. }
  11995. $courseInfo = api_get_course_info();
  11996. $result = $this->generate_lp_folder($courseInfo);
  11997. $relative_path = api_substr($result['dir'], 1, strlen($result['dir']));
  11998. $relative_prefix = '../../';
  11999. $editorConfig = [
  12000. 'ToolbarSet' => 'LearningPathDocuments',
  12001. 'Width' => '100%',
  12002. 'Height' => '500',
  12003. 'FullPage' => true,
  12004. 'CreateDocumentDir' => $relative_prefix,
  12005. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/',
  12006. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/'.$relative_path,
  12007. ];
  12008. $url = api_get_self().'?'.api_get_cidreq().'&'.http_build_query([
  12009. 'type' => 'document',
  12010. 'lp_id' => $this->lp_id,
  12011. ]);
  12012. $form = new FormValidator('final_item', 'POST', $url);
  12013. $form->addText('title', get_lang('Title'));
  12014. $form->addButtonSave($buttonText);
  12015. $form->addHtml(
  12016. Display::return_message(
  12017. 'Variables :</br></br> <b>((certificate))</b> </br> <b>((skill))</b>',
  12018. 'normal',
  12019. false
  12020. )
  12021. );
  12022. $renderer = $form->defaultRenderer();
  12023. $renderer->setElementTemplate('&nbsp;{label}{element}', 'content_lp_certificate');
  12024. $form->addHtmlEditor(
  12025. 'content_lp_certificate',
  12026. null,
  12027. true,
  12028. false,
  12029. $editorConfig,
  12030. true
  12031. );
  12032. $form->addHidden('action', 'add_final_item');
  12033. $form->addHidden('path', Session::read('pathItem'));
  12034. $form->addHidden('previous', $this->get_last());
  12035. $form->setDefaults(
  12036. ['title' => $title, 'content_lp_certificate' => $content]
  12037. );
  12038. if ($form->validate()) {
  12039. $values = $form->exportValues();
  12040. $lastItemId = $this->getLastInFirstLevel();
  12041. if (!$finalItem) {
  12042. $documentId = $this->create_document(
  12043. $this->course_info,
  12044. $values['content_lp_certificate'],
  12045. $values['title']
  12046. );
  12047. $this->add_item(
  12048. 0,
  12049. $lastItemId,
  12050. 'final_item',
  12051. $documentId,
  12052. $values['title'],
  12053. ''
  12054. );
  12055. Display::addFlash(
  12056. Display::return_message(get_lang('Added'))
  12057. );
  12058. } else {
  12059. $this->edit_document($this->course_info);
  12060. }
  12061. }
  12062. return $form->returnForm();
  12063. }
  12064. /**
  12065. * Check if the current lp item is first, both, last or none from lp list.
  12066. *
  12067. * @param int $currentItemId
  12068. *
  12069. * @return string
  12070. */
  12071. public function isFirstOrLastItem($currentItemId)
  12072. {
  12073. if ($this->debug > 0) {
  12074. error_log('In learnpath::isFirstOrLastItem('.$currentItemId.')', 0);
  12075. }
  12076. $lpItemId = [];
  12077. $typeListNotToVerify = self::getChapterTypes();
  12078. // Using get_toc() function instead $this->items because returns the correct order of the items
  12079. foreach ($this->get_toc() as $item) {
  12080. if (!in_array($item['type'], $typeListNotToVerify)) {
  12081. $lpItemId[] = $item['id'];
  12082. }
  12083. }
  12084. $lastLpItemIndex = count($lpItemId) - 1;
  12085. $position = array_search($currentItemId, $lpItemId);
  12086. switch ($position) {
  12087. case 0:
  12088. if (!$lastLpItemIndex) {
  12089. $answer = 'both';
  12090. break;
  12091. }
  12092. $answer = 'first';
  12093. break;
  12094. case $lastLpItemIndex:
  12095. $answer = 'last';
  12096. break;
  12097. default:
  12098. $answer = 'none';
  12099. }
  12100. return $answer;
  12101. }
  12102. /**
  12103. * Get whether this is a learning path with the accumulated SCORM time or not.
  12104. *
  12105. * @return int
  12106. */
  12107. public function getAccumulateScormTime()
  12108. {
  12109. return $this->accumulateScormTime;
  12110. }
  12111. /**
  12112. * Set whether this is a learning path with the accumulated SCORM time or not.
  12113. *
  12114. * @param int $value (0 = false, 1 = true)
  12115. *
  12116. * @return bool Always returns true
  12117. */
  12118. public function setAccumulateScormTime($value)
  12119. {
  12120. if ($this->debug > 0) {
  12121. error_log('In learnpath::setAccumulateScormTime()', 0);
  12122. }
  12123. $this->accumulateScormTime = (int) $value;
  12124. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  12125. $lp_id = $this->get_id();
  12126. $sql = "UPDATE $lp_table
  12127. SET accumulate_scorm_time = ".$this->accumulateScormTime."
  12128. WHERE iid = $lp_id";
  12129. Database::query($sql);
  12130. return true;
  12131. }
  12132. /**
  12133. * Returns an HTML-formatted link to a resource, to incorporate directly into
  12134. * the new learning path tool.
  12135. *
  12136. * The function is a big switch on tool type.
  12137. * In each case, we query the corresponding table for information and build the link
  12138. * with that information.
  12139. *
  12140. * @author Yannick Warnier <ywarnier@beeznest.org> - rebranding based on
  12141. * previous work (display_addedresource_link_in_learnpath())
  12142. *
  12143. * @param int $course_id Course code
  12144. * @param int $learningPathId The learning path ID (in lp table)
  12145. * @param int $id_in_path the unique index in the items table
  12146. * @param int $lpViewId
  12147. *
  12148. * @return string
  12149. */
  12150. public static function rl_get_resource_link_for_learnpath(
  12151. $course_id,
  12152. $learningPathId,
  12153. $id_in_path,
  12154. $lpViewId
  12155. ) {
  12156. $session_id = api_get_session_id();
  12157. $course_info = api_get_course_info_by_id($course_id);
  12158. $learningPathId = (int) $learningPathId;
  12159. $id_in_path = (int) $id_in_path;
  12160. $lpViewId = (int) $lpViewId;
  12161. $em = Database::getManager();
  12162. $lpItemRepo = $em->getRepository('ChamiloCourseBundle:CLpItem');
  12163. /** @var CLpItem $rowItem */
  12164. $rowItem = $lpItemRepo->findOneBy([
  12165. 'cId' => $course_id,
  12166. 'lpId' => $learningPathId,
  12167. 'iid' => $id_in_path,
  12168. ]);
  12169. if (!$rowItem) {
  12170. // Try one more time with "id"
  12171. /** @var CLpItem $rowItem */
  12172. $rowItem = $lpItemRepo->findOneBy([
  12173. 'cId' => $course_id,
  12174. 'lpId' => $learningPathId,
  12175. 'id' => $id_in_path,
  12176. ]);
  12177. if (!$rowItem) {
  12178. return -1;
  12179. }
  12180. }
  12181. $course_code = $course_info['code'];
  12182. $type = $rowItem->getItemType();
  12183. $id = empty($rowItem->getPath()) ? '0' : $rowItem->getPath();
  12184. $main_dir_path = api_get_path(WEB_CODE_PATH);
  12185. $main_course_path = api_get_path(WEB_COURSE_PATH).$course_info['directory'].'/';
  12186. $link = '';
  12187. $extraParams = api_get_cidreq(true, true, 'learnpath').'&session_id='.$session_id;
  12188. switch ($type) {
  12189. case 'dir':
  12190. return $main_dir_path.'lp/blank.php';
  12191. case TOOL_CALENDAR_EVENT:
  12192. return $main_dir_path.'calendar/agenda.php?agenda_id='.$id.'&'.$extraParams;
  12193. case TOOL_ANNOUNCEMENT:
  12194. return $main_dir_path.'announcements/announcements.php?ann_id='.$id.'&'.$extraParams;
  12195. case TOOL_LINK:
  12196. $linkInfo = Link::getLinkInfo($id);
  12197. if (isset($linkInfo['url'])) {
  12198. return $linkInfo['url'];
  12199. }
  12200. return '';
  12201. case TOOL_QUIZ:
  12202. if (empty($id)) {
  12203. return '';
  12204. }
  12205. // Get the lp_item_view with the highest view_count.
  12206. $learnpathItemViewResult = $em
  12207. ->getRepository('ChamiloCourseBundle:CLpItemView')
  12208. ->findBy(
  12209. ['cId' => $course_id, 'lpItemId' => $rowItem->getId(), 'lpViewId' => $lpViewId],
  12210. ['viewCount' => 'DESC'],
  12211. 1
  12212. );
  12213. /** @var CLpItemView $learnpathItemViewData */
  12214. $learnpathItemViewData = current($learnpathItemViewResult);
  12215. $learnpathItemViewId = $learnpathItemViewData ? $learnpathItemViewData->getId() : 0;
  12216. return $main_dir_path.'exercise/overview.php?'.$extraParams.'&'
  12217. .http_build_query([
  12218. 'lp_init' => 1,
  12219. 'learnpath_item_view_id' => $learnpathItemViewId,
  12220. 'learnpath_id' => $learningPathId,
  12221. 'learnpath_item_id' => $id_in_path,
  12222. 'exerciseId' => $id,
  12223. ]);
  12224. case TOOL_HOTPOTATOES: //lowercase because of strtolower above
  12225. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  12226. $result = Database::query("SELECT * FROM ".$TBL_DOCUMENT." WHERE c_id = $course_id AND iid=$id");
  12227. $myrow = Database::fetch_array($result);
  12228. $path = $myrow['path'];
  12229. return $main_dir_path.'exercise/showinframes.php?file='.$path.'&cid='.$course_code.'&uid='
  12230. .api_get_user_id().'&learnpath_id='.$learningPathId.'&learnpath_item_id='.$id_in_path
  12231. .'&lp_view_id='.$lpViewId.'&'.$extraParams;
  12232. case TOOL_FORUM:
  12233. return $main_dir_path.'forum/viewforum.php?forum='.$id.'&lp=true&'.$extraParams;
  12234. case TOOL_THREAD:
  12235. // forum post
  12236. $tbl_topics = Database::get_course_table(TABLE_FORUM_THREAD);
  12237. if (empty($id)) {
  12238. return '';
  12239. }
  12240. $sql = "SELECT * FROM $tbl_topics WHERE c_id = $course_id AND thread_id=$id";
  12241. $result = Database::query($sql);
  12242. $myrow = Database::fetch_array($result);
  12243. return $main_dir_path.'forum/viewthread.php?thread='.$id.'&forum='.$myrow['forum_id'].'&lp=true&'
  12244. .$extraParams;
  12245. case TOOL_POST:
  12246. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  12247. $result = Database::query("SELECT * FROM $tbl_post WHERE c_id = $course_id AND post_id=$id");
  12248. $myrow = Database::fetch_array($result);
  12249. return $main_dir_path.'forum/viewthread.php?post='.$id.'&thread='.$myrow['thread_id'].'&forum='
  12250. .$myrow['forum_id'].'&lp=true&'.$extraParams;
  12251. case TOOL_READOUT_TEXT:
  12252. return api_get_path(WEB_CODE_PATH).
  12253. 'lp/readout_text.php?&id='.$id.'&lp_id='.$learningPathId.'&'.$extraParams;
  12254. case TOOL_DOCUMENT:
  12255. $repo = $em->getRepository('ChamiloCourseBundle:CDocument');
  12256. $document = $repo->findOneBy(['cId' => $course_id, 'iid' => $id]);
  12257. if (empty($document)) {
  12258. // Try with normal id
  12259. $document = $repo->findOneBy(['cId' => $course_id, 'id' => $id]);
  12260. if (empty($document)) {
  12261. return '';
  12262. }
  12263. }
  12264. $documentPathInfo = pathinfo($document->getPath());
  12265. $mediaSupportedFiles = ['mp3', 'mp4', 'ogv', 'flv', 'm4v'];
  12266. $extension = isset($documentPathInfo['extension']) ? $documentPathInfo['extension'] : '';
  12267. $showDirectUrl = !in_array($extension, $mediaSupportedFiles);
  12268. $openmethod = 2;
  12269. $officedoc = false;
  12270. Session::write('openmethod', $openmethod);
  12271. Session::write('officedoc', $officedoc);
  12272. if ($showDirectUrl) {
  12273. $file = $main_course_path.'document'.$document->getPath().'?'.$extraParams;
  12274. if (api_get_configuration_value('allow_pdf_viewerjs_in_lp')) {
  12275. if (Link::isPdfLink($file)) {
  12276. $pdfUrl = api_get_path(WEB_LIBRARY_PATH).'javascript/ViewerJS/index.html#'.$file;
  12277. return $pdfUrl;
  12278. }
  12279. }
  12280. return $file;
  12281. }
  12282. return api_get_path(WEB_CODE_PATH).'document/showinframes.php?id='.$id.'&'.$extraParams;
  12283. case TOOL_LP_FINAL_ITEM:
  12284. return api_get_path(WEB_CODE_PATH).'lp/lp_final_item.php?&id='.$id.'&lp_id='.$learningPathId.'&'
  12285. .$extraParams;
  12286. case 'assignments':
  12287. return $main_dir_path.'work/work.php?'.$extraParams;
  12288. case TOOL_DROPBOX:
  12289. return $main_dir_path.'dropbox/index.php?'.$extraParams;
  12290. case 'introduction_text': //DEPRECATED
  12291. return '';
  12292. case TOOL_COURSE_DESCRIPTION:
  12293. return $main_dir_path.'course_description?'.$extraParams;
  12294. case TOOL_GROUP:
  12295. return $main_dir_path.'group/group.php?'.$extraParams;
  12296. case TOOL_USER:
  12297. return $main_dir_path.'user/user.php?'.$extraParams;
  12298. case TOOL_STUDENTPUBLICATION:
  12299. if (!empty($rowItem->getPath())) {
  12300. return $main_dir_path.'work/work_list.php?id='.$rowItem->getPath().'&'.$extraParams;
  12301. }
  12302. return $main_dir_path.'work/work.php?'.api_get_cidreq().'&id='.$rowItem->getPath().'&'.$extraParams;
  12303. }
  12304. return $link;
  12305. }
  12306. /**
  12307. * Gets the name of a resource (generally used in learnpath when no name is provided).
  12308. *
  12309. * @author Yannick Warnier <ywarnier@beeznest.org>
  12310. *
  12311. * @param string $course_code Course code
  12312. * @param int $learningPathId
  12313. * @param int $id_in_path The resource ID
  12314. *
  12315. * @return string
  12316. */
  12317. public static function rl_get_resource_name($course_code, $learningPathId, $id_in_path)
  12318. {
  12319. $_course = api_get_course_info($course_code);
  12320. $course_id = $_course['real_id'];
  12321. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  12322. $learningPathId = (int) $learningPathId;
  12323. $id_in_path = (int) $id_in_path;
  12324. $sql = "SELECT item_type, title, ref
  12325. FROM $tbl_lp_item
  12326. WHERE c_id = $course_id AND lp_id = $learningPathId AND iid = $id_in_path";
  12327. $res_item = Database::query($sql);
  12328. if (Database::num_rows($res_item) < 1) {
  12329. return '';
  12330. }
  12331. $row_item = Database::fetch_array($res_item);
  12332. $type = strtolower($row_item['item_type']);
  12333. $id = $row_item['ref'];
  12334. $output = '';
  12335. switch ($type) {
  12336. case TOOL_CALENDAR_EVENT:
  12337. $TABLEAGENDA = Database::get_course_table(TABLE_AGENDA);
  12338. $result = Database::query("SELECT * FROM $TABLEAGENDA WHERE c_id = $course_id AND id=$id");
  12339. $myrow = Database::fetch_array($result);
  12340. $output = $myrow['title'];
  12341. break;
  12342. case TOOL_ANNOUNCEMENT:
  12343. $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
  12344. $result = Database::query("SELECT * FROM $tbl_announcement WHERE c_id = $course_id AND id=$id");
  12345. $myrow = Database::fetch_array($result);
  12346. $output = $myrow['title'];
  12347. break;
  12348. case TOOL_LINK:
  12349. // Doesn't take $target into account.
  12350. $TABLETOOLLINK = Database::get_course_table(TABLE_LINK);
  12351. $result = Database::query("SELECT * FROM $TABLETOOLLINK WHERE c_id = $course_id AND id=$id");
  12352. $myrow = Database::fetch_array($result);
  12353. $output = $myrow['title'];
  12354. break;
  12355. case TOOL_QUIZ:
  12356. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  12357. $result = Database::query("SELECT * FROM $TBL_EXERCICES WHERE c_id = $course_id AND id = $id");
  12358. $myrow = Database::fetch_array($result);
  12359. $output = $myrow['title'];
  12360. break;
  12361. case TOOL_FORUM:
  12362. $TBL_FORUMS = Database::get_course_table(TABLE_FORUM);
  12363. $result = Database::query("SELECT * FROM $TBL_FORUMS WHERE c_id = $course_id AND forum_id = $id");
  12364. $myrow = Database::fetch_array($result);
  12365. $output = $myrow['forum_name'];
  12366. break;
  12367. case TOOL_THREAD: //=topics
  12368. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  12369. // Grabbing the title of the post.
  12370. $sql_title = "SELECT * FROM $tbl_post WHERE c_id = $course_id AND post_id=".$id;
  12371. $result_title = Database::query($sql_title);
  12372. $myrow_title = Database::fetch_array($result_title);
  12373. $output = $myrow_title['post_title'];
  12374. break;
  12375. case TOOL_POST:
  12376. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  12377. //$tbl_post_text = Database::get_course_table(FORUM_POST_TEXT_TABLE);
  12378. $sql = "SELECT * FROM $tbl_post p WHERE c_id = $course_id AND p.post_id = $id";
  12379. $result = Database::query($sql);
  12380. $post = Database::fetch_array($result);
  12381. $output = $post['post_title'];
  12382. break;
  12383. case 'dir':
  12384. $title = $row_item['title'];
  12385. if (!empty($title)) {
  12386. $output = $title;
  12387. } else {
  12388. $output = '-';
  12389. }
  12390. break;
  12391. case TOOL_DOCUMENT:
  12392. $title = $row_item['title'];
  12393. if (!empty($title)) {
  12394. $output = $title;
  12395. } else {
  12396. $output = '-';
  12397. }
  12398. break;
  12399. case 'hotpotatoes':
  12400. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  12401. $result = Database::query("SELECT * FROM $tbl_doc WHERE c_id = $course_id AND iid = $id");
  12402. $myrow = Database::fetch_array($result);
  12403. $pathname = explode('/', $myrow['path']); // Making a correct name for the link.
  12404. $last = count($pathname) - 1; // Making a correct name for the link.
  12405. $filename = $pathname[$last]; // Making a correct name for the link.
  12406. $ext = explode('.', $filename);
  12407. $ext = strtolower($ext[sizeof($ext) - 1]);
  12408. $myrow['path'] = rawurlencode($myrow['path']);
  12409. $output = $filename;
  12410. break;
  12411. }
  12412. return stripslashes($output);
  12413. }
  12414. /**
  12415. * Get the parent names for the current item.
  12416. *
  12417. * @param int $newItemId Optional. The item ID
  12418. *
  12419. * @return array
  12420. */
  12421. public function getCurrentItemParentNames($newItemId = 0)
  12422. {
  12423. $newItemId = $newItemId ?: $this->get_current_item_id();
  12424. $return = [];
  12425. $item = $this->getItem($newItemId);
  12426. $parent = $this->getItem($item->get_parent());
  12427. while ($parent) {
  12428. $return[] = $parent->get_title();
  12429. $parent = $this->getItem($parent->get_parent());
  12430. }
  12431. return array_reverse($return);
  12432. }
  12433. /**
  12434. * Reads and process "lp_subscription_settings" setting.
  12435. *
  12436. * @return array
  12437. */
  12438. public static function getSubscriptionSettings()
  12439. {
  12440. $subscriptionSettings = api_get_configuration_value('lp_subscription_settings');
  12441. if (empty($subscriptionSettings)) {
  12442. // By default allow both settings
  12443. $subscriptionSettings = [
  12444. 'allow_add_users_to_lp' => true,
  12445. 'allow_add_users_to_lp_category' => true,
  12446. ];
  12447. } else {
  12448. $subscriptionSettings = $subscriptionSettings['options'];
  12449. }
  12450. return $subscriptionSettings;
  12451. }
  12452. /**
  12453. * Exports a LP to a courseBuilder zip file. It adds the documents related to the LP.
  12454. */
  12455. public function exportToCourseBuildFormat()
  12456. {
  12457. if (!api_is_allowed_to_edit()) {
  12458. return false;
  12459. }
  12460. $courseBuilder = new CourseBuilder();
  12461. $itemList = [];
  12462. /** @var learnpathItem $item */
  12463. foreach ($this->items as $item) {
  12464. $itemList[$item->get_type()][] = $item->get_path();
  12465. }
  12466. if (empty($itemList)) {
  12467. return false;
  12468. }
  12469. if (isset($itemList['document'])) {
  12470. // Get parents
  12471. foreach ($itemList['document'] as $documentId) {
  12472. $documentInfo = DocumentManager::get_document_data_by_id($documentId, api_get_course_id(), true);
  12473. if (!empty($documentInfo['parents'])) {
  12474. foreach ($documentInfo['parents'] as $parentInfo) {
  12475. if (in_array($parentInfo['iid'], $itemList['document'])) {
  12476. continue;
  12477. }
  12478. $itemList['document'][] = $parentInfo['iid'];
  12479. }
  12480. }
  12481. }
  12482. $courseInfo = api_get_course_info();
  12483. foreach ($itemList['document'] as $documentId) {
  12484. $documentInfo = DocumentManager::get_document_data_by_id($documentId, api_get_course_id());
  12485. $items = DocumentManager::get_resources_from_source_html(
  12486. $documentInfo['absolute_path'],
  12487. true,
  12488. TOOL_DOCUMENT
  12489. );
  12490. if (!empty($items)) {
  12491. foreach ($items as $item) {
  12492. // Get information about source url
  12493. $url = $item[0]; // url
  12494. $scope = $item[1]; // scope (local, remote)
  12495. $type = $item[2]; // type (rel, abs, url)
  12496. $origParseUrl = parse_url($url);
  12497. $realOrigPath = isset($origParseUrl['path']) ? $origParseUrl['path'] : null;
  12498. if ($scope == 'local') {
  12499. if ($type == 'abs' || $type == 'rel') {
  12500. $documentFile = strstr($realOrigPath, 'document');
  12501. if (strpos($realOrigPath, $documentFile) !== false) {
  12502. $documentFile = str_replace('document', '', $documentFile);
  12503. $itemDocumentId = DocumentManager::get_document_id($courseInfo, $documentFile);
  12504. // Document found! Add it to the list
  12505. if ($itemDocumentId) {
  12506. $itemList['document'][] = $itemDocumentId;
  12507. }
  12508. }
  12509. }
  12510. }
  12511. }
  12512. }
  12513. }
  12514. $courseBuilder->build_documents(
  12515. api_get_session_id(),
  12516. $this->get_course_int_id(),
  12517. true,
  12518. $itemList['document']
  12519. );
  12520. }
  12521. if (isset($itemList['quiz'])) {
  12522. $courseBuilder->build_quizzes(
  12523. api_get_session_id(),
  12524. $this->get_course_int_id(),
  12525. true,
  12526. $itemList['quiz']
  12527. );
  12528. }
  12529. require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
  12530. /*if (!empty($itemList['thread'])) {
  12531. $postList = [];
  12532. foreach ($itemList['thread'] as $postId) {
  12533. $post = get_post_information($postId);
  12534. if ($post) {
  12535. if (!isset($itemList['forum'])) {
  12536. $itemList['forum'] = [];
  12537. }
  12538. $itemList['forum'][] = $post['forum_id'];
  12539. $postList[] = $postId;
  12540. }
  12541. }
  12542. if (!empty($postList)) {
  12543. $courseBuilder->build_forum_posts(
  12544. $this->get_course_int_id(),
  12545. null,
  12546. null,
  12547. $postList
  12548. );
  12549. }
  12550. }*/
  12551. if (!empty($itemList['thread'])) {
  12552. $threadList = [];
  12553. $em = Database::getManager();
  12554. $repo = $em->getRepository('ChamiloCourseBundle:CForumThread');
  12555. foreach ($itemList['thread'] as $threadId) {
  12556. /** @var \Chamilo\CourseBundle\Entity\CForumThread $thread */
  12557. $thread = $repo->find($threadId);
  12558. if ($thread) {
  12559. $itemList['forum'][] = $thread->getForumId();
  12560. $threadList[] = $thread->getIid();
  12561. }
  12562. }
  12563. if (!empty($threadList)) {
  12564. $courseBuilder->build_forum_topics(
  12565. api_get_session_id(),
  12566. $this->get_course_int_id(),
  12567. null,
  12568. $threadList
  12569. );
  12570. }
  12571. }
  12572. $forumCategoryList = [];
  12573. if (isset($itemList['forum'])) {
  12574. foreach ($itemList['forum'] as $forumId) {
  12575. $forumInfo = get_forums($forumId);
  12576. $forumCategoryList[] = $forumInfo['forum_category'];
  12577. }
  12578. }
  12579. if (!empty($forumCategoryList)) {
  12580. $courseBuilder->build_forum_category(
  12581. api_get_session_id(),
  12582. $this->get_course_int_id(),
  12583. true,
  12584. $forumCategoryList
  12585. );
  12586. }
  12587. if (!empty($itemList['forum'])) {
  12588. $courseBuilder->build_forums(
  12589. api_get_session_id(),
  12590. $this->get_course_int_id(),
  12591. true,
  12592. $itemList['forum']
  12593. );
  12594. }
  12595. if (isset($itemList['link'])) {
  12596. $courseBuilder->build_links(
  12597. api_get_session_id(),
  12598. $this->get_course_int_id(),
  12599. true,
  12600. $itemList['link']
  12601. );
  12602. }
  12603. if (!empty($itemList['student_publication'])) {
  12604. $courseBuilder->build_works(
  12605. api_get_session_id(),
  12606. $this->get_course_int_id(),
  12607. true,
  12608. $itemList['student_publication']
  12609. );
  12610. }
  12611. $courseBuilder->build_learnpaths(
  12612. api_get_session_id(),
  12613. $this->get_course_int_id(),
  12614. true,
  12615. [$this->get_id()],
  12616. false
  12617. );
  12618. $courseBuilder->restoreDocumentsFromList();
  12619. $zipFile = CourseArchiver::createBackup($courseBuilder->course);
  12620. $zipPath = CourseArchiver::getBackupDir().$zipFile;
  12621. $result = DocumentManager::file_send_for_download(
  12622. $zipPath,
  12623. true,
  12624. $this->get_name().'.zip'
  12625. );
  12626. if ($result) {
  12627. api_not_allowed();
  12628. }
  12629. return true;
  12630. }
  12631. /**
  12632. * Get whether this is a learning path with the accumulated work time or not.
  12633. *
  12634. * @return int
  12635. */
  12636. public function getAccumulateWorkTime()
  12637. {
  12638. return (int) $this->accumulateWorkTime;
  12639. }
  12640. /**
  12641. * Get whether this is a learning path with the accumulated work time or not.
  12642. *
  12643. * @return int
  12644. */
  12645. public function getAccumulateWorkTimeTotalCourse()
  12646. {
  12647. $table = Database::get_course_table(TABLE_LP_MAIN);
  12648. $sql = "SELECT SUM(accumulate_work_time) AS total
  12649. FROM $table
  12650. WHERE c_id = ".$this->course_int_id;
  12651. $result = Database::query($sql);
  12652. $row = Database::fetch_array($result);
  12653. return (int) $row['total'];
  12654. }
  12655. /**
  12656. * Set whether this is a learning path with the accumulated work time or not.
  12657. *
  12658. * @param int $value (0 = false, 1 = true)
  12659. *
  12660. * @return bool
  12661. */
  12662. public function setAccumulateWorkTime($value)
  12663. {
  12664. if (!api_get_configuration_value('lp_minimum_time')) {
  12665. return false;
  12666. }
  12667. $this->accumulateWorkTime = (int) $value;
  12668. $table = Database::get_course_table(TABLE_LP_MAIN);
  12669. $lp_id = $this->get_id();
  12670. $sql = "UPDATE $table SET accumulate_work_time = ".$this->accumulateWorkTime."
  12671. WHERE c_id = ".$this->course_int_id." AND id = $lp_id";
  12672. Database::query($sql);
  12673. return true;
  12674. }
  12675. /**
  12676. * @param int $lpId
  12677. * @param int $courseId
  12678. *
  12679. * @return mixed
  12680. */
  12681. public static function getAccumulateWorkTimePrerequisite($lpId, $courseId)
  12682. {
  12683. $lpId = (int) $lpId;
  12684. $courseId = (int) $courseId;
  12685. $table = Database::get_course_table(TABLE_LP_MAIN);
  12686. $sql = "SELECT accumulate_work_time
  12687. FROM $table
  12688. WHERE c_id = $courseId AND id = $lpId";
  12689. $result = Database::query($sql);
  12690. $row = Database::fetch_array($result);
  12691. return $row['accumulate_work_time'];
  12692. }
  12693. /**
  12694. * @param int $courseId
  12695. *
  12696. * @return int
  12697. */
  12698. public static function getAccumulateWorkTimeTotal($courseId)
  12699. {
  12700. $table = Database::get_course_table(TABLE_LP_MAIN);
  12701. $courseId = (int) $courseId;
  12702. $sql = "SELECT SUM(accumulate_work_time) AS total
  12703. FROM $table
  12704. WHERE c_id = $courseId";
  12705. $result = Database::query($sql);
  12706. $row = Database::fetch_array($result);
  12707. return (int) $row['total'];
  12708. }
  12709. /**
  12710. * In order to use the lp icon option you need to create the "lp_icon" LP extra field
  12711. * and put the images in.
  12712. *
  12713. * @return array
  12714. */
  12715. public static function getIconSelect()
  12716. {
  12717. $theme = api_get_visual_theme();
  12718. $path = api_get_path(SYS_PUBLIC_PATH).'css/themes/'.$theme.'/lp_icons/';
  12719. $icons = ['' => get_lang('SelectAnOption')];
  12720. if (is_dir($path)) {
  12721. $finder = new Finder();
  12722. $finder->files()->in($path);
  12723. $allowedExtensions = ['jpeg', 'jpg', 'png'];
  12724. /** @var SplFileInfo $file */
  12725. foreach ($finder as $file) {
  12726. if (in_array(strtolower($file->getExtension()), $allowedExtensions)) {
  12727. $icons[$file->getFilename()] = $file->getFilename();
  12728. }
  12729. }
  12730. }
  12731. return $icons;
  12732. }
  12733. /**
  12734. * @param int $lpId
  12735. *
  12736. * @return string
  12737. */
  12738. public static function getSelectedIcon($lpId)
  12739. {
  12740. $extraFieldValue = new ExtraFieldValue('lp');
  12741. $lpIcon = $extraFieldValue->get_values_by_handler_and_field_variable($lpId, 'lp_icon');
  12742. $icon = '';
  12743. if (!empty($lpIcon) && isset($lpIcon['value'])) {
  12744. $icon = $lpIcon['value'];
  12745. }
  12746. return $icon;
  12747. }
  12748. /**
  12749. * @param int $lpId
  12750. *
  12751. * @return string
  12752. */
  12753. public static function getSelectedIconHtml($lpId)
  12754. {
  12755. $icon = self::getSelectedIcon($lpId);
  12756. if (empty($icon)) {
  12757. return '';
  12758. }
  12759. $theme = api_get_visual_theme();
  12760. $path = api_get_path(WEB_PUBLIC_PATH).'css/themes/'.$theme.'/lp_icons/'.$icon;
  12761. return Display::img($path);
  12762. }
  12763. /**
  12764. * Get the depth level of LP item.
  12765. *
  12766. * @param array $items
  12767. * @param int $currentItemId
  12768. *
  12769. * @return int
  12770. */
  12771. private static function get_level_for_item($items, $currentItemId)
  12772. {
  12773. $parentItemId = 0;
  12774. if (isset($items[$currentItemId])) {
  12775. $parentItemId = $items[$currentItemId]->parent;
  12776. }
  12777. if ($parentItemId == 0) {
  12778. return 0;
  12779. } else {
  12780. return self::get_level_for_item($items, $parentItemId) + 1;
  12781. }
  12782. }
  12783. /**
  12784. * Generate the link for a learnpath category as course tool.
  12785. *
  12786. * @param int $categoryId
  12787. *
  12788. * @return string
  12789. */
  12790. private static function getCategoryLinkForTool($categoryId)
  12791. {
  12792. $categoryId = (int) $categoryId;
  12793. $link = 'lp/lp_controller.php?'.api_get_cidreq().'&'
  12794. .http_build_query(
  12795. [
  12796. 'action' => 'view_category',
  12797. 'id' => $categoryId,
  12798. ]
  12799. );
  12800. return $link;
  12801. }
  12802. /**
  12803. * Return the scorm item type object with spaces replaced with _
  12804. * The return result is use to build a css classname like scorm_type_$return.
  12805. *
  12806. * @param $in_type
  12807. *
  12808. * @return mixed
  12809. */
  12810. private static function format_scorm_type_item($in_type)
  12811. {
  12812. return str_replace(' ', '_', $in_type);
  12813. }
  12814. /**
  12815. * Check and obtain the lp final item if exist.
  12816. *
  12817. * @return learnpathItem
  12818. */
  12819. private function getFinalItem()
  12820. {
  12821. if (empty($this->items)) {
  12822. return null;
  12823. }
  12824. foreach ($this->items as $item) {
  12825. if ($item->type !== 'final_item') {
  12826. continue;
  12827. }
  12828. return $item;
  12829. }
  12830. }
  12831. /**
  12832. * Get the LP Final Item Template.
  12833. *
  12834. * @return string
  12835. */
  12836. private function getFinalItemTemplate()
  12837. {
  12838. return file_get_contents(api_get_path(SYS_CODE_PATH).'lp/final_item_template/template.html');
  12839. }
  12840. /**
  12841. * Get the LP Final Item Url.
  12842. *
  12843. * @return string
  12844. */
  12845. private function getSavedFinalItem()
  12846. {
  12847. $finalItem = $this->getFinalItem();
  12848. $doc = DocumentManager::get_document_data_by_id(
  12849. $finalItem->path,
  12850. $this->cc
  12851. );
  12852. if ($doc && file_exists($doc['absolute_path'])) {
  12853. return file_get_contents($doc['absolute_path']);
  12854. }
  12855. return '';
  12856. }
  12857. }