learnpath.class.php 537 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309
  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. (
  5263. $type == 1 && $item_type != TOOL_QUIZ && $item_type != TOOL_HOTPOTATOES &&
  5264. WhispeakAuthPlugin::isAllowedToSaveLpItem($this->current)
  5265. )
  5266. ) {
  5267. if ($debug) {
  5268. error_log('item type: '.$item_type);
  5269. error_log('lp type: '.$type);
  5270. }
  5271. $this->items[$this->current]->open($allow_new_attempt);
  5272. $this->autocomplete_parents($this->current);
  5273. $prereq_check = $this->prerequisites_match($this->current);
  5274. if ($debug) {
  5275. error_log('start_current_item will save item with prereq: '.$prereq_check);
  5276. }
  5277. $this->items[$this->current]->save(false, $prereq_check);
  5278. }
  5279. // If sco, then it is supposed to have been updated by some other call.
  5280. if ($item_type == 'sco') {
  5281. $this->items[$this->current]->restart();
  5282. }
  5283. }
  5284. if ($debug) {
  5285. error_log('lp_view_session_id');
  5286. error_log($this->lp_view_session_id);
  5287. error_log('api session id');
  5288. error_log(api_get_session_id());
  5289. error_log('End of learnpath::start_current_item()');
  5290. }
  5291. return true;
  5292. }
  5293. /**
  5294. * Stops the processing and counters for the old item (as held in $this->last).
  5295. *
  5296. * @return bool True/False
  5297. */
  5298. public function stop_previous_item()
  5299. {
  5300. $debug = $this->debug;
  5301. if ($debug) {
  5302. error_log('In learnpath::stop_previous_item()', 0);
  5303. }
  5304. if ($this->last != 0 && $this->last != $this->current &&
  5305. isset($this->items[$this->last]) && is_object($this->items[$this->last])
  5306. ) {
  5307. if ($debug) {
  5308. error_log('In learnpath::stop_previous_item() - '.$this->last.' is object');
  5309. }
  5310. switch ($this->get_type()) {
  5311. case '3':
  5312. if ($this->items[$this->last]->get_type() != 'au') {
  5313. if ($debug) {
  5314. error_log('In learnpath::stop_previous_item() - '.$this->last.' in lp_type 3 is <> au');
  5315. }
  5316. $this->items[$this->last]->close();
  5317. } else {
  5318. if ($debug) {
  5319. error_log('In learnpath::stop_previous_item() - Item is an AU, saving is managed by AICC signals');
  5320. }
  5321. }
  5322. break;
  5323. case '2':
  5324. if ($this->items[$this->last]->get_type() != 'sco') {
  5325. if ($debug) {
  5326. error_log('In learnpath::stop_previous_item() - '.$this->last.' in lp_type 2 is <> sco');
  5327. }
  5328. $this->items[$this->last]->close();
  5329. } else {
  5330. if ($debug) {
  5331. error_log('In learnpath::stop_previous_item() - Item is a SCO, saving is managed by SCO signals');
  5332. }
  5333. }
  5334. break;
  5335. case '1':
  5336. default:
  5337. if ($debug) {
  5338. error_log('In learnpath::stop_previous_item() - '.$this->last.' in lp_type 1 is asset');
  5339. }
  5340. $this->items[$this->last]->close();
  5341. break;
  5342. }
  5343. } else {
  5344. if ($debug) {
  5345. error_log('In learnpath::stop_previous_item() - No previous element found, ignoring...');
  5346. }
  5347. return false;
  5348. }
  5349. return true;
  5350. }
  5351. /**
  5352. * Updates the default view mode from fullscreen to embedded and inversely.
  5353. *
  5354. * @return string The current default view mode ('fullscreen' or 'embedded')
  5355. */
  5356. public function update_default_view_mode()
  5357. {
  5358. if ($this->debug > 0) {
  5359. error_log('In learnpath::update_default_view_mode()', 0);
  5360. }
  5361. $table = Database::get_course_table(TABLE_LP_MAIN);
  5362. $sql = "SELECT * FROM $table
  5363. WHERE iid = ".$this->get_id();
  5364. $res = Database::query($sql);
  5365. if (Database::num_rows($res) > 0) {
  5366. $row = Database::fetch_array($res);
  5367. $default_view_mode = $row['default_view_mod'];
  5368. $view_mode = $default_view_mode;
  5369. switch ($default_view_mode) {
  5370. case 'fullscreen': // default with popup
  5371. $view_mode = 'embedded';
  5372. break;
  5373. case 'embedded': // default view with left menu
  5374. $view_mode = 'embedframe';
  5375. break;
  5376. case 'embedframe': //folded menu
  5377. $view_mode = 'impress';
  5378. break;
  5379. case 'impress':
  5380. $view_mode = 'fullscreen';
  5381. break;
  5382. }
  5383. $sql = "UPDATE $table SET default_view_mod = '$view_mode'
  5384. WHERE iid = ".$this->get_id();
  5385. Database::query($sql);
  5386. $this->mode = $view_mode;
  5387. return $view_mode;
  5388. } else {
  5389. if ($this->debug > 2) {
  5390. error_log('Problem in update_default_view() - could not find LP '.$this->get_id().' in DB', 0);
  5391. }
  5392. }
  5393. return -1;
  5394. }
  5395. /**
  5396. * Updates the default behaviour about auto-commiting SCORM updates.
  5397. *
  5398. * @return bool True if auto-commit has been set to 'on', false otherwise
  5399. */
  5400. public function update_default_scorm_commit()
  5401. {
  5402. if ($this->debug > 0) {
  5403. error_log('In learnpath::update_default_scorm_commit()', 0);
  5404. }
  5405. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5406. $sql = "SELECT * FROM $lp_table
  5407. WHERE iid = ".$this->get_id();
  5408. $res = Database::query($sql);
  5409. if (Database::num_rows($res) > 0) {
  5410. $row = Database::fetch_array($res);
  5411. $force = $row['force_commit'];
  5412. if ($force == 1) {
  5413. $force = 0;
  5414. $force_return = false;
  5415. } elseif ($force == 0) {
  5416. $force = 1;
  5417. $force_return = true;
  5418. }
  5419. $sql = "UPDATE $lp_table SET force_commit = $force
  5420. WHERE iid = ".$this->get_id();
  5421. Database::query($sql);
  5422. $this->force_commit = $force_return;
  5423. return $force_return;
  5424. } else {
  5425. if ($this->debug > 2) {
  5426. error_log('Problem in update_default_scorm_commit() - could not find LP '.$this->get_id().' in DB', 0);
  5427. }
  5428. }
  5429. return -1;
  5430. }
  5431. /**
  5432. * Updates the order of learning paths (goes through all of them by order and fills the gaps).
  5433. *
  5434. * @return bool True on success, false on failure
  5435. */
  5436. public function update_display_order()
  5437. {
  5438. $course_id = api_get_course_int_id();
  5439. $table = Database::get_course_table(TABLE_LP_MAIN);
  5440. $sql = "SELECT * FROM $table
  5441. WHERE c_id = $course_id
  5442. ORDER BY display_order";
  5443. $res = Database::query($sql);
  5444. if ($res === false) {
  5445. return false;
  5446. }
  5447. $num = Database::num_rows($res);
  5448. // First check the order is correct, globally (might be wrong because
  5449. // of versions < 1.8.4).
  5450. if ($num > 0) {
  5451. $i = 1;
  5452. while ($row = Database::fetch_array($res)) {
  5453. if ($row['display_order'] != $i) {
  5454. // If we find a gap in the order, we need to fix it.
  5455. $sql = "UPDATE $table SET display_order = $i
  5456. WHERE iid = ".$row['iid'];
  5457. Database::query($sql);
  5458. }
  5459. $i++;
  5460. }
  5461. }
  5462. return true;
  5463. }
  5464. /**
  5465. * Updates the "prevent_reinit" value that enables control on reinitialising items on second view.
  5466. *
  5467. * @return bool True if prevent_reinit has been set to 'on', false otherwise (or 1 or 0 in this case)
  5468. */
  5469. public function update_reinit()
  5470. {
  5471. if ($this->debug > 0) {
  5472. error_log('In learnpath::update_reinit()', 0);
  5473. }
  5474. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5475. $sql = "SELECT * FROM $lp_table
  5476. WHERE iid = ".$this->get_id();
  5477. $res = Database::query($sql);
  5478. if (Database::num_rows($res) > 0) {
  5479. $row = Database::fetch_array($res);
  5480. $force = $row['prevent_reinit'];
  5481. if ($force == 1) {
  5482. $force = 0;
  5483. } elseif ($force == 0) {
  5484. $force = 1;
  5485. }
  5486. $sql = "UPDATE $lp_table SET prevent_reinit = $force
  5487. WHERE iid = ".$this->get_id();
  5488. Database::query($sql);
  5489. $this->prevent_reinit = $force;
  5490. return $force;
  5491. } else {
  5492. if ($this->debug > 2) {
  5493. error_log('Problem in update_reinit() - could not find LP '.$this->get_id().' in DB', 0);
  5494. }
  5495. }
  5496. return -1;
  5497. }
  5498. /**
  5499. * Determine the attempt_mode thanks to prevent_reinit and seriousgame_mode db flag.
  5500. *
  5501. * @return string 'single', 'multi' or 'seriousgame'
  5502. *
  5503. * @author ndiechburg <noel@cblue.be>
  5504. */
  5505. public function get_attempt_mode()
  5506. {
  5507. //Set default value for seriousgame_mode
  5508. if (!isset($this->seriousgame_mode)) {
  5509. $this->seriousgame_mode = 0;
  5510. }
  5511. // Set default value for prevent_reinit
  5512. if (!isset($this->prevent_reinit)) {
  5513. $this->prevent_reinit = 1;
  5514. }
  5515. if ($this->seriousgame_mode == 1 && $this->prevent_reinit == 1) {
  5516. return 'seriousgame';
  5517. }
  5518. if ($this->seriousgame_mode == 0 && $this->prevent_reinit == 1) {
  5519. return 'single';
  5520. }
  5521. if ($this->seriousgame_mode == 0 && $this->prevent_reinit == 0) {
  5522. return 'multiple';
  5523. }
  5524. return 'single';
  5525. }
  5526. /**
  5527. * Register the attempt mode into db thanks to flags prevent_reinit and seriousgame_mode flags.
  5528. *
  5529. * @param string 'seriousgame', 'single' or 'multiple'
  5530. *
  5531. * @return bool
  5532. *
  5533. * @author ndiechburg <noel@cblue.be>
  5534. */
  5535. public function set_attempt_mode($mode)
  5536. {
  5537. switch ($mode) {
  5538. case 'seriousgame':
  5539. $sg_mode = 1;
  5540. $prevent_reinit = 1;
  5541. break;
  5542. case 'single':
  5543. $sg_mode = 0;
  5544. $prevent_reinit = 1;
  5545. break;
  5546. case 'multiple':
  5547. $sg_mode = 0;
  5548. $prevent_reinit = 0;
  5549. break;
  5550. default:
  5551. $sg_mode = 0;
  5552. $prevent_reinit = 0;
  5553. break;
  5554. }
  5555. $this->prevent_reinit = $prevent_reinit;
  5556. $this->seriousgame_mode = $sg_mode;
  5557. $table = Database::get_course_table(TABLE_LP_MAIN);
  5558. $sql = "UPDATE $table SET
  5559. prevent_reinit = $prevent_reinit ,
  5560. seriousgame_mode = $sg_mode
  5561. WHERE iid = ".$this->get_id();
  5562. $res = Database::query($sql);
  5563. if ($res) {
  5564. return true;
  5565. } else {
  5566. return false;
  5567. }
  5568. }
  5569. /**
  5570. * Switch between multiple attempt, single attempt or serious_game mode (only for scorm).
  5571. *
  5572. * @author ndiechburg <noel@cblue.be>
  5573. */
  5574. public function switch_attempt_mode()
  5575. {
  5576. if ($this->debug > 0) {
  5577. error_log('In learnpath::switch_attempt_mode()', 0);
  5578. }
  5579. $mode = $this->get_attempt_mode();
  5580. switch ($mode) {
  5581. case 'single':
  5582. $next_mode = 'multiple';
  5583. break;
  5584. case 'multiple':
  5585. $next_mode = 'seriousgame';
  5586. break;
  5587. case 'seriousgame':
  5588. $next_mode = 'single';
  5589. break;
  5590. default:
  5591. $next_mode = 'single';
  5592. break;
  5593. }
  5594. $this->set_attempt_mode($next_mode);
  5595. }
  5596. /**
  5597. * Switch the lp in ktm mode. This is a special scorm mode with unique attempt
  5598. * but possibility to do again a completed item.
  5599. *
  5600. * @return bool true if seriousgame_mode has been set to 1, false otherwise
  5601. *
  5602. * @author ndiechburg <noel@cblue.be>
  5603. */
  5604. public function set_seriousgame_mode()
  5605. {
  5606. if ($this->debug > 0) {
  5607. error_log('In learnpath::set_seriousgame_mode()', 0);
  5608. }
  5609. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5610. $sql = "SELECT * FROM $lp_table
  5611. WHERE iid = ".$this->get_id();
  5612. $res = Database::query($sql);
  5613. if (Database::num_rows($res) > 0) {
  5614. $row = Database::fetch_array($res);
  5615. $force = $row['seriousgame_mode'];
  5616. if ($force == 1) {
  5617. $force = 0;
  5618. } elseif ($force == 0) {
  5619. $force = 1;
  5620. }
  5621. $sql = "UPDATE $lp_table SET seriousgame_mode = $force
  5622. WHERE iid = ".$this->get_id();
  5623. Database::query($sql);
  5624. $this->seriousgame_mode = $force;
  5625. return $force;
  5626. } else {
  5627. if ($this->debug > 2) {
  5628. error_log('Problem in set_seriousgame_mode() - could not find LP '.$this->get_id().' in DB', 0);
  5629. }
  5630. }
  5631. return -1;
  5632. }
  5633. /**
  5634. * Updates the "scorm_debug" value that shows or hide the debug window.
  5635. *
  5636. * @return bool True if scorm_debug has been set to 'on', false otherwise (or 1 or 0 in this case)
  5637. */
  5638. public function update_scorm_debug()
  5639. {
  5640. if ($this->debug > 0) {
  5641. error_log('In learnpath::update_scorm_debug()', 0);
  5642. }
  5643. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5644. $sql = "SELECT * FROM $lp_table
  5645. WHERE iid = ".$this->get_id();
  5646. $res = Database::query($sql);
  5647. if (Database::num_rows($res) > 0) {
  5648. $row = Database::fetch_array($res);
  5649. $force = $row['debug'];
  5650. if ($force == 1) {
  5651. $force = 0;
  5652. } elseif ($force == 0) {
  5653. $force = 1;
  5654. }
  5655. $sql = "UPDATE $lp_table SET debug = $force
  5656. WHERE iid = ".$this->get_id();
  5657. Database::query($sql);
  5658. $this->scorm_debug = $force;
  5659. return $force;
  5660. } else {
  5661. if ($this->debug > 2) {
  5662. error_log('Problem in update_scorm_debug() - could not find LP '.$this->get_id().' in DB', 0);
  5663. }
  5664. }
  5665. return -1;
  5666. }
  5667. /**
  5668. * Function that makes a call to the function sort_tree_array and create_tree_array.
  5669. *
  5670. * @author Kevin Van Den Haute
  5671. *
  5672. * @param array
  5673. */
  5674. public function tree_array($array)
  5675. {
  5676. if ($this->debug > 1) {
  5677. error_log('In learnpath::tree_array()', 0);
  5678. }
  5679. $array = $this->sort_tree_array($array);
  5680. $this->create_tree_array($array);
  5681. }
  5682. /**
  5683. * Creates an array with the elements of the learning path tree in it.
  5684. *
  5685. * @author Kevin Van Den Haute
  5686. *
  5687. * @param array $array
  5688. * @param int $parent
  5689. * @param int $depth
  5690. * @param array $tmp
  5691. */
  5692. public function create_tree_array($array, $parent = 0, $depth = -1, $tmp = [])
  5693. {
  5694. if ($this->debug > 1) {
  5695. error_log('In learnpath::create_tree_array())', 0);
  5696. }
  5697. if (is_array($array)) {
  5698. for ($i = 0; $i < count($array); $i++) {
  5699. if ($array[$i]['parent_item_id'] == $parent) {
  5700. if (!in_array($array[$i]['parent_item_id'], $tmp)) {
  5701. $tmp[] = $array[$i]['parent_item_id'];
  5702. $depth++;
  5703. }
  5704. $preq = (empty($array[$i]['prerequisite']) ? '' : $array[$i]['prerequisite']);
  5705. $audio = isset($array[$i]['audio']) ? $array[$i]['audio'] : null;
  5706. $path = isset($array[$i]['path']) ? $array[$i]['path'] : null;
  5707. $prerequisiteMinScore = isset($array[$i]['prerequisite_min_score']) ? $array[$i]['prerequisite_min_score'] : null;
  5708. $prerequisiteMaxScore = isset($array[$i]['prerequisite_max_score']) ? $array[$i]['prerequisite_max_score'] : null;
  5709. $ref = isset($array[$i]['ref']) ? $array[$i]['ref'] : '';
  5710. $this->arrMenu[] = [
  5711. 'id' => $array[$i]['id'],
  5712. 'ref' => $ref,
  5713. 'item_type' => $array[$i]['item_type'],
  5714. 'title' => $array[$i]['title'],
  5715. 'path' => $path,
  5716. 'description' => $array[$i]['description'],
  5717. 'parent_item_id' => $array[$i]['parent_item_id'],
  5718. 'previous_item_id' => $array[$i]['previous_item_id'],
  5719. 'next_item_id' => $array[$i]['next_item_id'],
  5720. 'min_score' => $array[$i]['min_score'],
  5721. 'max_score' => $array[$i]['max_score'],
  5722. 'mastery_score' => $array[$i]['mastery_score'],
  5723. 'display_order' => $array[$i]['display_order'],
  5724. 'prerequisite' => $preq,
  5725. 'depth' => $depth,
  5726. 'audio' => $audio,
  5727. 'prerequisite_min_score' => $prerequisiteMinScore,
  5728. 'prerequisite_max_score' => $prerequisiteMaxScore,
  5729. ];
  5730. $this->create_tree_array($array, $array[$i]['id'], $depth, $tmp);
  5731. }
  5732. }
  5733. }
  5734. }
  5735. /**
  5736. * Sorts a multi dimensional array by parent id and display order.
  5737. *
  5738. * @author Kevin Van Den Haute
  5739. *
  5740. * @param array $array (array with al the learning path items in it)
  5741. *
  5742. * @return array
  5743. */
  5744. public function sort_tree_array($array)
  5745. {
  5746. foreach ($array as $key => $row) {
  5747. $parent[$key] = $row['parent_item_id'];
  5748. $position[$key] = $row['display_order'];
  5749. }
  5750. if (count($array) > 0) {
  5751. array_multisort($parent, SORT_ASC, $position, SORT_ASC, $array);
  5752. }
  5753. return $array;
  5754. }
  5755. /**
  5756. * Function that creates a html list of learning path items so that we can add audio files to them.
  5757. *
  5758. * @author Kevin Van Den Haute
  5759. *
  5760. * @return string
  5761. */
  5762. public function overview()
  5763. {
  5764. if ($this->debug > 0) {
  5765. error_log('In learnpath::overview()', 0);
  5766. }
  5767. $return = '';
  5768. $update_audio = isset($_GET['updateaudio']) ? $_GET['updateaudio'] : null;
  5769. // we need to start a form when we want to update all the mp3 files
  5770. if ($update_audio == 'true') {
  5771. $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">';
  5772. }
  5773. $return .= '<div id="message"></div>';
  5774. if (count($this->items) == 0) {
  5775. $return .= Display::return_message(get_lang('YouShouldAddItemsBeforeAttachAudio'), 'normal');
  5776. } else {
  5777. $return_audio = '<table class="data_table">';
  5778. $return_audio .= '<tr>';
  5779. $return_audio .= '<th width="40%">'.get_lang('Title').'</th>';
  5780. $return_audio .= '<th>'.get_lang('Audio').'</th>';
  5781. $return_audio .= '</tr>';
  5782. if ($update_audio != 'true') {
  5783. $return .= '<div class="col-md-12">';
  5784. $return .= self::return_new_tree($update_audio);
  5785. $return .= '</div>';
  5786. $return .= Display::div(
  5787. Display::url(get_lang('Save'), '#', ['id' => 'listSubmit', 'class' => 'btn btn-primary']),
  5788. ['style' => 'float:left; margin-top:15px;width:100%']
  5789. );
  5790. } else {
  5791. $return_audio .= self::return_new_tree($update_audio);
  5792. $return .= $return_audio.'</table>';
  5793. }
  5794. // We need to close the form when we are updating the mp3 files.
  5795. if ($update_audio == 'true') {
  5796. $return .= '<div class="footer-audio">';
  5797. $return .= Display::button(
  5798. 'save_audio',
  5799. '<em class="fa fa-file-audio-o"></em> '.get_lang('SaveAudioAndOrganization'),
  5800. ['class' => 'btn btn-primary', 'type' => 'submit']
  5801. );
  5802. $return .= '</div>';
  5803. }
  5804. }
  5805. // We need to close the form when we are updating the mp3 files.
  5806. if ($update_audio == 'true' && isset($this->arrMenu) && count($this->arrMenu) != 0) {
  5807. $return .= '</form>';
  5808. }
  5809. return $return;
  5810. }
  5811. /**
  5812. * @param string $update_audio
  5813. *
  5814. * @return array
  5815. */
  5816. public function processBuildMenuElements($update_audio = 'false')
  5817. {
  5818. $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
  5819. $course_id = api_get_course_int_id();
  5820. $table = Database::get_course_table(TABLE_LP_ITEM);
  5821. $sql = "SELECT * FROM $table
  5822. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  5823. $result = Database::query($sql);
  5824. $arrLP = [];
  5825. while ($row = Database::fetch_array($result)) {
  5826. $arrLP[] = [
  5827. 'id' => $row['iid'],
  5828. 'item_type' => $row['item_type'],
  5829. 'title' => Security::remove_XSS($row['title']),
  5830. 'path' => $row['path'],
  5831. 'description' => Security::remove_XSS($row['description']),
  5832. 'parent_item_id' => $row['parent_item_id'],
  5833. 'previous_item_id' => $row['previous_item_id'],
  5834. 'next_item_id' => $row['next_item_id'],
  5835. 'max_score' => $row['max_score'],
  5836. 'min_score' => $row['min_score'],
  5837. 'mastery_score' => $row['mastery_score'],
  5838. 'prerequisite' => $row['prerequisite'],
  5839. 'display_order' => $row['display_order'],
  5840. 'audio' => $row['audio'],
  5841. 'prerequisite_max_score' => $row['prerequisite_max_score'],
  5842. 'prerequisite_min_score' => $row['prerequisite_min_score'],
  5843. ];
  5844. }
  5845. $this->tree_array($arrLP);
  5846. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  5847. unset($this->arrMenu);
  5848. $default_data = null;
  5849. $default_content = null;
  5850. $elements = [];
  5851. $return_audio = null;
  5852. $iconPath = api_get_path(SYS_CODE_PATH).'img/';
  5853. $mainUrl = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq();
  5854. for ($i = 0; $i < count($arrLP); $i++) {
  5855. $title = $arrLP[$i]['title'];
  5856. $title_cut = cut($arrLP[$i]['title'], self::MAX_LP_ITEM_TITLE_LENGTH);
  5857. // Link for the documents
  5858. if ($arrLP[$i]['item_type'] == 'document' || $arrLP[$i]['item_type'] == TOOL_READOUT_TEXT) {
  5859. $url = $mainUrl.'&action=view_item&mode=preview_document&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5860. $title_cut = Display::url(
  5861. $title_cut,
  5862. $url,
  5863. [
  5864. 'class' => 'ajax moved',
  5865. 'data-title' => $title,
  5866. 'title' => $title,
  5867. ]
  5868. );
  5869. }
  5870. // Detect if type is FINAL_ITEM to set path_id to SESSION
  5871. if ($arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM) {
  5872. Session::write('pathItem', $arrLP[$i]['path']);
  5873. }
  5874. if (($i % 2) == 0) {
  5875. $oddClass = 'row_odd';
  5876. } else {
  5877. $oddClass = 'row_even';
  5878. }
  5879. $return_audio .= '<tr id ="lp_item_'.$arrLP[$i]['id'].'" class="'.$oddClass.'">';
  5880. $icon_name = str_replace(' ', '', $arrLP[$i]['item_type']);
  5881. if (file_exists($iconPath.'lp_'.$icon_name.'.png')) {
  5882. $icon = Display::return_icon('lp_'.$icon_name.'.png');
  5883. } else {
  5884. if (file_exists($iconPath.'lp_'.$icon_name.'.gif')) {
  5885. $icon = Display::return_icon('lp_'.$icon_name.'.gif');
  5886. } else {
  5887. if ($arrLP[$i]['item_type'] === TOOL_LP_FINAL_ITEM) {
  5888. $icon = Display::return_icon('certificate.png');
  5889. } else {
  5890. $icon = Display::return_icon('folder_document.gif');
  5891. }
  5892. }
  5893. }
  5894. // The audio column.
  5895. $return_audio .= '<td align="left" style="padding-left:10px;">';
  5896. $audio = '';
  5897. if (!$update_audio || $update_audio != 'true') {
  5898. if (empty($arrLP[$i]['audio'])) {
  5899. $audio .= '';
  5900. }
  5901. } else {
  5902. $types = self::getChapterTypes();
  5903. if (!in_array($arrLP[$i]['item_type'], $types)) {
  5904. $audio .= '<input type="file" name="mp3file'.$arrLP[$i]['id'].'" id="mp3file" />';
  5905. if (!empty($arrLP[$i]['audio'])) {
  5906. $audio .= '<br />'.Security::remove_XSS($arrLP[$i]['audio']).'<br />
  5907. <input type="checkbox" name="removemp3'.$arrLP[$i]['id'].'" id="checkbox'.$arrLP[$i]['id'].'" />'.get_lang('RemoveAudio');
  5908. }
  5909. }
  5910. }
  5911. $return_audio .= Display::span($icon.' '.$title).
  5912. Display::tag(
  5913. 'td',
  5914. $audio,
  5915. ['style' => '']
  5916. );
  5917. $return_audio .= '</td>';
  5918. $move_icon = '';
  5919. $move_item_icon = '';
  5920. $edit_icon = '';
  5921. $delete_icon = '';
  5922. $audio_icon = '';
  5923. $prerequisities_icon = '';
  5924. $forumIcon = '';
  5925. $previewIcon = '';
  5926. $pluginCalendarIcon = '';
  5927. $pluginCalendar = api_get_plugin_setting('learning_calendar', 'enabled') === 'true';
  5928. $plugin = null;
  5929. if ($pluginCalendar) {
  5930. $plugin = LearningCalendarPlugin::create();
  5931. }
  5932. $pluginUrl = api_get_path(WEB_PLUGIN_PATH).'learning_calendar/start.php?';
  5933. if ($is_allowed_to_edit) {
  5934. if (!$update_audio || $update_audio != 'true') {
  5935. if ($arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM) {
  5936. $move_icon .= '<a class="moved" href="#">';
  5937. $move_icon .= Display::return_icon(
  5938. 'move_everywhere.png',
  5939. get_lang('Move'),
  5940. [],
  5941. ICON_SIZE_TINY
  5942. );
  5943. $move_icon .= '</a>';
  5944. }
  5945. }
  5946. // No edit for this item types
  5947. if (!in_array($arrLP[$i]['item_type'], ['sco', 'asset', 'final_item'])) {
  5948. if ($arrLP[$i]['item_type'] != 'dir') {
  5949. $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">';
  5950. $edit_icon .= Display::return_icon(
  5951. 'edit.png',
  5952. get_lang('LearnpathEditModule'),
  5953. [],
  5954. ICON_SIZE_TINY
  5955. );
  5956. $edit_icon .= '</a>';
  5957. if (!in_array($arrLP[$i]['item_type'], ['forum', 'thread'])) {
  5958. $forumThread = null;
  5959. if (isset($this->items[$arrLP[$i]['id']])) {
  5960. $forumThread = $this->items[$arrLP[$i]['id']]->getForumThread(
  5961. $this->course_int_id,
  5962. $this->lp_session_id
  5963. );
  5964. }
  5965. if ($forumThread) {
  5966. $forumIconUrl = $mainUrl.'&'.http_build_query([
  5967. 'action' => 'dissociate_forum',
  5968. 'id' => $arrLP[$i]['id'],
  5969. 'lp_id' => $this->lp_id,
  5970. ]);
  5971. $forumIcon = Display::url(
  5972. Display::return_icon(
  5973. 'forum.png',
  5974. get_lang('DissociateForumToLPItem'),
  5975. [],
  5976. ICON_SIZE_TINY
  5977. ),
  5978. $forumIconUrl,
  5979. ['class' => 'btn btn-default lp-btn-dissociate-forum']
  5980. );
  5981. } else {
  5982. $forumIconUrl = $mainUrl.'&'.http_build_query([
  5983. 'action' => 'create_forum',
  5984. 'id' => $arrLP[$i]['id'],
  5985. 'lp_id' => $this->lp_id,
  5986. ]);
  5987. $forumIcon = Display::url(
  5988. Display::return_icon(
  5989. 'forum.png',
  5990. get_lang('AssociateForumToLPItem'),
  5991. [],
  5992. ICON_SIZE_TINY
  5993. ),
  5994. $forumIconUrl,
  5995. ['class' => 'btn btn-default lp-btn-associate-forum']
  5996. );
  5997. }
  5998. }
  5999. } else {
  6000. $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">';
  6001. $edit_icon .= Display::return_icon(
  6002. 'edit.png',
  6003. get_lang('LearnpathEditModule'),
  6004. [],
  6005. ICON_SIZE_TINY
  6006. );
  6007. $edit_icon .= '</a>';
  6008. }
  6009. } else {
  6010. if ($arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM) {
  6011. $edit_icon .= '<a href="'.$mainUrl.'&action=edit_item&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'" class="btn btn-default">';
  6012. $edit_icon .= Display::return_icon(
  6013. 'edit.png',
  6014. get_lang('Edit'),
  6015. [],
  6016. ICON_SIZE_TINY
  6017. );
  6018. $edit_icon .= '</a>';
  6019. }
  6020. }
  6021. if ($pluginCalendar) {
  6022. $pluginLink = $pluginUrl.
  6023. '&action=toggle_visibility&lp_item_id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  6024. $iconCalendar = Display::return_icon('agenda_na.png', get_lang('OneDay'), [], ICON_SIZE_TINY);
  6025. $itemInfo = $plugin->getItemVisibility($arrLP[$i]['id']);
  6026. if ($itemInfo && $itemInfo['value'] == 1) {
  6027. $iconCalendar = Display::return_icon('agenda.png', get_lang('OneDay'), [], ICON_SIZE_TINY);
  6028. }
  6029. $pluginCalendarIcon = Display::url(
  6030. $iconCalendar,
  6031. $pluginLink,
  6032. ['class' => 'btn btn-default']
  6033. );
  6034. }
  6035. $delete_icon .= ' <a
  6036. href="'.$mainUrl.'&action=delete_item&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'"
  6037. onclick="return confirmation(\''.addslashes($title).'\');"
  6038. class="btn btn-default">';
  6039. $delete_icon .= Display::return_icon(
  6040. 'delete.png',
  6041. get_lang('LearnpathDeleteModule'),
  6042. [],
  6043. ICON_SIZE_TINY
  6044. );
  6045. $delete_icon .= '</a>';
  6046. $url = $mainUrl.'&view=build&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  6047. $previewImage = Display::return_icon(
  6048. 'preview_view.png',
  6049. get_lang('Preview'),
  6050. [],
  6051. ICON_SIZE_TINY
  6052. );
  6053. switch ($arrLP[$i]['item_type']) {
  6054. case TOOL_DOCUMENT:
  6055. case TOOL_LP_FINAL_ITEM:
  6056. case TOOL_READOUT_TEXT:
  6057. $urlPreviewLink = $mainUrl.'&action=view_item&mode=preview_document&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  6058. $previewIcon = Display::url(
  6059. $previewImage,
  6060. $urlPreviewLink,
  6061. [
  6062. 'target' => '_blank',
  6063. 'class' => 'btn btn-default',
  6064. 'data-title' => $arrLP[$i]['title'],
  6065. 'title' => $arrLP[$i]['title'],
  6066. ]
  6067. );
  6068. break;
  6069. case TOOL_THREAD:
  6070. case TOOL_FORUM:
  6071. case TOOL_QUIZ:
  6072. case TOOL_STUDENTPUBLICATION:
  6073. case TOOL_LP_FINAL_ITEM:
  6074. case TOOL_LINK:
  6075. //$target = '';
  6076. //$class = 'btn btn-default ajax';
  6077. //if ($arrLP[$i]['item_type'] == TOOL_LINK) {
  6078. $class = 'btn btn-default';
  6079. $target = '_blank';
  6080. //}
  6081. $link = self::rl_get_resource_link_for_learnpath(
  6082. $this->course_int_id,
  6083. $this->lp_id,
  6084. $arrLP[$i]['id'],
  6085. 0
  6086. );
  6087. $previewIcon = Display::url(
  6088. $previewImage,
  6089. $link,
  6090. [
  6091. 'class' => $class,
  6092. 'data-title' => $arrLP[$i]['title'],
  6093. 'title' => $arrLP[$i]['title'],
  6094. 'target' => $target,
  6095. ]
  6096. );
  6097. break;
  6098. default:
  6099. $previewIcon = Display::url(
  6100. $previewImage,
  6101. $url.'&action=view_item',
  6102. ['class' => 'btn btn-default', 'target' => '_blank']
  6103. );
  6104. break;
  6105. }
  6106. if ($arrLP[$i]['item_type'] != 'dir') {
  6107. $prerequisities_icon = Display::url(
  6108. Display::return_icon(
  6109. 'accept.png',
  6110. get_lang('LearnpathPrerequisites'),
  6111. [],
  6112. ICON_SIZE_TINY
  6113. ),
  6114. $url.'&action=edit_item_prereq',
  6115. ['class' => 'btn btn-default']
  6116. );
  6117. if ($arrLP[$i]['item_type'] != 'final_item') {
  6118. $move_item_icon = Display::url(
  6119. Display::return_icon(
  6120. 'move.png',
  6121. get_lang('Move'),
  6122. [],
  6123. ICON_SIZE_TINY
  6124. ),
  6125. $url.'&action=move_item',
  6126. ['class' => 'btn btn-default']
  6127. );
  6128. }
  6129. $audio_icon = Display::url(
  6130. Display::return_icon(
  6131. 'audio.png',
  6132. get_lang('UplUpload'),
  6133. [],
  6134. ICON_SIZE_TINY
  6135. ),
  6136. $url.'&action=add_audio',
  6137. ['class' => 'btn btn-default']
  6138. );
  6139. }
  6140. }
  6141. if ($update_audio != 'true') {
  6142. $row = $move_icon.' '.$icon.
  6143. Display::span($title_cut).
  6144. Display::tag(
  6145. 'div',
  6146. "<div class=\"btn-group btn-group-xs\">
  6147. $previewIcon
  6148. $audio
  6149. $edit_icon
  6150. $pluginCalendarIcon
  6151. $forumIcon
  6152. $prerequisities_icon
  6153. $move_item_icon
  6154. $audio_icon
  6155. $delete_icon
  6156. </div>",
  6157. ['class' => 'btn-toolbar button_actions']
  6158. );
  6159. } else {
  6160. $row =
  6161. Display::span($title.$icon).
  6162. Display::span($audio, ['class' => 'button_actions']);
  6163. }
  6164. $parent_id = $arrLP[$i]['parent_item_id'];
  6165. $default_data[$arrLP[$i]['id']] = $row;
  6166. $default_content[$arrLP[$i]['id']] = $arrLP[$i];
  6167. if (empty($parent_id)) {
  6168. $elements[$arrLP[$i]['id']]['data'] = $row;
  6169. $elements[$arrLP[$i]['id']]['type'] = $arrLP[$i]['item_type'];
  6170. } else {
  6171. $parent_arrays = [];
  6172. if ($arrLP[$i]['depth'] > 1) {
  6173. //Getting list of parents
  6174. for ($j = 0; $j < $arrLP[$i]['depth']; $j++) {
  6175. foreach ($arrLP as $item) {
  6176. if ($item['id'] == $parent_id) {
  6177. if ($item['parent_item_id'] == 0) {
  6178. $parent_id = $item['id'];
  6179. break;
  6180. } else {
  6181. $parent_id = $item['parent_item_id'];
  6182. if (empty($parent_arrays)) {
  6183. $parent_arrays[] = intval($item['id']);
  6184. }
  6185. $parent_arrays[] = $parent_id;
  6186. break;
  6187. }
  6188. }
  6189. }
  6190. }
  6191. }
  6192. if (!empty($parent_arrays)) {
  6193. $parent_arrays = array_reverse($parent_arrays);
  6194. $val = '$elements';
  6195. $x = 0;
  6196. foreach ($parent_arrays as $item) {
  6197. if ($x != count($parent_arrays) - 1) {
  6198. $val .= '["'.$item.'"]["children"]';
  6199. } else {
  6200. $val .= '["'.$item.'"]["children"]';
  6201. }
  6202. $x++;
  6203. }
  6204. $val .= "";
  6205. $code_str = $val."[".$arrLP[$i]['id']."][\"load_data\"] = '".$arrLP[$i]['id']."' ; ";
  6206. eval($code_str);
  6207. } else {
  6208. $elements[$parent_id]['children'][$arrLP[$i]['id']]['data'] = $row;
  6209. $elements[$parent_id]['children'][$arrLP[$i]['id']]['type'] = $arrLP[$i]['item_type'];
  6210. }
  6211. }
  6212. }
  6213. return [
  6214. 'elements' => $elements,
  6215. 'default_data' => $default_data,
  6216. 'default_content' => $default_content,
  6217. 'return_audio' => $return_audio,
  6218. ];
  6219. }
  6220. /**
  6221. * @param string $updateAudio true/false strings
  6222. *
  6223. * @return string
  6224. */
  6225. public function returnLpItemList($updateAudio)
  6226. {
  6227. $result = $this->processBuildMenuElements($updateAudio);
  6228. $html = self::print_recursive(
  6229. $result['elements'],
  6230. $result['default_data'],
  6231. $result['default_content']
  6232. );
  6233. if (!empty($html)) {
  6234. $html .= Display::return_message(get_lang('DragAndDropAnElementHere'));
  6235. }
  6236. return $html;
  6237. }
  6238. /**
  6239. * @param string $update_audio
  6240. * @param bool $drop_element_here
  6241. *
  6242. * @return string
  6243. */
  6244. public function return_new_tree($update_audio = 'false', $drop_element_here = false)
  6245. {
  6246. $return = '';
  6247. $result = $this->processBuildMenuElements($update_audio);
  6248. $list = '<ul id="lp_item_list">';
  6249. $tree = $this->print_recursive(
  6250. $result['elements'],
  6251. $result['default_data'],
  6252. $result['default_content']
  6253. );
  6254. if (!empty($tree)) {
  6255. $list .= $tree;
  6256. } else {
  6257. if ($drop_element_here) {
  6258. $list .= Display::return_message(get_lang('DragAndDropAnElementHere'));
  6259. }
  6260. }
  6261. $list .= '</ul>';
  6262. $return .= Display::panelCollapse(
  6263. $this->name,
  6264. $list,
  6265. 'scorm-list',
  6266. null,
  6267. 'scorm-list-accordion',
  6268. 'scorm-list-collapse'
  6269. );
  6270. if ($update_audio === 'true') {
  6271. $return = $result['return_audio'];
  6272. }
  6273. return $return;
  6274. }
  6275. /**
  6276. * @param array $elements
  6277. * @param array $default_data
  6278. * @param array $default_content
  6279. *
  6280. * @return string
  6281. */
  6282. public function print_recursive($elements, $default_data, $default_content)
  6283. {
  6284. $return = '';
  6285. foreach ($elements as $key => $item) {
  6286. if (isset($item['load_data']) || empty($item['data'])) {
  6287. $item['data'] = $default_data[$item['load_data']];
  6288. $item['type'] = $default_content[$item['load_data']]['item_type'];
  6289. }
  6290. $sub_list = '';
  6291. if (isset($item['type']) && $item['type'] == 'dir') {
  6292. // empty value
  6293. $sub_list = Display::tag('li', '', ['class' => 'sub_item empty']);
  6294. }
  6295. if (empty($item['children'])) {
  6296. $sub_list = Display::tag('ul', $sub_list, ['id' => 'UL_'.$key, 'class' => 'record li_container']);
  6297. $active = null;
  6298. if (isset($_REQUEST['id']) && $key == $_REQUEST['id']) {
  6299. $active = 'active';
  6300. }
  6301. $return .= Display::tag(
  6302. 'li',
  6303. Display::div($item['data'], ['class' => "item_data $active"]).$sub_list,
  6304. ['id' => $key, 'class' => 'record li_container']
  6305. );
  6306. } else {
  6307. // Sections
  6308. $data = '';
  6309. if (isset($item['children'])) {
  6310. $data = self::print_recursive($item['children'], $default_data, $default_content);
  6311. }
  6312. $sub_list = Display::tag('ul', $sub_list.$data, ['id' => 'UL_'.$key, 'class' => 'record li_container']);
  6313. $return .= Display::tag(
  6314. 'li',
  6315. Display::div($item['data'], ['class' => 'item_data']).$sub_list,
  6316. ['id' => $key, 'class' => 'record li_container']
  6317. );
  6318. }
  6319. }
  6320. return $return;
  6321. }
  6322. /**
  6323. * This function builds the action menu.
  6324. *
  6325. * @param bool $returnContent Optional
  6326. * @param bool $showRequirementButtons Optional. Allow show the requirements button
  6327. * @param bool $isConfigPage Optional. If is the config page, show the edit button
  6328. * @param bool $allowExpand Optional. Allow show the expand/contract button
  6329. *
  6330. * @return string
  6331. */
  6332. public function build_action_menu(
  6333. $returnContent = false,
  6334. $showRequirementButtons = true,
  6335. $isConfigPage = false,
  6336. $allowExpand = true
  6337. ) {
  6338. $actionsLeft = '';
  6339. $actionsRight = '';
  6340. $actionsLeft .= Display::url(
  6341. Display::return_icon(
  6342. 'back.png',
  6343. get_lang('ReturnToLearningPaths'),
  6344. '',
  6345. ICON_SIZE_MEDIUM
  6346. ),
  6347. 'lp_controller.php?'.api_get_cidreq()
  6348. );
  6349. $actionsLeft .= Display::url(
  6350. Display::return_icon(
  6351. 'preview_view.png',
  6352. get_lang('Preview'),
  6353. '',
  6354. ICON_SIZE_MEDIUM
  6355. ),
  6356. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6357. 'action' => 'view',
  6358. 'lp_id' => $this->lp_id,
  6359. 'isStudentView' => 'true',
  6360. ])
  6361. );
  6362. $actionsLeft .= Display::url(
  6363. Display::return_icon(
  6364. 'upload_audio.png',
  6365. get_lang('UpdateAllAudioFragments'),
  6366. '',
  6367. ICON_SIZE_MEDIUM
  6368. ),
  6369. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6370. 'action' => 'admin_view',
  6371. 'lp_id' => $this->lp_id,
  6372. 'updateaudio' => 'true',
  6373. ])
  6374. );
  6375. if (!$isConfigPage) {
  6376. $actionsLeft .= Display::url(
  6377. Display::return_icon(
  6378. 'settings.png',
  6379. get_lang('CourseSettings'),
  6380. '',
  6381. ICON_SIZE_MEDIUM
  6382. ),
  6383. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6384. 'action' => 'edit',
  6385. 'lp_id' => $this->lp_id,
  6386. ])
  6387. );
  6388. } else {
  6389. $actionsLeft .= Display::url(
  6390. Display::return_icon(
  6391. 'edit.png',
  6392. get_lang('Edit'),
  6393. '',
  6394. ICON_SIZE_MEDIUM
  6395. ),
  6396. 'lp_controller.php?'.http_build_query([
  6397. 'action' => 'build',
  6398. 'lp_id' => $this->lp_id,
  6399. ]).'&'.api_get_cidreq()
  6400. );
  6401. }
  6402. if ($allowExpand) {
  6403. $actionsLeft .= Display::url(
  6404. Display::return_icon(
  6405. 'expand.png',
  6406. get_lang('Expand'),
  6407. ['id' => 'expand'],
  6408. ICON_SIZE_MEDIUM
  6409. ).
  6410. Display::return_icon(
  6411. 'contract.png',
  6412. get_lang('Collapse'),
  6413. ['id' => 'contract', 'class' => 'hide'],
  6414. ICON_SIZE_MEDIUM
  6415. ),
  6416. '#',
  6417. ['role' => 'button', 'id' => 'hide_bar_template']
  6418. );
  6419. }
  6420. if ($showRequirementButtons) {
  6421. $buttons = [
  6422. [
  6423. 'title' => get_lang('SetPrerequisiteForEachItem'),
  6424. 'href' => 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6425. 'action' => 'set_previous_step_as_prerequisite',
  6426. 'lp_id' => $this->lp_id,
  6427. ]),
  6428. ],
  6429. [
  6430. 'title' => get_lang('ClearAllPrerequisites'),
  6431. 'href' => 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6432. 'action' => 'clear_prerequisites',
  6433. 'lp_id' => $this->lp_id,
  6434. ]),
  6435. ],
  6436. ];
  6437. $actionsRight = Display::groupButtonWithDropDown(
  6438. get_lang('PrerequisitesOptions'),
  6439. $buttons,
  6440. true
  6441. );
  6442. }
  6443. $toolbar = Display::toolbarAction(
  6444. 'actions-lp-controller',
  6445. [$actionsLeft, $actionsRight]
  6446. );
  6447. if ($returnContent) {
  6448. return $toolbar;
  6449. }
  6450. echo $toolbar;
  6451. }
  6452. /**
  6453. * Creates the default learning path folder.
  6454. *
  6455. * @param array $course
  6456. * @param int $creatorId
  6457. *
  6458. * @return bool
  6459. */
  6460. public static function generate_learning_path_folder($course, $creatorId = 0)
  6461. {
  6462. // Creating learning_path folder
  6463. $dir = '/learning_path';
  6464. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document';
  6465. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6466. $folder = false;
  6467. if (!is_dir($filepath.'/'.$dir)) {
  6468. $folderData = create_unexisting_directory(
  6469. $course,
  6470. $creatorId,
  6471. 0,
  6472. null,
  6473. 0,
  6474. $filepath,
  6475. $dir,
  6476. get_lang('LearningPaths'),
  6477. 0
  6478. );
  6479. if (!empty($folderData)) {
  6480. $folder = true;
  6481. }
  6482. } else {
  6483. $folder = true;
  6484. }
  6485. return $folder;
  6486. }
  6487. /**
  6488. * @param array $course
  6489. * @param string $lp_name
  6490. * @param int $creatorId
  6491. *
  6492. * @return array
  6493. */
  6494. public function generate_lp_folder($course, $lp_name = '', $creatorId = 0)
  6495. {
  6496. $filepath = '';
  6497. $dir = '/learning_path/';
  6498. if (empty($lp_name)) {
  6499. $lp_name = $this->name;
  6500. }
  6501. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6502. $folder = self::generate_learning_path_folder($course, $creatorId);
  6503. // Limits title size
  6504. $title = api_substr(api_replace_dangerous_char($lp_name), 0, 80);
  6505. $dir = $dir.$title;
  6506. // Creating LP folder
  6507. $documentId = null;
  6508. if ($folder) {
  6509. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document';
  6510. if (!is_dir($filepath.'/'.$dir)) {
  6511. $folderData = create_unexisting_directory(
  6512. $course,
  6513. $creatorId,
  6514. 0,
  6515. 0,
  6516. 0,
  6517. $filepath,
  6518. $dir,
  6519. $lp_name
  6520. );
  6521. if (!empty($folderData)) {
  6522. $folder = true;
  6523. }
  6524. $documentId = $folderData['id'];
  6525. } else {
  6526. $folder = true;
  6527. }
  6528. $dir = $dir.'/';
  6529. if ($folder) {
  6530. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document'.$dir;
  6531. }
  6532. }
  6533. if (empty($documentId)) {
  6534. $dir = api_remove_trailing_slash($dir);
  6535. $documentId = DocumentManager::get_document_id($course, $dir, 0);
  6536. }
  6537. $array = [
  6538. 'dir' => $dir,
  6539. 'filepath' => $filepath,
  6540. 'folder' => $folder,
  6541. 'id' => $documentId,
  6542. ];
  6543. return $array;
  6544. }
  6545. /**
  6546. * Create a new document //still needs some finetuning.
  6547. *
  6548. * @param array $courseInfo
  6549. * @param string $content
  6550. * @param string $title
  6551. * @param string $extension
  6552. * @param int $parentId
  6553. * @param int $creatorId creator id
  6554. *
  6555. * @return int
  6556. */
  6557. public function create_document(
  6558. $courseInfo,
  6559. $content = '',
  6560. $title = '',
  6561. $extension = 'html',
  6562. $parentId = 0,
  6563. $creatorId = 0
  6564. ) {
  6565. if (!empty($courseInfo)) {
  6566. $course_id = $courseInfo['real_id'];
  6567. } else {
  6568. $course_id = api_get_course_int_id();
  6569. }
  6570. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6571. $sessionId = api_get_session_id();
  6572. // Generates folder
  6573. $result = $this->generate_lp_folder($courseInfo);
  6574. $dir = $result['dir'];
  6575. if (empty($parentId) || $parentId == '/') {
  6576. $postDir = isset($_POST['dir']) ? $_POST['dir'] : $dir;
  6577. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir; // Please, do not modify this dirname formatting.
  6578. if ($parentId === '/') {
  6579. $dir = '/';
  6580. }
  6581. // Please, do not modify this dirname formatting.
  6582. if (strstr($dir, '..')) {
  6583. $dir = '/';
  6584. }
  6585. if (!empty($dir[0]) && $dir[0] == '.') {
  6586. $dir = substr($dir, 1);
  6587. }
  6588. if (!empty($dir[0]) && $dir[0] != '/') {
  6589. $dir = '/'.$dir;
  6590. }
  6591. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  6592. $dir .= '/';
  6593. }
  6594. } else {
  6595. $parentInfo = DocumentManager::get_document_data_by_id(
  6596. $parentId,
  6597. $courseInfo['code']
  6598. );
  6599. if (!empty($parentInfo)) {
  6600. $dir = $parentInfo['path'].'/';
  6601. }
  6602. }
  6603. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  6604. if (!is_dir($filepath)) {
  6605. $dir = '/';
  6606. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  6607. }
  6608. // stripslashes() before calling api_replace_dangerous_char() because $_POST['title']
  6609. // is already escaped twice when it gets here.
  6610. $originalTitle = !empty($title) ? $title : $_POST['title'];
  6611. if (!empty($title)) {
  6612. $title = api_replace_dangerous_char(stripslashes($title));
  6613. } else {
  6614. $title = api_replace_dangerous_char(stripslashes($_POST['title']));
  6615. }
  6616. $title = disable_dangerous_file($title);
  6617. $filename = $title;
  6618. $content = !empty($content) ? $content : $_POST['content_lp'];
  6619. $tmp_filename = $filename;
  6620. $i = 0;
  6621. while (file_exists($filepath.$tmp_filename.'.'.$extension)) {
  6622. $tmp_filename = $filename.'_'.++$i;
  6623. }
  6624. $filename = $tmp_filename.'.'.$extension;
  6625. if ($extension == 'html') {
  6626. $content = stripslashes($content);
  6627. $content = str_replace(
  6628. api_get_path(WEB_COURSE_PATH),
  6629. api_get_path(REL_PATH).'courses/',
  6630. $content
  6631. );
  6632. // Change the path of mp3 to absolute.
  6633. // The first regexp deals with :// urls.
  6634. $content = preg_replace(
  6635. "|(flashvars=\"file=)([^:/]+)/|",
  6636. "$1".api_get_path(
  6637. REL_COURSE_PATH
  6638. ).$courseInfo['path'].'/document/',
  6639. $content
  6640. );
  6641. // The second regexp deals with audio/ urls.
  6642. $content = preg_replace(
  6643. "|(flashvars=\"file=)([^/]+)/|",
  6644. "$1".api_get_path(
  6645. REL_COURSE_PATH
  6646. ).$courseInfo['path'].'/document/$2/',
  6647. $content
  6648. );
  6649. // For flv player: To prevent edition problem with firefox,
  6650. // we have to use a strange tip (don't blame me please).
  6651. $content = str_replace(
  6652. '</body>',
  6653. '<style type="text/css">body{}</style></body>',
  6654. $content
  6655. );
  6656. }
  6657. if (!file_exists($filepath.$filename)) {
  6658. if ($fp = @fopen($filepath.$filename, 'w')) {
  6659. fputs($fp, $content);
  6660. fclose($fp);
  6661. $file_size = filesize($filepath.$filename);
  6662. $save_file_path = $dir.$filename;
  6663. $document_id = add_document(
  6664. $courseInfo,
  6665. $save_file_path,
  6666. 'file',
  6667. $file_size,
  6668. $tmp_filename,
  6669. '',
  6670. 0, //readonly
  6671. true,
  6672. null,
  6673. $sessionId,
  6674. $creatorId
  6675. );
  6676. if ($document_id) {
  6677. api_item_property_update(
  6678. $courseInfo,
  6679. TOOL_DOCUMENT,
  6680. $document_id,
  6681. 'DocumentAdded',
  6682. $creatorId,
  6683. null,
  6684. null,
  6685. null,
  6686. null,
  6687. $sessionId
  6688. );
  6689. $new_comment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
  6690. $new_title = $originalTitle;
  6691. if ($new_comment || $new_title) {
  6692. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6693. $ct = '';
  6694. if ($new_comment) {
  6695. $ct .= ", comment='".Database::escape_string($new_comment)."'";
  6696. }
  6697. if ($new_title) {
  6698. $ct .= ", title='".Database::escape_string($new_title)."' ";
  6699. }
  6700. $sql = "UPDATE ".$tbl_doc." SET ".substr($ct, 1)."
  6701. WHERE c_id = ".$course_id." AND id = ".$document_id;
  6702. Database::query($sql);
  6703. }
  6704. }
  6705. return $document_id;
  6706. }
  6707. }
  6708. }
  6709. /**
  6710. * Edit a document based on $_POST and $_GET parameters 'dir' and 'path'.
  6711. *
  6712. * @param array $_course array
  6713. */
  6714. public function edit_document($_course)
  6715. {
  6716. $course_id = api_get_course_int_id();
  6717. $urlAppend = api_get_configuration_value('url_append');
  6718. // Please, do not modify this dirname formatting.
  6719. $postDir = isset($_POST['dir']) ? $_POST['dir'] : '';
  6720. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir;
  6721. if (strstr($dir, '..')) {
  6722. $dir = '/';
  6723. }
  6724. if (isset($dir[0]) && $dir[0] == '.') {
  6725. $dir = substr($dir, 1);
  6726. }
  6727. if (isset($dir[0]) && $dir[0] != '/') {
  6728. $dir = '/'.$dir;
  6729. }
  6730. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  6731. $dir .= '/';
  6732. }
  6733. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.$dir;
  6734. if (!is_dir($filepath)) {
  6735. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  6736. }
  6737. $table_doc = Database::get_course_table(TABLE_DOCUMENT);
  6738. if (isset($_POST['path']) && !empty($_POST['path'])) {
  6739. $document_id = (int) $_POST['path'];
  6740. $documentInfo = DocumentManager::get_document_data_by_id($document_id, api_get_course_id(), false, null, true);
  6741. if (empty($documentInfo)) {
  6742. // Try with iid
  6743. $table = Database::get_course_table(TABLE_DOCUMENT);
  6744. $sql = "SELECT id, path FROM $table
  6745. WHERE c_id = $course_id AND iid = $document_id AND path NOT LIKE '%_DELETED_%' ";
  6746. $res_doc = Database::query($sql);
  6747. $row = Database::fetch_array($res_doc);
  6748. if ($row) {
  6749. $document_id = $row['id'];
  6750. $documentPath = $row['path'];
  6751. }
  6752. } else {
  6753. $documentPath = $documentInfo['path'];
  6754. }
  6755. $content = stripslashes($_POST['content_lp']);
  6756. $file = $filepath.$documentPath;
  6757. if (!file_exists($file)) {
  6758. return false;
  6759. }
  6760. if ($fp = @fopen($file, 'w')) {
  6761. $content = str_replace(
  6762. api_get_path(WEB_COURSE_PATH),
  6763. $urlAppend.api_get_path(REL_COURSE_PATH),
  6764. $content
  6765. );
  6766. // Change the path of mp3 to absolute.
  6767. // The first regexp deals with :// urls.
  6768. $content = preg_replace(
  6769. "|(flashvars=\"file=)([^:/]+)/|",
  6770. "$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/',
  6771. $content
  6772. );
  6773. // The second regexp deals with audio/ urls.
  6774. $content = preg_replace(
  6775. "|(flashvars=\"file=)([^:/]+)/|",
  6776. "$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/$2/',
  6777. $content
  6778. );
  6779. fputs($fp, $content);
  6780. fclose($fp);
  6781. $sql = "UPDATE $table_doc SET
  6782. title='".Database::escape_string($_POST['title'])."'
  6783. WHERE c_id = $course_id AND id = ".$document_id;
  6784. Database::query($sql);
  6785. }
  6786. }
  6787. }
  6788. /**
  6789. * Displays the selected item, with a panel for manipulating the item.
  6790. *
  6791. * @param int $item_id
  6792. * @param string $msg
  6793. * @param bool $show_actions
  6794. *
  6795. * @return string
  6796. */
  6797. public function display_item($item_id, $msg = null, $show_actions = true)
  6798. {
  6799. $course_id = api_get_course_int_id();
  6800. $return = '';
  6801. if (is_numeric($item_id)) {
  6802. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  6803. $sql = "SELECT lp.* FROM $tbl_lp_item as lp
  6804. WHERE lp.iid = ".intval($item_id);
  6805. $result = Database::query($sql);
  6806. while ($row = Database::fetch_array($result, 'ASSOC')) {
  6807. $_SESSION['parent_item_id'] = $row['item_type'] == 'dir' ? $item_id : 0;
  6808. // Prevents wrong parent selection for document, see Bug#1251.
  6809. if ($row['item_type'] != 'dir') {
  6810. $_SESSION['parent_item_id'] = $row['parent_item_id'];
  6811. }
  6812. if ($show_actions) {
  6813. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6814. }
  6815. $return .= '<div style="padding:10px;">';
  6816. if ($msg != '') {
  6817. $return .= $msg;
  6818. }
  6819. $return .= '<h3>'.$row['title'].'</h3>';
  6820. switch ($row['item_type']) {
  6821. case TOOL_THREAD:
  6822. $link = $this->rl_get_resource_link_for_learnpath(
  6823. $course_id,
  6824. $row['lp_id'],
  6825. $item_id,
  6826. 0
  6827. );
  6828. $return .= Display::url(
  6829. get_lang('GoToThread'),
  6830. $link,
  6831. ['class' => 'btn btn-primary']
  6832. );
  6833. break;
  6834. case TOOL_FORUM:
  6835. $return .= Display::url(
  6836. get_lang('GoToForum'),
  6837. api_get_path(WEB_CODE_PATH).'forum/viewforum.php?'.api_get_cidreq().'&forum='.$row['path'],
  6838. ['class' => 'btn btn-primary']
  6839. );
  6840. break;
  6841. case TOOL_QUIZ:
  6842. if (!empty($row['path'])) {
  6843. $exercise = new Exercise();
  6844. $exercise->read($row['path']);
  6845. $return .= $exercise->description.'<br />';
  6846. $return .= Display::url(
  6847. get_lang('GoToExercise'),
  6848. api_get_path(WEB_CODE_PATH).'exercise/overview.php?'.api_get_cidreq().'&exerciseId='.$exercise->id,
  6849. ['class' => 'btn btn-primary']
  6850. );
  6851. }
  6852. break;
  6853. case TOOL_LP_FINAL_ITEM:
  6854. $return .= $this->getSavedFinalItem();
  6855. break;
  6856. case TOOL_DOCUMENT:
  6857. case TOOL_READOUT_TEXT:
  6858. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6859. $sql_doc = "SELECT path FROM $tbl_doc
  6860. WHERE c_id = $course_id AND iid = ".intval($row['path']);
  6861. $result = Database::query($sql_doc);
  6862. $path_file = Database::result($result, 0, 0);
  6863. $path_parts = pathinfo($path_file);
  6864. // TODO: Correct the following naive comparisons.
  6865. if (in_array($path_parts['extension'], [
  6866. 'html',
  6867. 'txt',
  6868. 'png',
  6869. 'jpg',
  6870. 'JPG',
  6871. 'jpeg',
  6872. 'JPEG',
  6873. 'gif',
  6874. 'swf',
  6875. 'pdf',
  6876. 'htm',
  6877. ])) {
  6878. $return .= $this->display_document($row['path'], true, true);
  6879. }
  6880. break;
  6881. case TOOL_HOTPOTATOES:
  6882. $return .= $this->display_document($row['path'], false, true);
  6883. break;
  6884. }
  6885. $return .= '</div>';
  6886. }
  6887. }
  6888. return $return;
  6889. }
  6890. /**
  6891. * Shows the needed forms for editing a specific item.
  6892. *
  6893. * @param int $item_id
  6894. *
  6895. * @throws Exception
  6896. * @throws HTML_QuickForm_Error
  6897. *
  6898. * @return string
  6899. */
  6900. public function display_edit_item($item_id)
  6901. {
  6902. $course_id = api_get_course_int_id();
  6903. $return = '';
  6904. $item_id = (int) $item_id;
  6905. if (empty($item_id)) {
  6906. return '';
  6907. }
  6908. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  6909. $sql = "SELECT * FROM $tbl_lp_item
  6910. WHERE iid = ".$item_id;
  6911. $res = Database::query($sql);
  6912. $row = Database::fetch_array($res);
  6913. switch ($row['item_type']) {
  6914. case 'dir':
  6915. case 'asset':
  6916. case 'sco':
  6917. if (isset($_GET['view']) && $_GET['view'] == 'build') {
  6918. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6919. $return .= $this->display_item_form(
  6920. $row['item_type'],
  6921. get_lang('EditCurrentChapter').' :',
  6922. 'edit',
  6923. $item_id,
  6924. $row
  6925. );
  6926. } else {
  6927. $return .= $this->display_item_form(
  6928. $row['item_type'],
  6929. get_lang('EditCurrentChapter').' :',
  6930. 'edit_item',
  6931. $item_id,
  6932. $row
  6933. );
  6934. }
  6935. break;
  6936. case TOOL_DOCUMENT:
  6937. case TOOL_READOUT_TEXT:
  6938. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6939. $sql = "SELECT lp.*, doc.path as dir
  6940. FROM $tbl_lp_item as lp
  6941. LEFT JOIN $tbl_doc as doc
  6942. ON (doc.iid = lp.path AND lp.c_id = doc.c_id)
  6943. WHERE
  6944. doc.c_id = $course_id AND
  6945. lp.iid = ".$item_id;
  6946. $res_step = Database::query($sql);
  6947. $row_step = Database::fetch_array($res_step, 'ASSOC');
  6948. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6949. if ($row['item_type'] === TOOL_DOCUMENT) {
  6950. $return .= $this->display_document_form('edit', $item_id, $row_step);
  6951. }
  6952. if ($row['item_type'] === TOOL_READOUT_TEXT) {
  6953. $return .= $this->displayFrmReadOutText('edit', $item_id, $row_step);
  6954. }
  6955. break;
  6956. case TOOL_LINK:
  6957. $linkId = (int) $row['path'];
  6958. if (!empty($linkId)) {
  6959. $table = Database::get_course_table(TABLE_LINK);
  6960. $sql = 'SELECT url FROM '.$table.'
  6961. WHERE c_id = '.$course_id.' AND iid = '.$linkId;
  6962. $res_link = Database::query($sql);
  6963. $row_link = Database::fetch_array($res_link);
  6964. if (empty($row_link)) {
  6965. // Try with id
  6966. $sql = 'SELECT url FROM '.$table.'
  6967. WHERE c_id = '.$course_id.' AND id = '.$linkId;
  6968. $res_link = Database::query($sql);
  6969. $row_link = Database::fetch_array($res_link);
  6970. }
  6971. if (is_array($row_link)) {
  6972. $row['url'] = $row_link['url'];
  6973. }
  6974. }
  6975. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6976. $return .= $this->display_link_form('edit', $item_id, $row);
  6977. break;
  6978. case TOOL_LP_FINAL_ITEM:
  6979. Session::write('finalItem', true);
  6980. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6981. $sql = "SELECT lp.*, doc.path as dir
  6982. FROM $tbl_lp_item as lp
  6983. LEFT JOIN $tbl_doc as doc
  6984. ON (doc.iid = lp.path AND lp.c_id = doc.c_id)
  6985. WHERE
  6986. doc.c_id = $course_id AND
  6987. lp.iid = ".$item_id;
  6988. $res_step = Database::query($sql);
  6989. $row_step = Database::fetch_array($res_step, 'ASSOC');
  6990. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6991. $return .= $this->display_document_form('edit', $item_id, $row_step);
  6992. break;
  6993. case TOOL_QUIZ:
  6994. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6995. $return .= $this->display_quiz_form('edit', $item_id, $row);
  6996. break;
  6997. case TOOL_HOTPOTATOES:
  6998. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6999. $return .= $this->display_hotpotatoes_form('edit', $item_id, $row);
  7000. break;
  7001. case TOOL_STUDENTPUBLICATION:
  7002. $return .= $this->display_manipulate($item_id, $row['item_type']);
  7003. $return .= $this->display_student_publication_form('edit', $item_id, $row);
  7004. break;
  7005. case TOOL_FORUM:
  7006. $return .= $this->display_manipulate($item_id, $row['item_type']);
  7007. $return .= $this->display_forum_form('edit', $item_id, $row);
  7008. break;
  7009. case TOOL_THREAD:
  7010. $return .= $this->display_manipulate($item_id, $row['item_type']);
  7011. $return .= $this->display_thread_form('edit', $item_id, $row);
  7012. break;
  7013. }
  7014. return $return;
  7015. }
  7016. /**
  7017. * Function that displays a list with al the resources that
  7018. * could be added to the learning path.
  7019. *
  7020. * @throws Exception
  7021. * @throws HTML_QuickForm_Error
  7022. *
  7023. * @return bool
  7024. */
  7025. public function display_resources()
  7026. {
  7027. $course_code = api_get_course_id();
  7028. // Get all the docs.
  7029. $documents = $this->get_documents(true);
  7030. // Get all the exercises.
  7031. $exercises = $this->get_exercises();
  7032. // Get all the links.
  7033. $links = $this->get_links();
  7034. // Get all the student publications.
  7035. $works = $this->get_student_publications();
  7036. // Get all the forums.
  7037. $forums = $this->get_forums(null, $course_code);
  7038. // Get the final item form (see BT#11048) .
  7039. $finish = $this->getFinalItemForm();
  7040. $headers = [
  7041. Display::return_icon('folder_document.png', get_lang('Documents'), [], ICON_SIZE_BIG),
  7042. Display::return_icon('quiz.png', get_lang('Quiz'), [], ICON_SIZE_BIG),
  7043. Display::return_icon('links.png', get_lang('Links'), [], ICON_SIZE_BIG),
  7044. Display::return_icon('works.png', get_lang('Works'), [], ICON_SIZE_BIG),
  7045. Display::return_icon('forum.png', get_lang('Forums'), [], ICON_SIZE_BIG),
  7046. Display::return_icon('add_learnpath_section.png', get_lang('NewChapter'), [], ICON_SIZE_BIG),
  7047. Display::return_icon('certificate.png', get_lang('Certificate'), [], ICON_SIZE_BIG),
  7048. ];
  7049. echo Display::return_message(get_lang('ClickOnTheLearnerViewToSeeYourLearningPath'), 'normal');
  7050. $dir = $this->display_item_form('dir', get_lang('EnterDataNewChapter'), 'add_item');
  7051. $selected = isset($_REQUEST['lp_build_selected']) ? (int) $_REQUEST['lp_build_selected'] : 0;
  7052. echo Display::tabs(
  7053. $headers,
  7054. [
  7055. $documents,
  7056. $exercises,
  7057. $links,
  7058. $works,
  7059. $forums,
  7060. $dir,
  7061. $finish,
  7062. ],
  7063. 'resource_tab',
  7064. [],
  7065. [],
  7066. $selected
  7067. );
  7068. return true;
  7069. }
  7070. /**
  7071. * Returns the extension of a document.
  7072. *
  7073. * @param string $filename
  7074. *
  7075. * @return string Extension (part after the last dot)
  7076. */
  7077. public function get_extension($filename)
  7078. {
  7079. $explode = explode('.', $filename);
  7080. return $explode[count($explode) - 1];
  7081. }
  7082. /**
  7083. * Displays a document by id.
  7084. *
  7085. * @param int $id
  7086. * @param bool $show_title
  7087. * @param bool $iframe
  7088. * @param bool $edit_link
  7089. *
  7090. * @return string
  7091. */
  7092. public function display_document($id, $show_title = false, $iframe = true, $edit_link = false)
  7093. {
  7094. $_course = api_get_course_info();
  7095. $course_id = api_get_course_int_id();
  7096. $id = (int) $id;
  7097. $return = '';
  7098. $table = Database::get_course_table(TABLE_DOCUMENT);
  7099. $sql_doc = "SELECT * FROM $table
  7100. WHERE c_id = $course_id AND iid = $id";
  7101. $res_doc = Database::query($sql_doc);
  7102. $row_doc = Database::fetch_array($res_doc);
  7103. // TODO: Add a path filter.
  7104. if ($iframe) {
  7105. $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>';
  7106. } else {
  7107. $return .= file_get_contents(api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/'.$row_doc['path']);
  7108. }
  7109. return $return;
  7110. }
  7111. /**
  7112. * Return HTML form to add/edit a quiz.
  7113. *
  7114. * @param string $action Action (add/edit)
  7115. * @param int $id Item ID if already exists
  7116. * @param mixed $extra_info Extra information (quiz ID if integer)
  7117. *
  7118. * @throws Exception
  7119. *
  7120. * @return string HTML form
  7121. */
  7122. public function display_quiz_form($action = 'add', $id = 0, $extra_info = '')
  7123. {
  7124. $course_id = api_get_course_int_id();
  7125. $id = (int) $id;
  7126. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7127. $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  7128. if ($id != 0 && is_array($extra_info)) {
  7129. $item_title = $extra_info['title'];
  7130. $item_description = $extra_info['description'];
  7131. } elseif (is_numeric($extra_info)) {
  7132. $sql = "SELECT title, description
  7133. FROM $tbl_quiz
  7134. WHERE c_id = $course_id AND iid = ".$extra_info;
  7135. $result = Database::query($sql);
  7136. $row = Database::fetch_array($result);
  7137. $item_title = $row['title'];
  7138. $item_description = $row['description'];
  7139. } else {
  7140. $item_title = '';
  7141. $item_description = '';
  7142. }
  7143. $item_title = Security::remove_XSS($item_title);
  7144. $item_description = Security::remove_XSS($item_description);
  7145. $parent = 0;
  7146. if ($id != 0 && is_array($extra_info)) {
  7147. $parent = $extra_info['parent_item_id'];
  7148. }
  7149. $sql = "SELECT * FROM $tbl_lp_item
  7150. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  7151. $result = Database::query($sql);
  7152. $arrLP = [];
  7153. while ($row = Database::fetch_array($result)) {
  7154. $arrLP[] = [
  7155. 'id' => $row['iid'],
  7156. 'item_type' => $row['item_type'],
  7157. 'title' => $row['title'],
  7158. 'path' => $row['path'],
  7159. 'description' => $row['description'],
  7160. 'parent_item_id' => $row['parent_item_id'],
  7161. 'previous_item_id' => $row['previous_item_id'],
  7162. 'next_item_id' => $row['next_item_id'],
  7163. 'display_order' => $row['display_order'],
  7164. 'max_score' => $row['max_score'],
  7165. 'min_score' => $row['min_score'],
  7166. 'mastery_score' => $row['mastery_score'],
  7167. 'prerequisite' => $row['prerequisite'],
  7168. 'max_time_allowed' => $row['max_time_allowed'],
  7169. ];
  7170. }
  7171. $this->tree_array($arrLP);
  7172. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7173. unset($this->arrMenu);
  7174. $form = new FormValidator(
  7175. 'quiz_form',
  7176. 'POST',
  7177. $this->getCurrentBuildingModeURL()
  7178. );
  7179. $defaults = [];
  7180. if ($action === 'add') {
  7181. $legend = get_lang('CreateTheExercise');
  7182. } elseif ($action === 'move') {
  7183. $legend = get_lang('MoveTheCurrentExercise');
  7184. } else {
  7185. $legend = get_lang('EditCurrentExecice');
  7186. }
  7187. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  7188. $legend .= Display::return_message(get_lang('Warning').' ! '.get_lang('WarningEditingDocument'));
  7189. }
  7190. $form->addHeader($legend);
  7191. if ($action != 'move') {
  7192. $form->addText('title', get_lang('Title'), true, ['id' => 'idTitle']);
  7193. $defaults['title'] = $item_title;
  7194. }
  7195. // Select for Parent item, root or chapter
  7196. $selectParent = $form->addSelect(
  7197. 'parent',
  7198. get_lang('Parent'),
  7199. [],
  7200. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);']
  7201. );
  7202. $selectParent->addOption($this->name, 0);
  7203. $arrHide = [
  7204. $id,
  7205. ];
  7206. for ($i = 0; $i < count($arrLP); $i++) {
  7207. if ($action != 'add') {
  7208. if (
  7209. ($arrLP[$i]['item_type'] == 'dir') &&
  7210. !in_array($arrLP[$i]['id'], $arrHide) &&
  7211. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7212. ) {
  7213. $selectParent->addOption(
  7214. $arrLP[$i]['title'],
  7215. $arrLP[$i]['id'],
  7216. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7217. );
  7218. if ($parent == $arrLP[$i]['id']) {
  7219. $selectParent->setSelected($arrLP[$i]['id']);
  7220. }
  7221. } else {
  7222. $arrHide[] = $arrLP[$i]['id'];
  7223. }
  7224. } else {
  7225. if ($arrLP[$i]['item_type'] == 'dir') {
  7226. $selectParent->addOption(
  7227. $arrLP[$i]['title'],
  7228. $arrLP[$i]['id'],
  7229. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7230. );
  7231. if ($parent == $arrLP[$i]['id']) {
  7232. $selectParent->setSelected($arrLP[$i]['id']);
  7233. }
  7234. }
  7235. }
  7236. }
  7237. if (is_array($arrLP)) {
  7238. reset($arrLP);
  7239. }
  7240. $selectPrevious = $form->addSelect(
  7241. 'previous',
  7242. get_lang('Position'),
  7243. [],
  7244. ['id' => 'previous']
  7245. );
  7246. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  7247. for ($i = 0; $i < count($arrLP); $i++) {
  7248. if ($arrLP[$i]['parent_item_id'] == $parent &&
  7249. $arrLP[$i]['id'] != $id
  7250. ) {
  7251. $selectPrevious->addOption(
  7252. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  7253. $arrLP[$i]['id']
  7254. );
  7255. if (is_array($extra_info)) {
  7256. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7257. $selectPrevious->setSelected($arrLP[$i]['id']);
  7258. }
  7259. } elseif ($action == 'add') {
  7260. $selectPrevious->setSelected($arrLP[$i]['id']);
  7261. }
  7262. }
  7263. }
  7264. if ($action != 'move') {
  7265. $arrHide = [];
  7266. for ($i = 0; $i < count($arrLP); $i++) {
  7267. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7268. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7269. }
  7270. }
  7271. }
  7272. if ('edit' === $action) {
  7273. $extraField = new ExtraField('lp_item');
  7274. $extraField->addElements($form, $id);
  7275. }
  7276. if ($action == 'add') {
  7277. $form->addButtonSave(get_lang('AddExercise'), 'submit_button');
  7278. } else {
  7279. $form->addButtonSave(get_lang('EditCurrentExecice'), 'submit_button');
  7280. }
  7281. if ($action == 'move') {
  7282. $form->addHidden('title', $item_title);
  7283. $form->addHidden('description', $item_description);
  7284. }
  7285. if (is_numeric($extra_info)) {
  7286. $form->addHidden('path', $extra_info);
  7287. } elseif (is_array($extra_info)) {
  7288. $form->addHidden('path', $extra_info['path']);
  7289. }
  7290. $form->addHidden('type', TOOL_QUIZ);
  7291. $form->addHidden('post_time', time());
  7292. $form->setDefaults($defaults);
  7293. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  7294. }
  7295. /**
  7296. * Addition of Hotpotatoes tests.
  7297. *
  7298. * @param string $action
  7299. * @param int $id Internal ID of the item
  7300. * @param string $extra_info
  7301. *
  7302. * @return string HTML structure to display the hotpotatoes addition formular
  7303. */
  7304. public function display_hotpotatoes_form($action = 'add', $id = 0, $extra_info = '')
  7305. {
  7306. $course_id = api_get_course_int_id();
  7307. $uploadPath = DIR_HOTPOTATOES; //defined in main_api
  7308. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7309. if ($id != 0 && is_array($extra_info)) {
  7310. $item_title = stripslashes($extra_info['title']);
  7311. $item_description = stripslashes($extra_info['description']);
  7312. } elseif (is_numeric($extra_info)) {
  7313. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  7314. $sql = "SELECT * FROM ".$TBL_DOCUMENT."
  7315. WHERE
  7316. c_id = ".$course_id." AND
  7317. path LIKE '".$uploadPath."/%/%htm%' AND
  7318. iid = ".(int) $extra_info."
  7319. ORDER BY iid ASC";
  7320. $res_hot = Database::query($sql);
  7321. $row = Database::fetch_array($res_hot);
  7322. $item_title = $row['title'];
  7323. $item_description = $row['description'];
  7324. if (!empty($row['comment'])) {
  7325. $item_title = $row['comment'];
  7326. }
  7327. } else {
  7328. $item_title = '';
  7329. $item_description = '';
  7330. }
  7331. if ($id != 0 && is_array($extra_info)) {
  7332. $parent = $extra_info['parent_item_id'];
  7333. } else {
  7334. $parent = 0;
  7335. }
  7336. $sql = "SELECT * FROM $tbl_lp_item
  7337. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  7338. $result = Database::query($sql);
  7339. $arrLP = [];
  7340. while ($row = Database::fetch_array($result)) {
  7341. $arrLP[] = [
  7342. 'id' => $row['id'],
  7343. 'item_type' => $row['item_type'],
  7344. 'title' => $row['title'],
  7345. 'path' => $row['path'],
  7346. 'description' => $row['description'],
  7347. 'parent_item_id' => $row['parent_item_id'],
  7348. 'previous_item_id' => $row['previous_item_id'],
  7349. 'next_item_id' => $row['next_item_id'],
  7350. 'display_order' => $row['display_order'],
  7351. 'max_score' => $row['max_score'],
  7352. 'min_score' => $row['min_score'],
  7353. 'mastery_score' => $row['mastery_score'],
  7354. 'prerequisite' => $row['prerequisite'],
  7355. 'max_time_allowed' => $row['max_time_allowed'],
  7356. ];
  7357. }
  7358. $legend = '<legend>';
  7359. if ($action == 'add') {
  7360. $legend .= get_lang('CreateTheExercise');
  7361. } elseif ($action == 'move') {
  7362. $legend .= get_lang('MoveTheCurrentExercise');
  7363. } else {
  7364. $legend .= get_lang('EditCurrentExecice');
  7365. }
  7366. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  7367. $legend .= Display:: return_message(
  7368. get_lang('Warning').' ! '.get_lang('WarningEditingDocument')
  7369. );
  7370. }
  7371. $legend .= '</legend>';
  7372. $return = '<form method="POST">';
  7373. $return .= $legend;
  7374. $return .= '<table cellpadding="0" cellspacing="0" class="lp_form">';
  7375. $return .= '<tr>';
  7376. $return .= '<td class="label"><label for="idParent">'.get_lang('Parent').' :</label></td>';
  7377. $return .= '<td class="input">';
  7378. $return .= '<select id="idParent" name="parent" onChange="javascript: load_cbo(this.value);" size="1">';
  7379. $return .= '<option class="top" value="0">'.$this->name.'</option>';
  7380. $arrHide = [
  7381. $id,
  7382. ];
  7383. if (count($arrLP) > 0) {
  7384. for ($i = 0; $i < count($arrLP); $i++) {
  7385. if ($action != 'add') {
  7386. if ($arrLP[$i]['item_type'] == 'dir' &&
  7387. !in_array($arrLP[$i]['id'], $arrHide) &&
  7388. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7389. ) {
  7390. $return .= '<option '.(($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '').'style="padding-left:'.($arrLP[$i]['depth'] * 10).'px;" value="'.$arrLP[$i]['id'].'">'.$arrLP[$i]['title'].'</option>';
  7391. } else {
  7392. $arrHide[] = $arrLP[$i]['id'];
  7393. }
  7394. } else {
  7395. if ($arrLP[$i]['item_type'] == 'dir') {
  7396. $return .= '<option '.(($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '').'style="padding-left:'.($arrLP[$i]['depth'] * 10).'px;" value="'.$arrLP[$i]['id'].'">'.$arrLP[$i]['title'].'</option>';
  7397. }
  7398. }
  7399. }
  7400. reset($arrLP);
  7401. }
  7402. $return .= '</select>';
  7403. $return .= '</td>';
  7404. $return .= '</tr>';
  7405. $return .= '<tr>';
  7406. $return .= '<td class="label"><label for="previous">'.get_lang('Position').' :</label></td>';
  7407. $return .= '<td class="input">';
  7408. $return .= '<select id="previous" name="previous" size="1">';
  7409. $return .= '<option class="top" value="0">'.get_lang('FirstPosition').'</option>';
  7410. for ($i = 0; $i < count($arrLP); $i++) {
  7411. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  7412. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7413. $selected = 'selected="selected" ';
  7414. } elseif ($action == 'add') {
  7415. $selected = 'selected="selected" ';
  7416. } else {
  7417. $selected = '';
  7418. }
  7419. $return .= '<option '.$selected.'value="'.$arrLP[$i]['id'].'">'.get_lang('After').' "'.$arrLP[$i]['title'].'"</option>';
  7420. }
  7421. }
  7422. $return .= '</select>';
  7423. $return .= '</td>';
  7424. $return .= '</tr>';
  7425. if ($action != 'move') {
  7426. $return .= '<tr>';
  7427. $return .= '<td class="label"><label for="idTitle">'.get_lang('Title').' :</label></td>';
  7428. $return .= '<td class="input"><input id="idTitle" name="title" type="text" value="'.$item_title.'" /></td>';
  7429. $return .= '</tr>';
  7430. $id_prerequisite = 0;
  7431. if (is_array($arrLP) && count($arrLP) > 0) {
  7432. foreach ($arrLP as $key => $value) {
  7433. if ($value['id'] == $id) {
  7434. $id_prerequisite = $value['prerequisite'];
  7435. break;
  7436. }
  7437. }
  7438. $arrHide = [];
  7439. for ($i = 0; $i < count($arrLP); $i++) {
  7440. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7441. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7442. }
  7443. }
  7444. }
  7445. }
  7446. $return .= '<tr>';
  7447. $return .= '<td>&nbsp; </td><td><button class="save" name="submit_button" action="edit" type="submit">'.
  7448. get_lang('SaveHotpotatoes').'</button></td>';
  7449. $return .= '</tr>';
  7450. $return .= '</table>';
  7451. if ($action == 'move') {
  7452. $return .= '<input name="title" type="hidden" value="'.$item_title.'" />';
  7453. $return .= '<input name="description" type="hidden" value="'.$item_description.'" />';
  7454. }
  7455. if (is_numeric($extra_info)) {
  7456. $return .= '<input name="path" type="hidden" value="'.$extra_info.'" />';
  7457. } elseif (is_array($extra_info)) {
  7458. $return .= '<input name="path" type="hidden" value="'.$extra_info['path'].'" />';
  7459. }
  7460. $return .= '<input name="type" type="hidden" value="'.TOOL_HOTPOTATOES.'" />';
  7461. $return .= '<input name="post_time" type="hidden" value="'.time().'" />';
  7462. $return .= '</form>';
  7463. return $return;
  7464. }
  7465. /**
  7466. * Return the form to display the forum edit/add option.
  7467. *
  7468. * @param string $action
  7469. * @param int $id ID of the lp_item if already exists
  7470. * @param string $extra_info
  7471. *
  7472. * @throws Exception
  7473. *
  7474. * @return string HTML form
  7475. */
  7476. public function display_forum_form($action = 'add', $id = 0, $extra_info = '')
  7477. {
  7478. $course_id = api_get_course_int_id();
  7479. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7480. $tbl_forum = Database::get_course_table(TABLE_FORUM);
  7481. if ($id != 0 && is_array($extra_info)) {
  7482. $item_title = stripslashes($extra_info['title']);
  7483. } elseif (is_numeric($extra_info)) {
  7484. $sql = "SELECT forum_title as title, forum_comment as comment
  7485. FROM $tbl_forum
  7486. WHERE c_id = $course_id AND forum_id = ".$extra_info;
  7487. $result = Database::query($sql);
  7488. $row = Database::fetch_array($result);
  7489. $item_title = $row['title'];
  7490. $item_description = $row['comment'];
  7491. } else {
  7492. $item_title = '';
  7493. $item_description = '';
  7494. }
  7495. if ($id != 0 && is_array($extra_info)) {
  7496. $parent = $extra_info['parent_item_id'];
  7497. } else {
  7498. $parent = 0;
  7499. }
  7500. $sql = "SELECT * FROM $tbl_lp_item
  7501. WHERE
  7502. c_id = $course_id AND
  7503. lp_id = ".$this->lp_id;
  7504. $result = Database::query($sql);
  7505. $arrLP = [];
  7506. while ($row = Database::fetch_array($result)) {
  7507. $arrLP[] = [
  7508. 'id' => $row['iid'],
  7509. 'item_type' => $row['item_type'],
  7510. 'title' => $row['title'],
  7511. 'path' => $row['path'],
  7512. 'description' => $row['description'],
  7513. 'parent_item_id' => $row['parent_item_id'],
  7514. 'previous_item_id' => $row['previous_item_id'],
  7515. 'next_item_id' => $row['next_item_id'],
  7516. 'display_order' => $row['display_order'],
  7517. 'max_score' => $row['max_score'],
  7518. 'min_score' => $row['min_score'],
  7519. 'mastery_score' => $row['mastery_score'],
  7520. 'prerequisite' => $row['prerequisite'],
  7521. ];
  7522. }
  7523. $this->tree_array($arrLP);
  7524. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7525. unset($this->arrMenu);
  7526. if ($action == 'add') {
  7527. $legend = get_lang('CreateTheForum');
  7528. } elseif ($action == 'move') {
  7529. $legend = get_lang('MoveTheCurrentForum');
  7530. } else {
  7531. $legend = get_lang('EditCurrentForum');
  7532. }
  7533. $form = new FormValidator(
  7534. 'forum_form',
  7535. 'POST',
  7536. $this->getCurrentBuildingModeURL()
  7537. );
  7538. $defaults = [];
  7539. $form->addHeader($legend);
  7540. if ($action != 'move') {
  7541. $form->addText(
  7542. 'title',
  7543. get_lang('Title'),
  7544. true,
  7545. ['id' => 'idTitle', 'class' => 'learnpath_item_form']
  7546. );
  7547. $defaults['title'] = $item_title;
  7548. }
  7549. $selectParent = $form->addSelect(
  7550. 'parent',
  7551. get_lang('Parent'),
  7552. [],
  7553. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);', 'class' => 'learnpath_item_form']
  7554. );
  7555. $selectParent->addOption($this->name, 0);
  7556. $arrHide = [
  7557. $id,
  7558. ];
  7559. for ($i = 0; $i < count($arrLP); $i++) {
  7560. if ($action != 'add') {
  7561. if ($arrLP[$i]['item_type'] == 'dir' &&
  7562. !in_array($arrLP[$i]['id'], $arrHide) &&
  7563. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7564. ) {
  7565. $selectParent->addOption(
  7566. $arrLP[$i]['title'],
  7567. $arrLP[$i]['id'],
  7568. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7569. );
  7570. if ($parent == $arrLP[$i]['id']) {
  7571. $selectParent->setSelected($arrLP[$i]['id']);
  7572. }
  7573. } else {
  7574. $arrHide[] = $arrLP[$i]['id'];
  7575. }
  7576. } else {
  7577. if ($arrLP[$i]['item_type'] == 'dir') {
  7578. $selectParent->addOption(
  7579. $arrLP[$i]['title'],
  7580. $arrLP[$i]['id'],
  7581. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7582. );
  7583. if ($parent == $arrLP[$i]['id']) {
  7584. $selectParent->setSelected($arrLP[$i]['id']);
  7585. }
  7586. }
  7587. }
  7588. }
  7589. if (is_array($arrLP)) {
  7590. reset($arrLP);
  7591. }
  7592. $selectPrevious = $form->addSelect(
  7593. 'previous',
  7594. get_lang('Position'),
  7595. [],
  7596. ['id' => 'previous', 'class' => 'learnpath_item_form']
  7597. );
  7598. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  7599. for ($i = 0; $i < count($arrLP); $i++) {
  7600. if ($arrLP[$i]['parent_item_id'] == $parent &&
  7601. $arrLP[$i]['id'] != $id
  7602. ) {
  7603. $selectPrevious->addOption(
  7604. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  7605. $arrLP[$i]['id']
  7606. );
  7607. if (isset($extra_info['previous_item_id']) &&
  7608. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7609. ) {
  7610. $selectPrevious->setSelected($arrLP[$i]['id']);
  7611. } elseif ($action == 'add') {
  7612. $selectPrevious->setSelected($arrLP[$i]['id']);
  7613. }
  7614. }
  7615. }
  7616. if ($action != 'move') {
  7617. $id_prerequisite = 0;
  7618. if (is_array($arrLP)) {
  7619. foreach ($arrLP as $key => $value) {
  7620. if ($value['id'] == $id) {
  7621. $id_prerequisite = $value['prerequisite'];
  7622. break;
  7623. }
  7624. }
  7625. }
  7626. $arrHide = [];
  7627. for ($i = 0; $i < count($arrLP); $i++) {
  7628. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7629. if (isset($extra_info['previous_item_id']) &&
  7630. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7631. ) {
  7632. $s_selected_position = $arrLP[$i]['id'];
  7633. } elseif ($action == 'add') {
  7634. $s_selected_position = 0;
  7635. }
  7636. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7637. }
  7638. }
  7639. }
  7640. if ('edit' === $action) {
  7641. $extraField = new ExtraField('lp_item');
  7642. $extraField->addElements($form, $id);
  7643. }
  7644. if ($action == 'add') {
  7645. $form->addButtonSave(get_lang('AddForumToCourse'), 'submit_button');
  7646. } else {
  7647. $form->addButtonSave(get_lang('EditCurrentForum'), 'submit_button');
  7648. }
  7649. if ($action == 'move') {
  7650. $form->addHidden('title', $item_title);
  7651. $form->addHidden('description', $item_description);
  7652. }
  7653. if (is_numeric($extra_info)) {
  7654. $form->addHidden('path', $extra_info);
  7655. } elseif (is_array($extra_info)) {
  7656. $form->addHidden('path', $extra_info['path']);
  7657. }
  7658. $form->addHidden('type', TOOL_FORUM);
  7659. $form->addHidden('post_time', time());
  7660. $form->setDefaults($defaults);
  7661. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  7662. }
  7663. /**
  7664. * Return HTML form to add/edit forum threads.
  7665. *
  7666. * @param string $action
  7667. * @param int $id Item ID if already exists in learning path
  7668. * @param string $extra_info
  7669. *
  7670. * @throws Exception
  7671. *
  7672. * @return string HTML form
  7673. */
  7674. public function display_thread_form($action = 'add', $id = 0, $extra_info = '')
  7675. {
  7676. $course_id = api_get_course_int_id();
  7677. if (empty($course_id)) {
  7678. return null;
  7679. }
  7680. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7681. $tbl_forum = Database::get_course_table(TABLE_FORUM_THREAD);
  7682. if ($id != 0 && is_array($extra_info)) {
  7683. $item_title = stripslashes($extra_info['title']);
  7684. } elseif (is_numeric($extra_info)) {
  7685. $sql = "SELECT thread_title as title FROM $tbl_forum
  7686. WHERE c_id = $course_id AND thread_id = ".$extra_info;
  7687. $result = Database::query($sql);
  7688. $row = Database::fetch_array($result);
  7689. $item_title = $row['title'];
  7690. $item_description = '';
  7691. } else {
  7692. $item_title = '';
  7693. $item_description = '';
  7694. }
  7695. if ($id != 0 && is_array($extra_info)) {
  7696. $parent = $extra_info['parent_item_id'];
  7697. } else {
  7698. $parent = 0;
  7699. }
  7700. $sql = "SELECT * FROM $tbl_lp_item
  7701. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  7702. $result = Database::query($sql);
  7703. $arrLP = [];
  7704. while ($row = Database::fetch_array($result)) {
  7705. $arrLP[] = [
  7706. 'id' => $row['iid'],
  7707. 'item_type' => $row['item_type'],
  7708. 'title' => $row['title'],
  7709. 'path' => $row['path'],
  7710. 'description' => $row['description'],
  7711. 'parent_item_id' => $row['parent_item_id'],
  7712. 'previous_item_id' => $row['previous_item_id'],
  7713. 'next_item_id' => $row['next_item_id'],
  7714. 'display_order' => $row['display_order'],
  7715. 'max_score' => $row['max_score'],
  7716. 'min_score' => $row['min_score'],
  7717. 'mastery_score' => $row['mastery_score'],
  7718. 'prerequisite' => $row['prerequisite'],
  7719. ];
  7720. }
  7721. $this->tree_array($arrLP);
  7722. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7723. unset($this->arrMenu);
  7724. $form = new FormValidator(
  7725. 'thread_form',
  7726. 'POST',
  7727. $this->getCurrentBuildingModeURL()
  7728. );
  7729. $defaults = [];
  7730. if ($action == 'add') {
  7731. $legend = get_lang('CreateTheForum');
  7732. } elseif ($action == 'move') {
  7733. $legend = get_lang('MoveTheCurrentForum');
  7734. } else {
  7735. $legend = get_lang('EditCurrentForum');
  7736. }
  7737. $form->addHeader($legend);
  7738. $selectParent = $form->addSelect(
  7739. 'parent',
  7740. get_lang('Parent'),
  7741. [],
  7742. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);']
  7743. );
  7744. $selectParent->addOption($this->name, 0);
  7745. $arrHide = [
  7746. $id,
  7747. ];
  7748. for ($i = 0; $i < count($arrLP); $i++) {
  7749. if ($action != 'add') {
  7750. if (
  7751. ($arrLP[$i]['item_type'] == 'dir') &&
  7752. !in_array($arrLP[$i]['id'], $arrHide) &&
  7753. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7754. ) {
  7755. $selectParent->addOption(
  7756. $arrLP[$i]['title'],
  7757. $arrLP[$i]['id'],
  7758. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7759. );
  7760. if ($parent == $arrLP[$i]['id']) {
  7761. $selectParent->setSelected($arrLP[$i]['id']);
  7762. }
  7763. } else {
  7764. $arrHide[] = $arrLP[$i]['id'];
  7765. }
  7766. } else {
  7767. if ($arrLP[$i]['item_type'] == 'dir') {
  7768. $selectParent->addOption(
  7769. $arrLP[$i]['title'],
  7770. $arrLP[$i]['id'],
  7771. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7772. );
  7773. if ($parent == $arrLP[$i]['id']) {
  7774. $selectParent->setSelected($arrLP[$i]['id']);
  7775. }
  7776. }
  7777. }
  7778. }
  7779. if ($arrLP != null) {
  7780. reset($arrLP);
  7781. }
  7782. $selectPrevious = $form->addSelect(
  7783. 'previous',
  7784. get_lang('Position'),
  7785. [],
  7786. ['id' => 'previous']
  7787. );
  7788. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  7789. for ($i = 0; $i < count($arrLP); $i++) {
  7790. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  7791. $selectPrevious->addOption(
  7792. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  7793. $arrLP[$i]['id']
  7794. );
  7795. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7796. $selectPrevious->setSelected($arrLP[$i]['id']);
  7797. } elseif ($action == 'add') {
  7798. $selectPrevious->setSelected($arrLP[$i]['id']);
  7799. }
  7800. }
  7801. }
  7802. if ($action != 'move') {
  7803. $form->addText(
  7804. 'title',
  7805. get_lang('Title'),
  7806. true,
  7807. ['id' => 'idTitle']
  7808. );
  7809. $defaults['title'] = $item_title;
  7810. $id_prerequisite = 0;
  7811. if ($arrLP != null) {
  7812. foreach ($arrLP as $key => $value) {
  7813. if ($value['id'] == $id) {
  7814. $id_prerequisite = $value['prerequisite'];
  7815. break;
  7816. }
  7817. }
  7818. }
  7819. $arrHide = [];
  7820. $s_selected_position = 0;
  7821. for ($i = 0; $i < count($arrLP); $i++) {
  7822. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7823. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7824. $s_selected_position = $arrLP[$i]['id'];
  7825. } elseif ($action == 'add') {
  7826. $s_selected_position = 0;
  7827. }
  7828. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7829. }
  7830. }
  7831. $selectPrerequisites = $form->addSelect(
  7832. 'prerequisites',
  7833. get_lang('LearnpathPrerequisites'),
  7834. [],
  7835. ['id' => 'prerequisites']
  7836. );
  7837. $selectPrerequisites->addOption(get_lang('NoPrerequisites'), 0);
  7838. foreach ($arrHide as $key => $value) {
  7839. $selectPrerequisites->addOption($value['value'], $key);
  7840. if ($key == $s_selected_position && $action == 'add') {
  7841. $selectPrerequisites->setSelected($key);
  7842. } elseif ($key == $id_prerequisite && $action == 'edit') {
  7843. $selectPrerequisites->setSelected($key);
  7844. }
  7845. }
  7846. }
  7847. if ('edit' === $action) {
  7848. $extraField = new ExtraField('lp_item');
  7849. $extraField->addElements($form, $id);
  7850. }
  7851. $form->addButtonSave(get_lang('Ok'), 'submit_button');
  7852. if ($action == 'move') {
  7853. $form->addHidden('title', $item_title);
  7854. $form->addHidden('description', $item_description);
  7855. }
  7856. if (is_numeric($extra_info)) {
  7857. $form->addHidden('path', $extra_info);
  7858. } elseif (is_array($extra_info)) {
  7859. $form->addHidden('path', $extra_info['path']);
  7860. }
  7861. $form->addHidden('type', TOOL_THREAD);
  7862. $form->addHidden('post_time', time());
  7863. $form->setDefaults($defaults);
  7864. return $form->returnForm();
  7865. }
  7866. /**
  7867. * Return the HTML form to display an item (generally a dir item).
  7868. *
  7869. * @param string $item_type
  7870. * @param string $title
  7871. * @param string $action
  7872. * @param int $id
  7873. * @param string $extra_info
  7874. *
  7875. * @throws Exception
  7876. * @throws HTML_QuickForm_Error
  7877. *
  7878. * @return string HTML form
  7879. */
  7880. public function display_item_form(
  7881. $item_type,
  7882. $title = '',
  7883. $action = 'add_item',
  7884. $id = 0,
  7885. $extra_info = 'new'
  7886. ) {
  7887. $_course = api_get_course_info();
  7888. global $charset;
  7889. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7890. $item_title = '';
  7891. $item_description = '';
  7892. $item_path_fck = '';
  7893. if ($id != 0 && is_array($extra_info)) {
  7894. $item_title = $extra_info['title'];
  7895. $item_description = $extra_info['description'];
  7896. $item_path = api_get_path(WEB_COURSE_PATH).$_course['path'].'/scorm/'.$this->path.'/'.stripslashes($extra_info['path']);
  7897. $item_path_fck = '/scorm/'.$this->path.'/'.stripslashes($extra_info['path']);
  7898. }
  7899. $parent = 0;
  7900. if ($id != 0 && is_array($extra_info)) {
  7901. $parent = $extra_info['parent_item_id'];
  7902. }
  7903. $id = (int) $id;
  7904. $sql = "SELECT * FROM $tbl_lp_item
  7905. WHERE
  7906. lp_id = ".$this->lp_id." AND
  7907. iid != $id";
  7908. if ($item_type == 'dir') {
  7909. $sql .= " AND parent_item_id = 0";
  7910. }
  7911. $result = Database::query($sql);
  7912. $arrLP = [];
  7913. while ($row = Database::fetch_array($result)) {
  7914. $arrLP[] = [
  7915. 'id' => $row['iid'],
  7916. 'item_type' => $row['item_type'],
  7917. 'title' => $row['title'],
  7918. 'path' => $row['path'],
  7919. 'description' => $row['description'],
  7920. 'parent_item_id' => $row['parent_item_id'],
  7921. 'previous_item_id' => $row['previous_item_id'],
  7922. 'next_item_id' => $row['next_item_id'],
  7923. 'max_score' => $row['max_score'],
  7924. 'min_score' => $row['min_score'],
  7925. 'mastery_score' => $row['mastery_score'],
  7926. 'prerequisite' => $row['prerequisite'],
  7927. 'display_order' => $row['display_order'],
  7928. ];
  7929. }
  7930. $this->tree_array($arrLP);
  7931. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7932. unset($this->arrMenu);
  7933. $url = api_get_self().'?'.api_get_cidreq().'&action='.$action.'&type='.$item_type.'&lp_id='.$this->lp_id;
  7934. $form = new FormValidator('form', 'POST', $url);
  7935. $defaults['title'] = api_html_entity_decode(
  7936. $item_title,
  7937. ENT_QUOTES,
  7938. $charset
  7939. );
  7940. $defaults['description'] = $item_description;
  7941. $form->addHeader($title);
  7942. $arrHide[0]['value'] = Security::remove_XSS($this->name);
  7943. $arrHide[0]['padding'] = 20;
  7944. $charset = api_get_system_encoding();
  7945. for ($i = 0; $i < count($arrLP); $i++) {
  7946. if ($action != 'add') {
  7947. if ($arrLP[$i]['item_type'] == 'dir' && !in_array($arrLP[$i]['id'], $arrHide) &&
  7948. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7949. ) {
  7950. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7951. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7952. if ($parent == $arrLP[$i]['id']) {
  7953. $s_selected_parent = $arrHide[$arrLP[$i]['id']];
  7954. }
  7955. }
  7956. } else {
  7957. if ($arrLP[$i]['item_type'] == 'dir') {
  7958. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7959. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7960. if ($parent == $arrLP[$i]['id']) {
  7961. $s_selected_parent = $arrHide[$arrLP[$i]['id']];
  7962. }
  7963. }
  7964. }
  7965. }
  7966. if ($action != 'move') {
  7967. $form->addElement('text', 'title', get_lang('Title'));
  7968. $form->applyFilter('title', 'html_filter');
  7969. $form->addRule('title', get_lang('ThisFieldIsRequired'), 'required');
  7970. } else {
  7971. $form->addElement('hidden', 'title');
  7972. }
  7973. $parentSelect = $form->addElement(
  7974. 'select',
  7975. 'parent',
  7976. get_lang('Parent'),
  7977. '',
  7978. [
  7979. 'id' => 'idParent',
  7980. 'onchange' => "javascript: load_cbo(this.value);",
  7981. ]
  7982. );
  7983. foreach ($arrHide as $key => $value) {
  7984. $parentSelect->addOption(
  7985. $value['value'],
  7986. $key,
  7987. 'style="padding-left:'.$value['padding'].'px;"'
  7988. );
  7989. $lastPosition = $key;
  7990. }
  7991. if (!empty($s_selected_parent)) {
  7992. $parentSelect->setSelected($s_selected_parent);
  7993. }
  7994. if (is_array($arrLP)) {
  7995. reset($arrLP);
  7996. }
  7997. $arrHide = [];
  7998. // POSITION
  7999. for ($i = 0; $i < count($arrLP); $i++) {
  8000. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id &&
  8001. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM) {
  8002. //this is the same!
  8003. if (isset($extra_info['previous_item_id']) &&
  8004. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  8005. ) {
  8006. $s_selected_position = $arrLP[$i]['id'];
  8007. } elseif ($action == 'add') {
  8008. $s_selected_position = $arrLP[$i]['id'];
  8009. }
  8010. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  8011. }
  8012. }
  8013. $position = $form->addElement(
  8014. 'select',
  8015. 'previous',
  8016. get_lang('Position'),
  8017. '',
  8018. ['id' => 'previous']
  8019. );
  8020. $padding = isset($value['padding']) ? $value['padding'] : 0;
  8021. $position->addOption(get_lang('FirstPosition'), 0, 'style="padding-left:'.$padding.'px;"');
  8022. $lastPosition = null;
  8023. foreach ($arrHide as $key => $value) {
  8024. $position->addOption($value['value'], $key, 'style="padding-left:'.$padding.'px;"');
  8025. $lastPosition = $key;
  8026. }
  8027. if (!empty($s_selected_position)) {
  8028. $position->setSelected($s_selected_position);
  8029. }
  8030. // When new chapter add at the end
  8031. if ($action == 'add_item') {
  8032. $position->setSelected($lastPosition);
  8033. }
  8034. if (is_array($arrLP)) {
  8035. reset($arrLP);
  8036. }
  8037. $form->addButtonSave(get_lang('SaveSection'), 'submit_button');
  8038. //fix in order to use the tab
  8039. if ($item_type == 'dir') {
  8040. $form->addElement('hidden', 'type', 'dir');
  8041. }
  8042. $extension = null;
  8043. if (!empty($item_path)) {
  8044. $extension = pathinfo($item_path, PATHINFO_EXTENSION);
  8045. }
  8046. //assets can't be modified
  8047. //$item_type == 'asset' ||
  8048. if (($item_type == 'sco') && ($extension == 'html' || $extension == 'htm')) {
  8049. if ($item_type == 'sco') {
  8050. $form->addElement(
  8051. 'html',
  8052. '<script>alert("'.get_lang('WarningWhenEditingScorm').'")</script>'
  8053. );
  8054. }
  8055. $renderer = $form->defaultRenderer();
  8056. $renderer->setElementTemplate(
  8057. '<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{label}<br />{element}',
  8058. 'content_lp'
  8059. );
  8060. $relative_prefix = '';
  8061. $editor_config = [
  8062. 'ToolbarSet' => 'LearningPathDocuments',
  8063. 'Width' => '100%',
  8064. 'Height' => '500',
  8065. 'FullPage' => true,
  8066. 'CreateDocumentDir' => $relative_prefix,
  8067. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/scorm/',
  8068. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().$item_path_fck,
  8069. ];
  8070. $form->addElement('html_editor', 'content_lp', '', null, $editor_config);
  8071. $content_path = api_get_path(SYS_COURSE_PATH).api_get_course_path().$item_path_fck;
  8072. $defaults['content_lp'] = file_get_contents($content_path);
  8073. }
  8074. if (!empty($id)) {
  8075. $form->addHidden('id', $id);
  8076. }
  8077. $form->addElement('hidden', 'type', $item_type);
  8078. $form->addElement('hidden', 'post_time', time());
  8079. $form->setDefaults($defaults);
  8080. return $form->returnForm();
  8081. }
  8082. /**
  8083. * @return string
  8084. */
  8085. public function getCurrentBuildingModeURL()
  8086. {
  8087. $pathItem = isset($_GET['path_item']) ? (int) $_GET['path_item'] : '';
  8088. $action = isset($_GET['action']) ? Security::remove_XSS($_GET['action']) : '';
  8089. $id = isset($_GET['id']) ? (int) $_GET['id'] : '';
  8090. $view = isset($_GET['view']) ? Security::remove_XSS($_GET['view']) : '';
  8091. $currentUrl = api_get_self().'?'.api_get_cidreq().
  8092. '&action='.$action.'&lp_id='.$this->lp_id.'&path_item='.$pathItem.'&view='.$view.'&id='.$id;
  8093. return $currentUrl;
  8094. }
  8095. /**
  8096. * Returns the form to update or create a document.
  8097. *
  8098. * @param string $action (add/edit)
  8099. * @param int $id ID of the lp_item (if already exists)
  8100. * @param mixed $extra_info Integer if document ID, string if info ('new')
  8101. *
  8102. * @throws Exception
  8103. * @throws HTML_QuickForm_Error
  8104. *
  8105. * @return string HTML form
  8106. */
  8107. public function display_document_form($action = 'add', $id = 0, $extra_info = 'new')
  8108. {
  8109. $course_id = api_get_course_int_id();
  8110. $_course = api_get_course_info();
  8111. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8112. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  8113. $no_display_edit_textarea = false;
  8114. $item_description = '';
  8115. //If action==edit document
  8116. //We don't display the document form if it's not an editable document (html or txt file)
  8117. if ($action === 'edit') {
  8118. if (is_array($extra_info)) {
  8119. $path_parts = pathinfo($extra_info['dir']);
  8120. if ($path_parts['extension'] != 'txt' && $path_parts['extension'] != 'html') {
  8121. $no_display_edit_textarea = true;
  8122. }
  8123. }
  8124. }
  8125. $no_display_add = false;
  8126. // If action==add an existing document
  8127. // We don't display the document form if it's not an editable document (html or txt file).
  8128. if ($action === 'add') {
  8129. if (is_numeric($extra_info)) {
  8130. $extra_info = (int) $extra_info;
  8131. $sql_doc = "SELECT path FROM $tbl_doc
  8132. WHERE c_id = $course_id AND iid = ".$extra_info;
  8133. $result = Database::query($sql_doc);
  8134. $path_file = Database::result($result, 0, 0);
  8135. $path_parts = pathinfo($path_file);
  8136. if ($path_parts['extension'] != 'txt' && $path_parts['extension'] != 'html') {
  8137. $no_display_add = true;
  8138. }
  8139. }
  8140. }
  8141. if ($id != 0 && is_array($extra_info)) {
  8142. $item_title = stripslashes($extra_info['title']);
  8143. $item_description = stripslashes($extra_info['description']);
  8144. if (empty($item_title)) {
  8145. $path_parts = pathinfo($extra_info['path']);
  8146. $item_title = stripslashes($path_parts['filename']);
  8147. }
  8148. } elseif (is_numeric($extra_info)) {
  8149. $sql = "SELECT path, title FROM $tbl_doc
  8150. WHERE
  8151. c_id = ".$course_id." AND
  8152. iid = ".intval($extra_info);
  8153. $result = Database::query($sql);
  8154. $row = Database::fetch_array($result);
  8155. $item_title = $row['title'];
  8156. $item_title = str_replace('_', ' ', $item_title);
  8157. if (empty($item_title)) {
  8158. $path_parts = pathinfo($row['path']);
  8159. $item_title = stripslashes($path_parts['filename']);
  8160. }
  8161. } else {
  8162. $item_title = '';
  8163. $item_description = '';
  8164. }
  8165. $return = '<legend>';
  8166. $parent = 0;
  8167. if ($id != 0 && is_array($extra_info)) {
  8168. $parent = $extra_info['parent_item_id'];
  8169. }
  8170. $sql = "SELECT * FROM $tbl_lp_item
  8171. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8172. $result = Database::query($sql);
  8173. $arrLP = [];
  8174. while ($row = Database::fetch_array($result)) {
  8175. $arrLP[] = [
  8176. 'id' => $row['iid'],
  8177. 'item_type' => $row['item_type'],
  8178. 'title' => $row['title'],
  8179. 'path' => $row['path'],
  8180. 'description' => $row['description'],
  8181. 'parent_item_id' => $row['parent_item_id'],
  8182. 'previous_item_id' => $row['previous_item_id'],
  8183. 'next_item_id' => $row['next_item_id'],
  8184. 'display_order' => $row['display_order'],
  8185. 'max_score' => $row['max_score'],
  8186. 'min_score' => $row['min_score'],
  8187. 'mastery_score' => $row['mastery_score'],
  8188. 'prerequisite' => $row['prerequisite'],
  8189. ];
  8190. }
  8191. $this->tree_array($arrLP);
  8192. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  8193. unset($this->arrMenu);
  8194. if ($action == 'add') {
  8195. $return .= get_lang('CreateTheDocument');
  8196. } elseif ($action == 'move') {
  8197. $return .= get_lang('MoveTheCurrentDocument');
  8198. } else {
  8199. $return .= get_lang('EditTheCurrentDocument');
  8200. }
  8201. $return .= '</legend>';
  8202. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  8203. $return .= Display::return_message(
  8204. '<strong>'.get_lang('Warning').' !</strong><br />'.get_lang('WarningEditingDocument'),
  8205. false
  8206. );
  8207. }
  8208. $form = new FormValidator(
  8209. 'form',
  8210. 'POST',
  8211. $this->getCurrentBuildingModeURL(),
  8212. '',
  8213. ['enctype' => 'multipart/form-data']
  8214. );
  8215. $defaults['title'] = Security::remove_XSS($item_title);
  8216. if (empty($item_title)) {
  8217. $defaults['title'] = Security::remove_XSS($item_title);
  8218. }
  8219. $defaults['description'] = $item_description;
  8220. $form->addElement('html', $return);
  8221. if ($action != 'move') {
  8222. $data = $this->generate_lp_folder($_course);
  8223. if ($action != 'edit') {
  8224. $folders = DocumentManager::get_all_document_folders(
  8225. $_course,
  8226. 0,
  8227. true
  8228. );
  8229. DocumentManager::build_directory_selector(
  8230. $folders,
  8231. '',
  8232. [],
  8233. true,
  8234. $form,
  8235. 'directory_parent_id'
  8236. );
  8237. }
  8238. if (isset($data['id'])) {
  8239. $defaults['directory_parent_id'] = $data['id'];
  8240. }
  8241. $form->addElement(
  8242. 'text',
  8243. 'title',
  8244. get_lang('Title'),
  8245. ['id' => 'idTitle', 'class' => 'col-md-4']
  8246. );
  8247. $form->applyFilter('title', 'html_filter');
  8248. }
  8249. $arrHide[0]['value'] = $this->name;
  8250. $arrHide[0]['padding'] = 20;
  8251. for ($i = 0; $i < count($arrLP); $i++) {
  8252. if ($action != 'add') {
  8253. if ($arrLP[$i]['item_type'] == 'dir' &&
  8254. !in_array($arrLP[$i]['id'], $arrHide) &&
  8255. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8256. ) {
  8257. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8258. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  8259. }
  8260. } else {
  8261. if ($arrLP[$i]['item_type'] == 'dir') {
  8262. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8263. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  8264. }
  8265. }
  8266. }
  8267. $parentSelect = $form->addSelect(
  8268. 'parent',
  8269. get_lang('Parent'),
  8270. [],
  8271. [
  8272. 'id' => 'idParent',
  8273. 'onchange' => 'javascript: load_cbo(this.value);',
  8274. ]
  8275. );
  8276. $my_count = 0;
  8277. foreach ($arrHide as $key => $value) {
  8278. if ($my_count != 0) {
  8279. // The LP name is also the first section and is not in the same charset like the other sections.
  8280. $value['value'] = Security::remove_XSS($value['value']);
  8281. $parentSelect->addOption(
  8282. $value['value'],
  8283. $key,
  8284. 'style="padding-left:'.$value['padding'].'px;"'
  8285. );
  8286. } else {
  8287. $value['value'] = Security::remove_XSS($value['value']);
  8288. $parentSelect->addOption(
  8289. $value['value'],
  8290. $key,
  8291. 'style="padding-left:'.$value['padding'].'px;"'
  8292. );
  8293. }
  8294. $my_count++;
  8295. }
  8296. if (!empty($id)) {
  8297. $parentSelect->setSelected($parent);
  8298. } else {
  8299. $parent_item_id = Session::read('parent_item_id', 0);
  8300. $parentSelect->setSelected($parent_item_id);
  8301. }
  8302. if (is_array($arrLP)) {
  8303. reset($arrLP);
  8304. }
  8305. $arrHide = [];
  8306. // POSITION
  8307. for ($i = 0; $i < count($arrLP); $i++) {
  8308. if (($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) ||
  8309. $arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM
  8310. ) {
  8311. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  8312. }
  8313. }
  8314. $selectedPosition = isset($extra_info['previous_item_id']) ? $extra_info['previous_item_id'] : 0;
  8315. $position = $form->addSelect(
  8316. 'previous',
  8317. get_lang('Position'),
  8318. [],
  8319. ['id' => 'previous']
  8320. );
  8321. $position->addOption(get_lang('FirstPosition'), 0);
  8322. foreach ($arrHide as $key => $value) {
  8323. $padding = isset($value['padding']) ? $value['padding'] : 20;
  8324. $position->addOption(
  8325. $value['value'],
  8326. $key,
  8327. 'style="padding-left:'.$padding.'px;"'
  8328. );
  8329. }
  8330. $position->setSelected($selectedPosition);
  8331. if (is_array($arrLP)) {
  8332. reset($arrLP);
  8333. }
  8334. if ('edit' === $action) {
  8335. $extraField = new ExtraField('lp_item');
  8336. $extraField->addElements($form, $id);
  8337. }
  8338. if ($action != 'move') {
  8339. $arrHide = [];
  8340. for ($i = 0; $i < count($arrLP); $i++) {
  8341. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir' &&
  8342. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM
  8343. ) {
  8344. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8345. }
  8346. }
  8347. if (!$no_display_add) {
  8348. $item_type = isset($extra_info['item_type']) ? $extra_info['item_type'] : null;
  8349. $edit = isset($_GET['edit']) ? $_GET['edit'] : null;
  8350. if ($extra_info == 'new' || $item_type == TOOL_DOCUMENT ||
  8351. $item_type == TOOL_LP_FINAL_ITEM || $edit == 'true'
  8352. ) {
  8353. if (isset($_POST['content'])) {
  8354. $content = stripslashes($_POST['content']);
  8355. } elseif (is_array($extra_info)) {
  8356. //If it's an html document or a text file
  8357. if (!$no_display_edit_textarea) {
  8358. $content = $this->display_document(
  8359. $extra_info['path'],
  8360. false,
  8361. false
  8362. );
  8363. }
  8364. } elseif (is_numeric($extra_info)) {
  8365. $content = $this->display_document(
  8366. $extra_info,
  8367. false,
  8368. false
  8369. );
  8370. } else {
  8371. $content = '';
  8372. }
  8373. if (!$no_display_edit_textarea) {
  8374. // We need to calculate here some specific settings for the online editor.
  8375. // The calculated settings work for documents in the Documents tool
  8376. // (on the root or in subfolders).
  8377. // For documents in native scorm packages it is unclear whether the
  8378. // online editor should be activated or not.
  8379. // A new document, it is in the root of the repository.
  8380. $relative_path = '';
  8381. $relative_prefix = '';
  8382. if (is_array($extra_info) && $extra_info != 'new') {
  8383. // The document already exists. Whe have to determine its relative path towards the repository root.
  8384. $relative_path = explode('/', $extra_info['dir']);
  8385. $cnt = count($relative_path) - 2;
  8386. if ($cnt < 0) {
  8387. $cnt = 0;
  8388. }
  8389. $relative_prefix = str_repeat('../', $cnt);
  8390. $relative_path = array_slice($relative_path, 1, $cnt);
  8391. $relative_path = implode('/', $relative_path);
  8392. if (strlen($relative_path) > 0) {
  8393. $relative_path = $relative_path.'/';
  8394. }
  8395. } else {
  8396. $result = $this->generate_lp_folder($_course);
  8397. $relative_path = api_substr($result['dir'], 1, strlen($result['dir']));
  8398. $relative_prefix = '../../';
  8399. }
  8400. $editor_config = [
  8401. 'ToolbarSet' => 'LearningPathDocuments',
  8402. 'Width' => '100%',
  8403. 'Height' => '500',
  8404. 'FullPage' => true,
  8405. 'CreateDocumentDir' => $relative_prefix,
  8406. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/',
  8407. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/'.$relative_path,
  8408. ];
  8409. if ($_GET['action'] == 'add_item') {
  8410. $class = 'add';
  8411. $text = get_lang('LPCreateDocument');
  8412. } else {
  8413. if ($_GET['action'] == 'edit_item') {
  8414. $class = 'save';
  8415. $text = get_lang('SaveDocument');
  8416. }
  8417. }
  8418. $form->addButtonSave($text, 'submit_button');
  8419. $renderer = $form->defaultRenderer();
  8420. $renderer->setElementTemplate('&nbsp;{label}{element}', 'content_lp');
  8421. $form->addElement('html', '<div class="editor-lp">');
  8422. $form->addHtmlEditor('content_lp', null, null, true, $editor_config, true);
  8423. $form->addElement('html', '</div>');
  8424. $defaults['content_lp'] = $content;
  8425. }
  8426. } elseif (is_numeric($extra_info)) {
  8427. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  8428. $return = $this->display_document($extra_info, true, true, true);
  8429. $form->addElement('html', $return);
  8430. }
  8431. }
  8432. }
  8433. if (isset($extra_info['item_type']) &&
  8434. $extra_info['item_type'] == TOOL_LP_FINAL_ITEM
  8435. ) {
  8436. $parentSelect->freeze();
  8437. $position->freeze();
  8438. }
  8439. if ($action == 'move') {
  8440. $form->addElement('hidden', 'title', $item_title);
  8441. $form->addElement('hidden', 'description', $item_description);
  8442. }
  8443. if (is_numeric($extra_info)) {
  8444. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  8445. $form->addElement('hidden', 'path', $extra_info);
  8446. } elseif (is_array($extra_info)) {
  8447. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  8448. $form->addElement('hidden', 'path', $extra_info['path']);
  8449. }
  8450. $form->addElement('hidden', 'type', TOOL_DOCUMENT);
  8451. $form->addElement('hidden', 'post_time', time());
  8452. $form->setDefaults($defaults);
  8453. return $form->returnForm();
  8454. }
  8455. /**
  8456. * Returns the form to update or create a read-out text.
  8457. *
  8458. * @param string $action "add" or "edit"
  8459. * @param int $id ID of the lp_item (if already exists)
  8460. * @param mixed $extra_info Integer if document ID, string if info ('new')
  8461. *
  8462. * @throws Exception
  8463. * @throws HTML_QuickForm_Error
  8464. *
  8465. * @return string HTML form
  8466. */
  8467. public function displayFrmReadOutText($action = 'add', $id = 0, $extra_info = 'new')
  8468. {
  8469. $course_id = api_get_course_int_id();
  8470. $_course = api_get_course_info();
  8471. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8472. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  8473. $no_display_edit_textarea = false;
  8474. $item_description = '';
  8475. //If action==edit document
  8476. //We don't display the document form if it's not an editable document (html or txt file)
  8477. if ($action == 'edit') {
  8478. if (is_array($extra_info)) {
  8479. $path_parts = pathinfo($extra_info['dir']);
  8480. if ($path_parts['extension'] != "txt" && $path_parts['extension'] != "html") {
  8481. $no_display_edit_textarea = true;
  8482. }
  8483. }
  8484. }
  8485. $no_display_add = false;
  8486. if ($id != 0 && is_array($extra_info)) {
  8487. $item_title = stripslashes($extra_info['title']);
  8488. $item_description = stripslashes($extra_info['description']);
  8489. $item_terms = stripslashes($extra_info['terms']);
  8490. if (empty($item_title)) {
  8491. $path_parts = pathinfo($extra_info['path']);
  8492. $item_title = stripslashes($path_parts['filename']);
  8493. }
  8494. } elseif (is_numeric($extra_info)) {
  8495. $sql = "SELECT path, title FROM $tbl_doc WHERE c_id = ".$course_id." AND iid = ".intval($extra_info);
  8496. $result = Database::query($sql);
  8497. $row = Database::fetch_array($result);
  8498. $item_title = $row['title'];
  8499. $item_title = str_replace('_', ' ', $item_title);
  8500. if (empty($item_title)) {
  8501. $path_parts = pathinfo($row['path']);
  8502. $item_title = stripslashes($path_parts['filename']);
  8503. }
  8504. } else {
  8505. $item_title = '';
  8506. $item_description = '';
  8507. }
  8508. if ($id != 0 && is_array($extra_info)) {
  8509. $parent = $extra_info['parent_item_id'];
  8510. } else {
  8511. $parent = 0;
  8512. }
  8513. $sql = "SELECT * FROM $tbl_lp_item WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8514. $result = Database::query($sql);
  8515. $arrLP = [];
  8516. while ($row = Database::fetch_array($result)) {
  8517. $arrLP[] = [
  8518. 'id' => $row['iid'],
  8519. 'item_type' => $row['item_type'],
  8520. 'title' => $row['title'],
  8521. 'path' => $row['path'],
  8522. 'description' => $row['description'],
  8523. 'parent_item_id' => $row['parent_item_id'],
  8524. 'previous_item_id' => $row['previous_item_id'],
  8525. 'next_item_id' => $row['next_item_id'],
  8526. 'display_order' => $row['display_order'],
  8527. 'max_score' => $row['max_score'],
  8528. 'min_score' => $row['min_score'],
  8529. 'mastery_score' => $row['mastery_score'],
  8530. 'prerequisite' => $row['prerequisite'],
  8531. ];
  8532. }
  8533. $this->tree_array($arrLP);
  8534. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  8535. unset($this->arrMenu);
  8536. if ($action == 'add') {
  8537. $formHeader = get_lang('CreateTheDocument');
  8538. } else {
  8539. $formHeader = get_lang('EditTheCurrentDocument');
  8540. }
  8541. if ('edit' === $action) {
  8542. $urlAudioIcon = Display::url(
  8543. Display::return_icon('audio.png', get_lang('CreateReadOutText'), [], ICON_SIZE_TINY),
  8544. api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq().'&lp_id='.$this->lp_id.'&'
  8545. .http_build_query(['view' => 'build', 'id' => $id, 'action' => 'add_audio'])
  8546. );
  8547. } else {
  8548. $urlAudioIcon = Display::return_icon('audio.png', get_lang('CreateReadOutText'), [], ICON_SIZE_TINY);
  8549. }
  8550. $form = new FormValidator(
  8551. 'frm_add_reading',
  8552. 'POST',
  8553. $this->getCurrentBuildingModeURL(),
  8554. '',
  8555. ['enctype' => 'multipart/form-data']
  8556. );
  8557. $form->addHeader($formHeader);
  8558. $form->addHtml(
  8559. Display::return_message(
  8560. sprintf(get_lang('FrmReadOutTextIntro'), $urlAudioIcon),
  8561. 'normal',
  8562. false
  8563. )
  8564. );
  8565. $defaults['title'] = !empty($item_title) ? Security::remove_XSS($item_title) : '';
  8566. $defaults['description'] = $item_description;
  8567. $data = $this->generate_lp_folder($_course);
  8568. if ($action != 'edit') {
  8569. $folders = DocumentManager::get_all_document_folders($_course, 0, true);
  8570. DocumentManager::build_directory_selector(
  8571. $folders,
  8572. '',
  8573. [],
  8574. true,
  8575. $form,
  8576. 'directory_parent_id'
  8577. );
  8578. }
  8579. if (isset($data['id'])) {
  8580. $defaults['directory_parent_id'] = $data['id'];
  8581. }
  8582. $form->addElement(
  8583. 'text',
  8584. 'title',
  8585. get_lang('Title')
  8586. );
  8587. $form->applyFilter('title', 'trim');
  8588. $form->applyFilter('title', 'html_filter');
  8589. $arrHide[0]['value'] = $this->name;
  8590. $arrHide[0]['padding'] = 20;
  8591. for ($i = 0; $i < count($arrLP); $i++) {
  8592. if ($action != 'add') {
  8593. if ($arrLP[$i]['item_type'] == 'dir' &&
  8594. !in_array($arrLP[$i]['id'], $arrHide) &&
  8595. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8596. ) {
  8597. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8598. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  8599. }
  8600. } else {
  8601. if ($arrLP[$i]['item_type'] == 'dir') {
  8602. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8603. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  8604. }
  8605. }
  8606. }
  8607. $parent_select = $form->addSelect(
  8608. 'parent',
  8609. get_lang('Parent'),
  8610. [],
  8611. ['onchange' => "javascript: load_cbo(this.value, 'frm_add_reading_previous');"]
  8612. );
  8613. $my_count = 0;
  8614. foreach ($arrHide as $key => $value) {
  8615. if ($my_count != 0) {
  8616. // The LP name is also the first section and is not in the same charset like the other sections.
  8617. $value['value'] = Security::remove_XSS($value['value']);
  8618. $parent_select->addOption(
  8619. $value['value'],
  8620. $key,
  8621. 'style="padding-left:'.$value['padding'].'px;"'
  8622. );
  8623. } else {
  8624. $value['value'] = Security::remove_XSS($value['value']);
  8625. $parent_select->addOption(
  8626. $value['value'],
  8627. $key,
  8628. 'style="padding-left:'.$value['padding'].'px;"'
  8629. );
  8630. }
  8631. $my_count++;
  8632. }
  8633. if (!empty($id)) {
  8634. $parent_select->setSelected($parent);
  8635. } else {
  8636. $parent_item_id = Session::read('parent_item_id', 0);
  8637. $parent_select->setSelected($parent_item_id);
  8638. }
  8639. if (is_array($arrLP)) {
  8640. reset($arrLP);
  8641. }
  8642. $arrHide = [];
  8643. $s_selected_position = null;
  8644. // POSITION
  8645. $lastPosition = null;
  8646. for ($i = 0; $i < count($arrLP); $i++) {
  8647. if (($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) &&
  8648. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM
  8649. ) {
  8650. if ((isset($extra_info['previous_item_id']) &&
  8651. $extra_info['previous_item_id'] == $arrLP[$i]['id']) || $action == 'add'
  8652. ) {
  8653. $s_selected_position = $arrLP[$i]['id'];
  8654. }
  8655. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  8656. }
  8657. $lastPosition = $arrLP[$i]['id'];
  8658. }
  8659. if (empty($s_selected_position)) {
  8660. $s_selected_position = $lastPosition;
  8661. }
  8662. $position = $form->addSelect(
  8663. 'previous',
  8664. get_lang('Position'),
  8665. []
  8666. );
  8667. $position->addOption(get_lang('FirstPosition'), 0);
  8668. foreach ($arrHide as $key => $value) {
  8669. $padding = isset($value['padding']) ? $value['padding'] : 20;
  8670. $position->addOption(
  8671. $value['value'],
  8672. $key,
  8673. 'style="padding-left:'.$padding.'px;"'
  8674. );
  8675. }
  8676. $position->setSelected($s_selected_position);
  8677. if (is_array($arrLP)) {
  8678. reset($arrLP);
  8679. }
  8680. if ('edit' === $action) {
  8681. $extraField = new ExtraField('lp_item');
  8682. $extraField->addElements($form, $id);
  8683. }
  8684. $arrHide = [];
  8685. for ($i = 0; $i < count($arrLP); $i++) {
  8686. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir' &&
  8687. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM
  8688. ) {
  8689. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8690. }
  8691. }
  8692. if (!$no_display_add) {
  8693. $item_type = isset($extra_info['item_type']) ? $extra_info['item_type'] : null;
  8694. $edit = isset($_GET['edit']) ? $_GET['edit'] : null;
  8695. if ($extra_info == 'new' || $item_type == TOOL_READOUT_TEXT || $edit == 'true') {
  8696. if (!$no_display_edit_textarea) {
  8697. $content = '';
  8698. if (isset($_POST['content'])) {
  8699. $content = stripslashes($_POST['content']);
  8700. } elseif (is_array($extra_info)) {
  8701. $content = $this->display_document($extra_info['path'], false, false);
  8702. } elseif (is_numeric($extra_info)) {
  8703. $content = $this->display_document($extra_info, false, false);
  8704. }
  8705. // A new document, it is in the root of the repository.
  8706. if (is_array($extra_info) && $extra_info != 'new') {
  8707. } else {
  8708. $this->generate_lp_folder($_course);
  8709. }
  8710. if ($_GET['action'] == 'add_item') {
  8711. $text = get_lang('LPCreateDocument');
  8712. } else {
  8713. $text = get_lang('SaveDocument');
  8714. }
  8715. $form->addTextarea('content_lp', get_lang('Content'), ['rows' => 20]);
  8716. $form
  8717. ->defaultRenderer()
  8718. ->setElementTemplate($form->getDefaultElementTemplate(), 'content_lp');
  8719. $form->addButtonSave($text, 'submit_button');
  8720. $defaults['content_lp'] = $content;
  8721. }
  8722. } elseif (is_numeric($extra_info)) {
  8723. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  8724. $return = $this->display_document($extra_info, true, true, true);
  8725. $form->addElement('html', $return);
  8726. }
  8727. }
  8728. if (is_numeric($extra_info)) {
  8729. $form->addElement('hidden', 'path', $extra_info);
  8730. } elseif (is_array($extra_info)) {
  8731. $form->addElement('hidden', 'path', $extra_info['path']);
  8732. }
  8733. $form->addElement('hidden', 'type', TOOL_READOUT_TEXT);
  8734. $form->addElement('hidden', 'post_time', time());
  8735. $form->setDefaults($defaults);
  8736. return $form->returnForm();
  8737. }
  8738. /**
  8739. * @param array $courseInfo
  8740. * @param string $content
  8741. * @param string $title
  8742. * @param int $parentId
  8743. *
  8744. * @throws \Doctrine\ORM\ORMException
  8745. * @throws \Doctrine\ORM\OptimisticLockException
  8746. * @throws \Doctrine\ORM\TransactionRequiredException
  8747. *
  8748. * @return int
  8749. */
  8750. public function createReadOutText($courseInfo, $content = '', $title = '', $parentId = 0)
  8751. {
  8752. $creatorId = api_get_user_id();
  8753. $sessionId = api_get_session_id();
  8754. // Generates folder
  8755. $result = $this->generate_lp_folder($courseInfo);
  8756. $dir = $result['dir'];
  8757. if (empty($parentId) || $parentId == '/') {
  8758. $postDir = isset($_POST['dir']) ? $_POST['dir'] : $dir;
  8759. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir; // Please, do not modify this dirname formatting.
  8760. if ($parentId === '/') {
  8761. $dir = '/';
  8762. }
  8763. // Please, do not modify this dirname formatting.
  8764. if (strstr($dir, '..')) {
  8765. $dir = '/';
  8766. }
  8767. if (!empty($dir[0]) && $dir[0] == '.') {
  8768. $dir = substr($dir, 1);
  8769. }
  8770. if (!empty($dir[0]) && $dir[0] != '/') {
  8771. $dir = '/'.$dir;
  8772. }
  8773. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  8774. $dir .= '/';
  8775. }
  8776. } else {
  8777. $parentInfo = DocumentManager::get_document_data_by_id(
  8778. $parentId,
  8779. $courseInfo['code']
  8780. );
  8781. if (!empty($parentInfo)) {
  8782. $dir = $parentInfo['path'].'/';
  8783. }
  8784. }
  8785. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  8786. if (!is_dir($filepath)) {
  8787. $dir = '/';
  8788. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  8789. }
  8790. $originalTitle = !empty($title) ? $title : $_POST['title'];
  8791. if (!empty($title)) {
  8792. $title = api_replace_dangerous_char(stripslashes($title));
  8793. } else {
  8794. $title = api_replace_dangerous_char(stripslashes($_POST['title']));
  8795. }
  8796. $title = disable_dangerous_file($title);
  8797. $filename = $title;
  8798. $content = !empty($content) ? $content : $_POST['content_lp'];
  8799. $tmpFileName = $filename;
  8800. $i = 0;
  8801. while (file_exists($filepath.$tmpFileName.'.html')) {
  8802. $tmpFileName = $filename.'_'.++$i;
  8803. }
  8804. $filename = $tmpFileName.'.html';
  8805. $content = stripslashes($content);
  8806. if (file_exists($filepath.$filename)) {
  8807. return 0;
  8808. }
  8809. $putContent = file_put_contents($filepath.$filename, $content);
  8810. if ($putContent === false) {
  8811. return 0;
  8812. }
  8813. $fileSize = filesize($filepath.$filename);
  8814. $saveFilePath = $dir.$filename;
  8815. $documentId = add_document(
  8816. $courseInfo,
  8817. $saveFilePath,
  8818. 'file',
  8819. $fileSize,
  8820. $tmpFileName,
  8821. '',
  8822. 0, //readonly
  8823. true,
  8824. null,
  8825. $sessionId,
  8826. $creatorId
  8827. );
  8828. if (!$documentId) {
  8829. return 0;
  8830. }
  8831. api_item_property_update(
  8832. $courseInfo,
  8833. TOOL_DOCUMENT,
  8834. $documentId,
  8835. 'DocumentAdded',
  8836. $creatorId,
  8837. null,
  8838. null,
  8839. null,
  8840. null,
  8841. $sessionId
  8842. );
  8843. $newComment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
  8844. $newTitle = $originalTitle;
  8845. if ($newComment || $newTitle) {
  8846. $em = Database::getManager();
  8847. /** @var CDocument $doc */
  8848. $doc = $em->find('ChamiloCourseBundle:CDocument', $documentId);
  8849. if ($newComment) {
  8850. $doc->setComment($newComment);
  8851. }
  8852. if ($newTitle) {
  8853. $doc->setTitle($newTitle);
  8854. }
  8855. $em->persist($doc);
  8856. $em->flush();
  8857. }
  8858. return $documentId;
  8859. }
  8860. /**
  8861. * Return HTML form to add/edit a link item.
  8862. *
  8863. * @param string $action (add/edit)
  8864. * @param int $id Item ID if exists
  8865. * @param mixed $extra_info
  8866. *
  8867. * @throws Exception
  8868. * @throws HTML_QuickForm_Error
  8869. *
  8870. * @return string HTML form
  8871. */
  8872. public function display_link_form($action = 'add', $id = 0, $extra_info = '')
  8873. {
  8874. $course_id = api_get_course_int_id();
  8875. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8876. $tbl_link = Database::get_course_table(TABLE_LINK);
  8877. $item_title = '';
  8878. $item_description = '';
  8879. $item_url = '';
  8880. if ($id != 0 && is_array($extra_info)) {
  8881. $item_title = stripslashes($extra_info['title']);
  8882. $item_description = stripslashes($extra_info['description']);
  8883. $item_url = stripslashes($extra_info['url']);
  8884. } elseif (is_numeric($extra_info)) {
  8885. $extra_info = (int) $extra_info;
  8886. $sql = "SELECT title, description, url
  8887. FROM $tbl_link
  8888. WHERE c_id = $course_id AND iid = $extra_info";
  8889. $result = Database::query($sql);
  8890. $row = Database::fetch_array($result);
  8891. $item_title = $row['title'];
  8892. $item_description = $row['description'];
  8893. $item_url = $row['url'];
  8894. }
  8895. $form = new FormValidator(
  8896. 'edit_link',
  8897. 'POST',
  8898. $this->getCurrentBuildingModeURL()
  8899. );
  8900. $defaults = [];
  8901. $parent = 0;
  8902. if ($id != 0 && is_array($extra_info)) {
  8903. $parent = $extra_info['parent_item_id'];
  8904. }
  8905. $sql = "SELECT * FROM $tbl_lp_item
  8906. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8907. $result = Database::query($sql);
  8908. $arrLP = [];
  8909. while ($row = Database::fetch_array($result)) {
  8910. $arrLP[] = [
  8911. 'id' => $row['id'],
  8912. 'item_type' => $row['item_type'],
  8913. 'title' => $row['title'],
  8914. 'path' => $row['path'],
  8915. 'description' => $row['description'],
  8916. 'parent_item_id' => $row['parent_item_id'],
  8917. 'previous_item_id' => $row['previous_item_id'],
  8918. 'next_item_id' => $row['next_item_id'],
  8919. 'display_order' => $row['display_order'],
  8920. 'max_score' => $row['max_score'],
  8921. 'min_score' => $row['min_score'],
  8922. 'mastery_score' => $row['mastery_score'],
  8923. 'prerequisite' => $row['prerequisite'],
  8924. ];
  8925. }
  8926. $this->tree_array($arrLP);
  8927. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  8928. unset($this->arrMenu);
  8929. if ($action == 'add') {
  8930. $legend = get_lang('CreateTheLink');
  8931. } elseif ($action == 'move') {
  8932. $legend = get_lang('MoveCurrentLink');
  8933. } else {
  8934. $legend = get_lang('EditCurrentLink');
  8935. }
  8936. $form->addHeader($legend);
  8937. if ($action != 'move') {
  8938. $form->addText('title', get_lang('Title'), true, ['class' => 'learnpath_item_form']);
  8939. $defaults['title'] = $item_title;
  8940. }
  8941. $selectParent = $form->addSelect(
  8942. 'parent',
  8943. get_lang('Parent'),
  8944. [],
  8945. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);', 'class' => 'learnpath_item_form']
  8946. );
  8947. $selectParent->addOption($this->name, 0);
  8948. $arrHide = [
  8949. $id,
  8950. ];
  8951. $parent_item_id = Session::read('parent_item_id', 0);
  8952. for ($i = 0; $i < count($arrLP); $i++) {
  8953. if ($action != 'add') {
  8954. if (
  8955. ($arrLP[$i]['item_type'] == 'dir') &&
  8956. !in_array($arrLP[$i]['id'], $arrHide) &&
  8957. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8958. ) {
  8959. $selectParent->addOption(
  8960. $arrLP[$i]['title'],
  8961. $arrLP[$i]['id'],
  8962. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px;']
  8963. );
  8964. if ($parent == $arrLP[$i]['id']) {
  8965. $selectParent->setSelected($arrLP[$i]['id']);
  8966. }
  8967. } else {
  8968. $arrHide[] = $arrLP[$i]['id'];
  8969. }
  8970. } else {
  8971. if ($arrLP[$i]['item_type'] == 'dir') {
  8972. $selectParent->addOption(
  8973. $arrLP[$i]['title'],
  8974. $arrLP[$i]['id'],
  8975. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  8976. );
  8977. if ($parent_item_id == $arrLP[$i]['id']) {
  8978. $selectParent->setSelected($arrLP[$i]['id']);
  8979. }
  8980. }
  8981. }
  8982. }
  8983. if (is_array($arrLP)) {
  8984. reset($arrLP);
  8985. }
  8986. $selectPrevious = $form->addSelect(
  8987. 'previous',
  8988. get_lang('Position'),
  8989. [],
  8990. ['id' => 'previous', 'class' => 'learnpath_item_form']
  8991. );
  8992. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  8993. for ($i = 0; $i < count($arrLP); $i++) {
  8994. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  8995. $selectPrevious->addOption(
  8996. $arrLP[$i]['title'],
  8997. $arrLP[$i]['id']
  8998. );
  8999. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  9000. $selectPrevious->setSelected($arrLP[$i]['id']);
  9001. } elseif ($action == 'add') {
  9002. $selectPrevious->setSelected($arrLP[$i]['id']);
  9003. }
  9004. }
  9005. }
  9006. if ($action != 'move') {
  9007. $urlAttributes = ['class' => 'learnpath_item_form'];
  9008. if (is_numeric($extra_info)) {
  9009. $urlAttributes['disabled'] = 'disabled';
  9010. }
  9011. $form->addElement('url', 'url', get_lang('Url'), $urlAttributes);
  9012. $defaults['url'] = $item_url;
  9013. $arrHide = [];
  9014. for ($i = 0; $i < count($arrLP); $i++) {
  9015. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  9016. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  9017. }
  9018. }
  9019. }
  9020. if ('edit' === $action) {
  9021. $extraField = new ExtraField('lp_item');
  9022. $extraField->addElements($form, $id);
  9023. }
  9024. if ($action == 'add') {
  9025. $form->addButtonSave(get_lang('AddLinkToCourse'), 'submit_button');
  9026. } else {
  9027. $form->addButtonSave(get_lang('EditCurrentLink'), 'submit_button');
  9028. }
  9029. if ($action == 'move') {
  9030. $form->addHidden('title', $item_title);
  9031. $form->addHidden('description', $item_description);
  9032. }
  9033. if (is_numeric($extra_info)) {
  9034. $form->addHidden('path', $extra_info);
  9035. } elseif (is_array($extra_info)) {
  9036. $form->addHidden('path', $extra_info['path']);
  9037. }
  9038. $form->addHidden('type', TOOL_LINK);
  9039. $form->addHidden('post_time', time());
  9040. $form->setDefaults($defaults);
  9041. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  9042. }
  9043. /**
  9044. * Return HTML form to add/edit a student publication (work).
  9045. *
  9046. * @param string $action
  9047. * @param int $id Item ID if already exists
  9048. * @param string $extra_info
  9049. *
  9050. * @throws Exception
  9051. *
  9052. * @return string HTML form
  9053. */
  9054. public function display_student_publication_form(
  9055. $action = 'add',
  9056. $id = 0,
  9057. $extra_info = ''
  9058. ) {
  9059. $course_id = api_get_course_int_id();
  9060. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  9061. $tbl_publication = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  9062. $item_title = get_lang('Student_publication');
  9063. if ($id != 0 && is_array($extra_info)) {
  9064. $item_title = stripslashes($extra_info['title']);
  9065. $item_description = stripslashes($extra_info['description']);
  9066. } elseif (is_numeric($extra_info)) {
  9067. $extra_info = (int) $extra_info;
  9068. $sql = "SELECT title, description
  9069. FROM $tbl_publication
  9070. WHERE c_id = $course_id AND id = ".$extra_info;
  9071. $result = Database::query($sql);
  9072. $row = Database::fetch_array($result);
  9073. if ($row) {
  9074. $item_title = $row['title'];
  9075. }
  9076. }
  9077. $parent = 0;
  9078. if ($id != 0 && is_array($extra_info)) {
  9079. $parent = $extra_info['parent_item_id'];
  9080. }
  9081. $sql = "SELECT * FROM $tbl_lp_item
  9082. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  9083. $result = Database::query($sql);
  9084. $arrLP = [];
  9085. while ($row = Database::fetch_array($result)) {
  9086. $arrLP[] = [
  9087. 'id' => $row['iid'],
  9088. 'item_type' => $row['item_type'],
  9089. 'title' => $row['title'],
  9090. 'path' => $row['path'],
  9091. 'description' => $row['description'],
  9092. 'parent_item_id' => $row['parent_item_id'],
  9093. 'previous_item_id' => $row['previous_item_id'],
  9094. 'next_item_id' => $row['next_item_id'],
  9095. 'display_order' => $row['display_order'],
  9096. 'max_score' => $row['max_score'],
  9097. 'min_score' => $row['min_score'],
  9098. 'mastery_score' => $row['mastery_score'],
  9099. 'prerequisite' => $row['prerequisite'],
  9100. ];
  9101. }
  9102. $this->tree_array($arrLP);
  9103. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  9104. unset($this->arrMenu);
  9105. $form = new FormValidator('frm_student_publication', 'post', '#');
  9106. if ($action == 'add') {
  9107. $form->addHeader(get_lang('Student_publication'));
  9108. } elseif ($action == 'move') {
  9109. $form->addHeader(get_lang('MoveCurrentStudentPublication'));
  9110. } else {
  9111. $form->addHeader(get_lang('EditCurrentStudentPublication'));
  9112. }
  9113. if ($action != 'move') {
  9114. $form->addText(
  9115. 'title',
  9116. get_lang('Title'),
  9117. true,
  9118. ['class' => 'learnpath_item_form', 'id' => 'idTitle']
  9119. );
  9120. }
  9121. $parentSelect = $form->addSelect(
  9122. 'parent',
  9123. get_lang('Parent'),
  9124. ['0' => $this->name],
  9125. [
  9126. 'onchange' => 'javascript: load_cbo(this.value);',
  9127. 'class' => 'learnpath_item_form',
  9128. 'id' => 'idParent',
  9129. ]
  9130. );
  9131. $arrHide = [$id];
  9132. for ($i = 0; $i < count($arrLP); $i++) {
  9133. if ($action != 'add') {
  9134. if (
  9135. ($arrLP[$i]['item_type'] == 'dir') &&
  9136. !in_array($arrLP[$i]['id'], $arrHide) &&
  9137. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  9138. ) {
  9139. $parentSelect->addOption(
  9140. $arrLP[$i]['title'],
  9141. $arrLP[$i]['id'],
  9142. ['style' => 'padding-left: '.(($arrLP[$i]['depth'] * 10) + 20).'px;']
  9143. );
  9144. if ($parent == $arrLP[$i]['id']) {
  9145. $parentSelect->setSelected($arrLP[$i]['id']);
  9146. }
  9147. } else {
  9148. $arrHide[] = $arrLP[$i]['id'];
  9149. }
  9150. } else {
  9151. if ($arrLP[$i]['item_type'] == 'dir') {
  9152. $parentSelect->addOption(
  9153. $arrLP[$i]['title'],
  9154. $arrLP[$i]['id'],
  9155. ['style' => 'padding-left: '.(($arrLP[$i]['depth'] * 10) + 20).'px;']
  9156. );
  9157. if ($parent == $arrLP[$i]['id']) {
  9158. $parentSelect->setSelected($arrLP[$i]['id']);
  9159. }
  9160. }
  9161. }
  9162. }
  9163. if (is_array($arrLP)) {
  9164. reset($arrLP);
  9165. }
  9166. $previousSelect = $form->addSelect(
  9167. 'previous',
  9168. get_lang('Position'),
  9169. ['0' => get_lang('FirstPosition')],
  9170. ['id' => 'previous', 'class' => 'learnpath_item_form']
  9171. );
  9172. for ($i = 0; $i < count($arrLP); $i++) {
  9173. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  9174. $previousSelect->addOption(
  9175. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  9176. $arrLP[$i]['id']
  9177. );
  9178. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  9179. $previousSelect->setSelected($arrLP[$i]['id']);
  9180. } elseif ($action == 'add') {
  9181. $previousSelect->setSelected($arrLP[$i]['id']);
  9182. }
  9183. }
  9184. }
  9185. if ('edit' === $action) {
  9186. $extraField = new ExtraField('lp_item');
  9187. $extraField->addElements($form, $id);
  9188. }
  9189. if ($action == 'add') {
  9190. $form->addButtonCreate(get_lang('AddAssignmentToCourse'), 'submit_button');
  9191. } else {
  9192. $form->addButtonCreate(get_lang('EditCurrentStudentPublication'), 'submit_button');
  9193. }
  9194. if ($action == 'move') {
  9195. $form->addHidden('title', $item_title);
  9196. $form->addHidden('description', $item_description);
  9197. }
  9198. if (is_numeric($extra_info)) {
  9199. $form->addHidden('path', $extra_info);
  9200. } elseif (is_array($extra_info)) {
  9201. $form->addHidden('path', $extra_info['path']);
  9202. }
  9203. $form->addHidden('type', TOOL_STUDENTPUBLICATION);
  9204. $form->addHidden('post_time', time());
  9205. $form->setDefaults(['title' => $item_title]);
  9206. $return = '<div class="sectioncomment">';
  9207. $return .= $form->returnForm();
  9208. $return .= '</div>';
  9209. return $return;
  9210. }
  9211. /**
  9212. * Displays the menu for manipulating a step.
  9213. *
  9214. * @param id $item_id
  9215. * @param string $item_type
  9216. *
  9217. * @return string
  9218. */
  9219. public function display_manipulate($item_id, $item_type = TOOL_DOCUMENT)
  9220. {
  9221. $_course = api_get_course_info();
  9222. $course_code = api_get_course_id();
  9223. $item_id = (int) $item_id;
  9224. $return = '<div class="actions">';
  9225. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  9226. $sql = "SELECT * FROM $tbl_lp_item
  9227. WHERE iid = ".$item_id;
  9228. $result = Database::query($sql);
  9229. $row = Database::fetch_assoc($result);
  9230. $audio_player = null;
  9231. // We display an audio player if needed.
  9232. if (!empty($row['audio'])) {
  9233. $webAudioPath = '../..'.api_get_path(REL_COURSE_PATH).$_course['path'].'/document/audio/'.$row['audio'];
  9234. $audio_player .= '<div class="lp_mediaplayer" id="container">'
  9235. .'<audio src="'.$webAudioPath.'" controls>'
  9236. .'</div><br>';
  9237. }
  9238. $url = api_get_self().'?'.api_get_cidreq().'&view=build&id='.$item_id.'&lp_id='.$this->lp_id;
  9239. if ($item_type != TOOL_LP_FINAL_ITEM) {
  9240. $return .= Display::url(
  9241. Display::return_icon(
  9242. 'edit.png',
  9243. get_lang('Edit'),
  9244. [],
  9245. ICON_SIZE_SMALL
  9246. ),
  9247. $url.'&action=edit_item&path_item='.$row['path']
  9248. );
  9249. $return .= Display::url(
  9250. Display::return_icon(
  9251. 'move.png',
  9252. get_lang('Move'),
  9253. [],
  9254. ICON_SIZE_SMALL
  9255. ),
  9256. $url.'&action=move_item'
  9257. );
  9258. }
  9259. // Commented for now as prerequisites cannot be added to chapters.
  9260. if ($item_type != 'dir') {
  9261. $return .= Display::url(
  9262. Display::return_icon(
  9263. 'accept.png',
  9264. get_lang('LearnpathPrerequisites'),
  9265. [],
  9266. ICON_SIZE_SMALL
  9267. ),
  9268. $url.'&action=edit_item_prereq'
  9269. );
  9270. }
  9271. $return .= Display::url(
  9272. Display::return_icon(
  9273. 'delete.png',
  9274. get_lang('Delete'),
  9275. [],
  9276. ICON_SIZE_SMALL
  9277. ),
  9278. $url.'&action=delete_item'
  9279. );
  9280. if (in_array($item_type, [TOOL_DOCUMENT, TOOL_LP_FINAL_ITEM, TOOL_HOTPOTATOES])) {
  9281. $documentData = DocumentManager::get_document_data_by_id($row['path'], $course_code);
  9282. if (empty($documentData)) {
  9283. // Try with iid
  9284. $table = Database::get_course_table(TABLE_DOCUMENT);
  9285. $sql = "SELECT path FROM $table
  9286. WHERE
  9287. c_id = ".api_get_course_int_id()." AND
  9288. iid = ".$row['path']." AND
  9289. path NOT LIKE '%_DELETED_%'";
  9290. $result = Database::query($sql);
  9291. $documentData = Database::fetch_array($result);
  9292. if ($documentData) {
  9293. $documentData['absolute_path_from_document'] = '/document'.$documentData['path'];
  9294. }
  9295. }
  9296. if (isset($documentData['absolute_path_from_document'])) {
  9297. $return .= get_lang('File').': '.$documentData['absolute_path_from_document'];
  9298. }
  9299. }
  9300. $return .= '</div>';
  9301. if (!empty($audio_player)) {
  9302. $return .= $audio_player;
  9303. }
  9304. return $return;
  9305. }
  9306. /**
  9307. * Creates the javascript needed for filling up the checkboxes without page reload.
  9308. *
  9309. * @return string
  9310. */
  9311. public function get_js_dropdown_array()
  9312. {
  9313. $course_id = api_get_course_int_id();
  9314. $return = 'var child_name = new Array();'."\n";
  9315. $return .= 'var child_value = new Array();'."\n\n";
  9316. $return .= 'child_name[0] = new Array();'."\n";
  9317. $return .= 'child_value[0] = new Array();'."\n\n";
  9318. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  9319. $sql = "SELECT * FROM ".$tbl_lp_item."
  9320. WHERE
  9321. c_id = $course_id AND
  9322. lp_id = ".$this->lp_id." AND
  9323. parent_item_id = 0
  9324. ORDER BY display_order ASC";
  9325. $res_zero = Database::query($sql);
  9326. $i = 0;
  9327. while ($row_zero = Database::fetch_array($res_zero)) {
  9328. if ($row_zero['item_type'] !== TOOL_LP_FINAL_ITEM) {
  9329. if ($row_zero['item_type'] == TOOL_QUIZ) {
  9330. $row_zero['title'] = Exercise::get_formated_title_variable($row_zero['title']);
  9331. }
  9332. $js_var = json_encode(get_lang('After').' '.$row_zero['title']);
  9333. $return .= 'child_name[0]['.$i.'] = '.$js_var.' ;'."\n";
  9334. $return .= 'child_value[0]['.$i++.'] = "'.$row_zero['iid'].'";'."\n";
  9335. }
  9336. }
  9337. $return .= "\n";
  9338. $sql = "SELECT * FROM $tbl_lp_item
  9339. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  9340. $res = Database::query($sql);
  9341. while ($row = Database::fetch_array($res)) {
  9342. $sql_parent = "SELECT * FROM ".$tbl_lp_item."
  9343. WHERE
  9344. c_id = ".$course_id." AND
  9345. parent_item_id = ".$row['iid']."
  9346. ORDER BY display_order ASC";
  9347. $res_parent = Database::query($sql_parent);
  9348. $i = 0;
  9349. $return .= 'child_name['.$row['iid'].'] = new Array();'."\n";
  9350. $return .= 'child_value['.$row['iid'].'] = new Array();'."\n\n";
  9351. while ($row_parent = Database::fetch_array($res_parent)) {
  9352. $js_var = json_encode(get_lang('After').' '.$row_parent['title']);
  9353. $return .= 'child_name['.$row['iid'].']['.$i.'] = '.$js_var.' ;'."\n";
  9354. $return .= 'child_value['.$row['iid'].']['.$i++.'] = "'.$row_parent['iid'].'";'."\n";
  9355. }
  9356. $return .= "\n";
  9357. }
  9358. $return .= "
  9359. function load_cbo(id) {
  9360. if (!id) {
  9361. return false;
  9362. }
  9363. var cbo = document.getElementById('previous');
  9364. for(var i = cbo.length - 1; i > 0; i--) {
  9365. cbo.options[i] = null;
  9366. }
  9367. var k=0;
  9368. for(var i = 1; i <= child_name[id].length; i++){
  9369. var option = new Option(child_name[id][i - 1], child_value[id][i - 1]);
  9370. option.style.paddingLeft = '40px';
  9371. cbo.options[i] = option;
  9372. k = i;
  9373. }
  9374. cbo.options[k].selected = true;
  9375. $('#previous').selectpicker('refresh');
  9376. }";
  9377. return $return;
  9378. }
  9379. /**
  9380. * Display the form to allow moving an item.
  9381. *
  9382. * @param int $item_id Item ID
  9383. *
  9384. * @throws Exception
  9385. * @throws HTML_QuickForm_Error
  9386. *
  9387. * @return string HTML form
  9388. */
  9389. public function display_move_item($item_id)
  9390. {
  9391. $return = '';
  9392. if (is_numeric($item_id)) {
  9393. $item_id = (int) $item_id;
  9394. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  9395. $sql = "SELECT * FROM $tbl_lp_item
  9396. WHERE iid = $item_id";
  9397. $res = Database::query($sql);
  9398. $row = Database::fetch_array($res);
  9399. switch ($row['item_type']) {
  9400. case 'dir':
  9401. case 'asset':
  9402. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9403. $return .= $this->display_item_form(
  9404. $row['item_type'],
  9405. get_lang('MoveCurrentChapter'),
  9406. 'move',
  9407. $item_id,
  9408. $row
  9409. );
  9410. break;
  9411. case TOOL_DOCUMENT:
  9412. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9413. $return .= $this->display_document_form('move', $item_id, $row);
  9414. break;
  9415. case TOOL_LINK:
  9416. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9417. $return .= $this->display_link_form('move', $item_id, $row);
  9418. break;
  9419. case TOOL_HOTPOTATOES:
  9420. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9421. $return .= $this->display_link_form('move', $item_id, $row);
  9422. break;
  9423. case TOOL_QUIZ:
  9424. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9425. $return .= $this->display_quiz_form('move', $item_id, $row);
  9426. break;
  9427. case TOOL_STUDENTPUBLICATION:
  9428. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9429. $return .= $this->display_student_publication_form('move', $item_id, $row);
  9430. break;
  9431. case TOOL_FORUM:
  9432. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9433. $return .= $this->display_forum_form('move', $item_id, $row);
  9434. break;
  9435. case TOOL_THREAD:
  9436. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9437. $return .= $this->display_forum_form('move', $item_id, $row);
  9438. break;
  9439. }
  9440. }
  9441. return $return;
  9442. }
  9443. /**
  9444. * Return HTML form to allow prerequisites selection.
  9445. *
  9446. * @todo use FormValidator
  9447. *
  9448. * @param int Item ID
  9449. *
  9450. * @return string HTML form
  9451. */
  9452. public function display_item_prerequisites_form($item_id = 0)
  9453. {
  9454. $course_id = api_get_course_int_id();
  9455. $item_id = (int) $item_id;
  9456. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  9457. /* Current prerequisite */
  9458. $sql = "SELECT * FROM $tbl_lp_item
  9459. WHERE iid = $item_id";
  9460. $result = Database::query($sql);
  9461. $row = Database::fetch_array($result);
  9462. $prerequisiteId = $row['prerequisite'];
  9463. $return = '<legend>';
  9464. $return .= get_lang('AddEditPrerequisites');
  9465. $return .= '</legend>';
  9466. $return .= '<form method="POST">';
  9467. $return .= '<div class="table-responsive">';
  9468. $return .= '<table class="table table-hover">';
  9469. $return .= '<thead>';
  9470. $return .= '<tr>';
  9471. $return .= '<th>'.get_lang('LearnpathPrerequisites').'</th>';
  9472. $return .= '<th width="140">'.get_lang('Minimum').'</th>';
  9473. $return .= '<th width="140">'.get_lang('Maximum').'</th>';
  9474. $return .= '</tr>';
  9475. $return .= '</thead>';
  9476. // Adding the none option to the prerequisites see http://www.chamilo.org/es/node/146
  9477. $return .= '<tbody>';
  9478. $return .= '<tr>';
  9479. $return .= '<td colspan="3">';
  9480. $return .= '<div class="radio learnpath"><label for="idNone">';
  9481. $return .= '<input checked="checked" id="idNone" name="prerequisites" type="radio" />';
  9482. $return .= get_lang('None').'</label>';
  9483. $return .= '</div>';
  9484. $return .= '</tr>';
  9485. $sql = "SELECT * FROM $tbl_lp_item
  9486. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  9487. $result = Database::query($sql);
  9488. $arrLP = [];
  9489. $selectedMinScore = [];
  9490. $selectedMaxScore = [];
  9491. $masteryScore = [];
  9492. while ($row = Database::fetch_array($result)) {
  9493. if ($row['iid'] == $item_id) {
  9494. $selectedMinScore[$row['prerequisite']] = $row['prerequisite_min_score'];
  9495. $selectedMaxScore[$row['prerequisite']] = $row['prerequisite_max_score'];
  9496. }
  9497. $masteryScore[$row['iid']] = $row['mastery_score'];
  9498. $arrLP[] = [
  9499. 'id' => $row['iid'],
  9500. 'item_type' => $row['item_type'],
  9501. 'title' => $row['title'],
  9502. 'ref' => $row['ref'],
  9503. 'description' => $row['description'],
  9504. 'parent_item_id' => $row['parent_item_id'],
  9505. 'previous_item_id' => $row['previous_item_id'],
  9506. 'next_item_id' => $row['next_item_id'],
  9507. 'max_score' => $row['max_score'],
  9508. 'min_score' => $row['min_score'],
  9509. 'mastery_score' => $row['mastery_score'],
  9510. 'prerequisite' => $row['prerequisite'],
  9511. 'display_order' => $row['display_order'],
  9512. 'prerequisite_min_score' => $row['prerequisite_min_score'],
  9513. 'prerequisite_max_score' => $row['prerequisite_max_score'],
  9514. ];
  9515. }
  9516. $this->tree_array($arrLP);
  9517. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  9518. unset($this->arrMenu);
  9519. for ($i = 0; $i < count($arrLP); $i++) {
  9520. $item = $arrLP[$i];
  9521. if ($item['id'] == $item_id) {
  9522. break;
  9523. }
  9524. $selectedMaxScoreValue = isset($selectedMaxScore[$item['id']]) ? $selectedMaxScore[$item['id']] : $item['max_score'];
  9525. $selectedMinScoreValue = isset($selectedMinScore[$item['id']]) ? $selectedMinScore[$item['id']] : 0;
  9526. $masteryScoreAsMinValue = isset($masteryScore[$item['id']]) ? $masteryScore[$item['id']] : 0;
  9527. $return .= '<tr>';
  9528. $return .= '<td '.(($item['item_type'] != TOOL_QUIZ && $item['item_type'] != TOOL_HOTPOTATOES) ? ' colspan="3"' : '').'>';
  9529. $return .= '<div style="margin-left:'.($item['depth'] * 20).'px;" class="radio learnpath">';
  9530. $return .= '<label for="id'.$item['id'].'">';
  9531. $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'].'" />';
  9532. $icon_name = str_replace(' ', '', $item['item_type']);
  9533. if (file_exists('../img/lp_'.$icon_name.'.png')) {
  9534. $return .= Display::return_icon('lp_'.$icon_name.'.png');
  9535. } else {
  9536. if (file_exists('../img/lp_'.$icon_name.'.png')) {
  9537. $return .= Display::return_icon('lp_'.$icon_name.'.png');
  9538. } else {
  9539. $return .= Display::return_icon('folder_document.png');
  9540. }
  9541. }
  9542. $return .= $item['title'].'</label>';
  9543. $return .= '</div>';
  9544. $return .= '</td>';
  9545. if ($item['item_type'] == TOOL_QUIZ) {
  9546. // lets update max_score Quiz information depending of the Quiz Advanced properties
  9547. $lpItemObj = new LpItem($course_id, $item['id']);
  9548. $exercise = new Exercise($course_id);
  9549. $exercise->read($lpItemObj->path);
  9550. $lpItemObj->max_score = $exercise->get_max_score();
  9551. $lpItemObj->update();
  9552. $item['max_score'] = $lpItemObj->max_score;
  9553. if (empty($selectedMinScoreValue) && !empty($masteryScoreAsMinValue)) {
  9554. // Backwards compatibility with 1.9.x use mastery_score as min value
  9555. $selectedMinScoreValue = $masteryScoreAsMinValue;
  9556. }
  9557. $return .= '<td>';
  9558. $return .= '<input
  9559. class="form-control"
  9560. size="4" maxlength="3"
  9561. name="min_'.$item['id'].'"
  9562. type="number"
  9563. min="0"
  9564. step="1"
  9565. max="'.$item['max_score'].'"
  9566. value="'.$selectedMinScoreValue.'"
  9567. />';
  9568. $return .= '</td>';
  9569. $return .= '<td>';
  9570. $return .= '<input
  9571. class="form-control"
  9572. size="4"
  9573. maxlength="3"
  9574. name="max_'.$item['id'].'"
  9575. type="number"
  9576. min="0"
  9577. step="1"
  9578. max="'.$item['max_score'].'"
  9579. value="'.$selectedMaxScoreValue.'"
  9580. />';
  9581. $return .= '</td>';
  9582. }
  9583. if ($item['item_type'] == TOOL_HOTPOTATOES) {
  9584. $return .= '<td>';
  9585. $return .= '<input
  9586. size="4"
  9587. maxlength="3"
  9588. name="min_'.$item['id'].'"
  9589. type="number"
  9590. min="0"
  9591. step="1"
  9592. max="'.$item['max_score'].'"
  9593. value="'.$selectedMinScoreValue.'"
  9594. />';
  9595. $return .= '</td>';
  9596. $return .= '<td>';
  9597. $return .= '<input
  9598. size="4"
  9599. maxlength="3"
  9600. name="max_'.$item['id'].'"
  9601. type="number"
  9602. min="0"
  9603. step="1"
  9604. max="'.$item['max_score'].'"
  9605. value="'.$selectedMaxScoreValue.'"
  9606. />';
  9607. $return .= '</td>';
  9608. }
  9609. $return .= '</tr>';
  9610. }
  9611. $return .= '<tr>';
  9612. $return .= '</tr>';
  9613. $return .= '</tbody>';
  9614. $return .= '</table>';
  9615. $return .= '</div>';
  9616. $return .= '<div class="form-group">';
  9617. $return .= '<button class="btn btn-primary" name="submit_button" type="submit">'.
  9618. get_lang('ModifyPrerequisites').'</button>';
  9619. $return .= '</form>';
  9620. return $return;
  9621. }
  9622. /**
  9623. * Return HTML list to allow prerequisites selection for lp.
  9624. *
  9625. * @return string HTML form
  9626. */
  9627. public function display_lp_prerequisites_list()
  9628. {
  9629. $course_id = api_get_course_int_id();
  9630. $lp_id = $this->lp_id;
  9631. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  9632. // get current prerequisite
  9633. $sql = "SELECT * FROM $tbl_lp WHERE iid = $lp_id ";
  9634. $result = Database::query($sql);
  9635. $row = Database::fetch_array($result);
  9636. $prerequisiteId = $row['prerequisite'];
  9637. $session_id = api_get_session_id();
  9638. $session_condition = api_get_session_condition($session_id, true, true);
  9639. $sql = "SELECT * FROM $tbl_lp
  9640. WHERE c_id = $course_id $session_condition
  9641. ORDER BY display_order ";
  9642. $rs = Database::query($sql);
  9643. $return = '';
  9644. $return .= '<select name="prerequisites" class="form-control">';
  9645. $return .= '<option value="0">'.get_lang('None').'</option>';
  9646. if (Database::num_rows($rs) > 0) {
  9647. while ($row = Database::fetch_array($rs)) {
  9648. if ($row['id'] == $lp_id) {
  9649. continue;
  9650. }
  9651. $return .= '<option value="'.$row['id'].'" '.(($row['id'] == $prerequisiteId) ? ' selected ' : '').'>'.$row['name'].'</option>';
  9652. }
  9653. }
  9654. $return .= '</select>';
  9655. return $return;
  9656. }
  9657. /**
  9658. * Creates a list with all the documents in it.
  9659. *
  9660. * @param bool $showInvisibleFiles
  9661. *
  9662. * @throws Exception
  9663. * @throws HTML_QuickForm_Error
  9664. *
  9665. * @return string
  9666. */
  9667. public function get_documents($showInvisibleFiles = false)
  9668. {
  9669. $course_info = api_get_course_info();
  9670. $sessionId = api_get_session_id();
  9671. $documentTree = DocumentManager::get_document_preview(
  9672. $course_info,
  9673. $this->lp_id,
  9674. null,
  9675. $sessionId,
  9676. true,
  9677. null,
  9678. null,
  9679. $showInvisibleFiles,
  9680. true
  9681. );
  9682. $headers = [
  9683. get_lang('Files'),
  9684. get_lang('CreateTheDocument'),
  9685. get_lang('CreateReadOutText'),
  9686. get_lang('Upload'),
  9687. ];
  9688. $form = new FormValidator(
  9689. 'form_upload',
  9690. 'POST',
  9691. $this->getCurrentBuildingModeURL(),
  9692. '',
  9693. ['enctype' => 'multipart/form-data']
  9694. );
  9695. $folders = DocumentManager::get_all_document_folders(
  9696. api_get_course_info(),
  9697. 0,
  9698. true
  9699. );
  9700. $lpPathInfo = $this->generate_lp_folder(api_get_course_info());
  9701. DocumentManager::build_directory_selector(
  9702. $folders,
  9703. $lpPathInfo['id'],
  9704. [],
  9705. true,
  9706. $form,
  9707. 'directory_parent_id'
  9708. );
  9709. $group = [
  9710. $form->createElement(
  9711. 'radio',
  9712. 'if_exists',
  9713. get_lang('UplWhatIfFileExists'),
  9714. get_lang('UplDoNothing'),
  9715. 'nothing'
  9716. ),
  9717. $form->createElement(
  9718. 'radio',
  9719. 'if_exists',
  9720. null,
  9721. get_lang('UplOverwriteLong'),
  9722. 'overwrite'
  9723. ),
  9724. $form->createElement(
  9725. 'radio',
  9726. 'if_exists',
  9727. null,
  9728. get_lang('UplRenameLong'),
  9729. 'rename'
  9730. ),
  9731. ];
  9732. $form->addGroup($group, null, get_lang('UplWhatIfFileExists'));
  9733. $fileExistsOption = api_get_setting('document_if_file_exists_option');
  9734. $defaultFileExistsOption = 'rename';
  9735. if (!empty($fileExistsOption)) {
  9736. $defaultFileExistsOption = $fileExistsOption;
  9737. }
  9738. $form->setDefaults(['if_exists' => $defaultFileExistsOption]);
  9739. // Check box options
  9740. $form->addElement(
  9741. 'checkbox',
  9742. 'unzip',
  9743. get_lang('Options'),
  9744. get_lang('Uncompress')
  9745. );
  9746. $url = api_get_path(WEB_AJAX_PATH).'document.ajax.php?'.api_get_cidreq().'&a=upload_file&curdirpath=';
  9747. $form->addMultipleUpload($url);
  9748. $new = $this->display_document_form('add', 0);
  9749. $frmReadOutText = $this->displayFrmReadOutText('add');
  9750. $tabs = Display::tabs(
  9751. $headers,
  9752. [$documentTree, $new, $frmReadOutText, $form->returnForm()],
  9753. 'subtab'
  9754. );
  9755. return $tabs;
  9756. }
  9757. /**
  9758. * Creates a list with all the exercises (quiz) in it.
  9759. *
  9760. * @return string
  9761. */
  9762. public function get_exercises()
  9763. {
  9764. $course_id = api_get_course_int_id();
  9765. $session_id = api_get_session_id();
  9766. $userInfo = api_get_user_info();
  9767. // New for hotpotatoes.
  9768. $uploadPath = DIR_HOTPOTATOES; //defined in main_api
  9769. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  9770. $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  9771. $condition_session = api_get_session_condition($session_id, true, true);
  9772. $setting = api_get_configuration_value('show_invisible_exercise_in_lp_list');
  9773. $activeCondition = ' active <> -1 ';
  9774. if ($setting) {
  9775. $activeCondition = ' active = 1 ';
  9776. }
  9777. $categoryCondition = '';
  9778. $categoryId = isset($_REQUEST['category_id']) ? (int) $_REQUEST['category_id'] : 0;
  9779. if (api_get_configuration_value('allow_exercise_categories') && !empty($categoryId)) {
  9780. $categoryCondition = " AND exercise_category_id = $categoryId ";
  9781. }
  9782. $keywordCondition = '';
  9783. $keyword = isset($_REQUEST['keyword']) ? $_REQUEST['keyword'] : '';
  9784. if (!empty($keyword)) {
  9785. $keyword = Database::escape_string($keyword);
  9786. $keywordCondition = " AND title LIKE '%$keyword%' ";
  9787. }
  9788. $sql_quiz = "SELECT * FROM $tbl_quiz
  9789. WHERE
  9790. c_id = $course_id AND
  9791. $activeCondition
  9792. $condition_session
  9793. $categoryCondition
  9794. $keywordCondition
  9795. ORDER BY title ASC";
  9796. $sql_hot = "SELECT * FROM $tbl_doc
  9797. WHERE
  9798. c_id = $course_id AND
  9799. path LIKE '".$uploadPath."/%/%htm%'
  9800. $condition_session
  9801. ORDER BY id ASC";
  9802. $res_quiz = Database::query($sql_quiz);
  9803. $res_hot = Database::query($sql_hot);
  9804. $currentUrl = api_get_self().'?'.api_get_cidreq().'&action=add_item&type=step&lp_id='.$this->lp_id.'#resource_tab-2';
  9805. // Create a search-box
  9806. $form = new FormValidator('search_simple', 'get', $currentUrl);
  9807. $form->addHidden('action', 'add_item');
  9808. $form->addHidden('type', 'step');
  9809. $form->addHidden('lp_id', $this->lp_id);
  9810. $form->addHidden('lp_build_selected', '2');
  9811. $form->addCourseHiddenParams();
  9812. $form->addText(
  9813. 'keyword',
  9814. get_lang('Search'),
  9815. false,
  9816. [
  9817. 'aria-label' => get_lang('Search'),
  9818. ]
  9819. );
  9820. if (api_get_configuration_value('allow_exercise_categories')) {
  9821. $manager = new ExerciseCategoryManager();
  9822. $options = $manager->getCategoriesForSelect(api_get_course_int_id());
  9823. if (!empty($options)) {
  9824. $form->addSelect(
  9825. 'category_id',
  9826. get_lang('Category'),
  9827. $options,
  9828. ['placeholder' => get_lang('SelectAnOption')]
  9829. );
  9830. }
  9831. }
  9832. $form->addButtonSearch(get_lang('Search'));
  9833. $return = $form->returnForm();
  9834. $return .= '<ul class="lp_resource">';
  9835. $return .= '<li class="lp_resource_element">';
  9836. $return .= Display::return_icon('new_exercice.png');
  9837. $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'exercise/exercise_admin.php?'.api_get_cidreq().'&lp_id='.$this->lp_id.'">'.
  9838. get_lang('NewExercise').'</a>';
  9839. $return .= '</li>';
  9840. $previewIcon = Display::return_icon(
  9841. 'preview_view.png',
  9842. get_lang('Preview')
  9843. );
  9844. $quizIcon = Display::return_icon('quiz.png', '', [], ICON_SIZE_TINY);
  9845. $moveIcon = Display::return_icon('move_everywhere.png', get_lang('Move'), [], ICON_SIZE_TINY);
  9846. $exerciseUrl = api_get_path(WEB_CODE_PATH).'exercise/showinframes.php?'.api_get_cidreq();
  9847. // Display hotpotatoes
  9848. while ($row_hot = Database::fetch_array($res_hot)) {
  9849. $link = Display::url(
  9850. $previewIcon,
  9851. $exerciseUrl.'&file='.$row_hot['path'],
  9852. ['target' => '_blank']
  9853. );
  9854. $return .= '<li class="lp_resource_element" data_id="'.$row_hot['id'].'" data_type="hotpotatoes" title="'.$row_hot['title'].'" >';
  9855. $return .= '<a class="moved" href="#">';
  9856. $return .= Display::return_icon(
  9857. 'move_everywhere.png',
  9858. get_lang('Move'),
  9859. [],
  9860. ICON_SIZE_TINY
  9861. );
  9862. $return .= '</a> ';
  9863. $return .= Display::return_icon('hotpotatoes_s.png');
  9864. $return .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_HOTPOTATOES.'&file='.$row_hot['id'].'&lp_id='.$this->lp_id.'">'.
  9865. ((!empty($row_hot['comment'])) ? $row_hot['comment'] : Security::remove_XSS($row_hot['title'])).$link.'</a>';
  9866. $return .= '</li>';
  9867. }
  9868. $exerciseUrl = api_get_path(WEB_CODE_PATH).'exercise/overview.php?'.api_get_cidreq();
  9869. while ($row_quiz = Database::fetch_array($res_quiz)) {
  9870. $title = strip_tags(
  9871. api_html_entity_decode($row_quiz['title'])
  9872. );
  9873. $visibility = api_get_item_visibility(
  9874. ['real_id' => $course_id],
  9875. TOOL_QUIZ,
  9876. $row_quiz['iid'],
  9877. $session_id
  9878. );
  9879. $link = Display::url(
  9880. $previewIcon,
  9881. $exerciseUrl.'&exerciseId='.$row_quiz['id'],
  9882. ['target' => '_blank']
  9883. );
  9884. $return .= '<li class="lp_resource_element" data_id="'.$row_quiz['id'].'" data_type="quiz" title="'.$title.'" >';
  9885. $return .= Display::url($moveIcon, '#', ['class' => 'moved']);
  9886. $return .= $quizIcon;
  9887. $sessionStar = api_get_session_image(
  9888. $row_quiz['session_id'],
  9889. $userInfo['status']
  9890. );
  9891. $return .= Display::url(
  9892. Security::remove_XSS(cut($title, 80)).$link.$sessionStar,
  9893. api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_QUIZ.'&file='.$row_quiz['id'].'&lp_id='.$this->lp_id,
  9894. [
  9895. 'class' => $visibility == 0 ? 'moved text-muted' : 'moved',
  9896. ]
  9897. );
  9898. $return .= '</li>';
  9899. }
  9900. $return .= '</ul>';
  9901. return $return;
  9902. }
  9903. /**
  9904. * Creates a list with all the links in it.
  9905. *
  9906. * @return string
  9907. */
  9908. public function get_links()
  9909. {
  9910. $selfUrl = api_get_self();
  9911. $courseIdReq = api_get_cidreq();
  9912. $course = api_get_course_info();
  9913. $userInfo = api_get_user_info();
  9914. $course_id = $course['real_id'];
  9915. $tbl_link = Database::get_course_table(TABLE_LINK);
  9916. $linkCategoryTable = Database::get_course_table(TABLE_LINK_CATEGORY);
  9917. $moveEverywhereIcon = Display::return_icon(
  9918. 'move_everywhere.png',
  9919. get_lang('Move'),
  9920. [],
  9921. ICON_SIZE_TINY
  9922. );
  9923. $session_id = api_get_session_id();
  9924. $condition_session = api_get_session_condition(
  9925. $session_id,
  9926. true,
  9927. true,
  9928. 'link.session_id'
  9929. );
  9930. $sql = "SELECT
  9931. link.id as link_id,
  9932. link.title as link_title,
  9933. link.session_id as link_session_id,
  9934. link.category_id as category_id,
  9935. link_category.category_title as category_title
  9936. FROM $tbl_link as link
  9937. LEFT JOIN $linkCategoryTable as link_category
  9938. ON (link.category_id = link_category.id AND link.c_id = link_category.c_id)
  9939. WHERE link.c_id = $course_id $condition_session
  9940. ORDER BY link_category.category_title ASC, link.title ASC";
  9941. $result = Database::query($sql);
  9942. $categorizedLinks = [];
  9943. $categories = [];
  9944. while ($link = Database::fetch_array($result)) {
  9945. if (!$link['category_id']) {
  9946. $link['category_title'] = get_lang('Uncategorized');
  9947. }
  9948. $categories[$link['category_id']] = $link['category_title'];
  9949. $categorizedLinks[$link['category_id']][$link['link_id']] = $link;
  9950. }
  9951. $linksHtmlCode =
  9952. '<script>
  9953. function toggle_tool(tool, id) {
  9954. if(document.getElementById(tool+"_"+id+"_content").style.display == "none"){
  9955. document.getElementById(tool+"_"+id+"_content").style.display = "block";
  9956. document.getElementById(tool+"_"+id+"_opener").src = "'.Display::returnIconPath('remove.gif').'";
  9957. } else {
  9958. document.getElementById(tool+"_"+id+"_content").style.display = "none";
  9959. document.getElementById(tool+"_"+id+"_opener").src = "'.Display::returnIconPath('add.gif').'";
  9960. }
  9961. }
  9962. </script>
  9963. <ul class="lp_resource">
  9964. <li class="lp_resource_element">
  9965. '.Display::return_icon('linksnew.gif').'
  9966. <a href="'.api_get_path(WEB_CODE_PATH).'link/link.php?'.$courseIdReq.'&action=addlink&lp_id='.$this->lp_id.'" title="'.get_lang('LinkAdd').'">'.
  9967. get_lang('LinkAdd').'
  9968. </a>
  9969. </li>';
  9970. foreach ($categorizedLinks as $categoryId => $links) {
  9971. $linkNodes = null;
  9972. foreach ($links as $key => $linkInfo) {
  9973. $title = $linkInfo['link_title'];
  9974. $linkSessionId = $linkInfo['link_session_id'];
  9975. $link = Display::url(
  9976. Display::return_icon('preview_view.png', get_lang('Preview')),
  9977. api_get_path(WEB_CODE_PATH).'link/link_goto.php?'.api_get_cidreq().'&link_id='.$key,
  9978. ['target' => '_blank']
  9979. );
  9980. if (api_get_item_visibility($course, TOOL_LINK, $key, $session_id) != 2) {
  9981. $sessionStar = api_get_session_image($linkSessionId, $userInfo['status']);
  9982. $linkNodes .=
  9983. '<li class="lp_resource_element" data_id="'.$key.'" data_type="'.TOOL_LINK.'" title="'.$title.'" >
  9984. <a class="moved" href="#">'.
  9985. $moveEverywhereIcon.
  9986. '</a>
  9987. '.Display::return_icon('links.png', '', [], ICON_SIZE_TINY).'
  9988. <a class="moved" href="'.$selfUrl.'?'.$courseIdReq.'&action=add_item&type='.
  9989. TOOL_LINK.'&file='.$key.'&lp_id='.$this->lp_id.'">'.
  9990. Security::remove_XSS($title).$sessionStar.$link.
  9991. '</a>
  9992. </li>';
  9993. }
  9994. }
  9995. $linksHtmlCode .=
  9996. '<li>
  9997. <a style="cursor:hand" onclick="javascript: toggle_tool(\''.TOOL_LINK.'\','.$categoryId.')" style="vertical-align:middle">
  9998. <img src="'.Display::returnIconPath('add.gif').'" id="'.TOOL_LINK.'_'.$categoryId.'_opener"
  9999. align="absbottom" />
  10000. </a>
  10001. <span style="vertical-align:middle">'.Security::remove_XSS($categories[$categoryId]).'</span>
  10002. </li>
  10003. <div style="display:none" id="'.TOOL_LINK.'_'.$categoryId.'_content">'.$linkNodes.'</div>';
  10004. }
  10005. $linksHtmlCode .= '</ul>';
  10006. return $linksHtmlCode;
  10007. }
  10008. /**
  10009. * Creates a list with all the student publications in it.
  10010. *
  10011. * @return string
  10012. */
  10013. public function get_student_publications()
  10014. {
  10015. $return = '<ul class="lp_resource">';
  10016. $return .= '<li class="lp_resource_element">';
  10017. $return .= Display::return_icon('works_new.gif');
  10018. $return .= ' <a href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_STUDENTPUBLICATION.'&lp_id='.$this->lp_id.'">'.
  10019. get_lang('AddAssignmentPage').'</a>';
  10020. $return .= '</li>';
  10021. require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
  10022. $works = getWorkListTeacher(0, 100, null, null, null);
  10023. if (!empty($works)) {
  10024. foreach ($works as $work) {
  10025. $link = Display::url(
  10026. Display::return_icon('preview_view.png', get_lang('Preview')),
  10027. api_get_path(WEB_CODE_PATH).'work/work_list_all.php?'.api_get_cidreq().'&id='.$work['iid'],
  10028. ['target' => '_blank']
  10029. );
  10030. $return .= '<li class="lp_resource_element" data_id="'.$work['iid'].'" data_type="'.TOOL_STUDENTPUBLICATION.'" title="'.Security::remove_XSS(cut(strip_tags($work['title']), 80)).'">';
  10031. $return .= '<a class="moved" href="#">';
  10032. $return .= Display::return_icon(
  10033. 'move_everywhere.png',
  10034. get_lang('Move'),
  10035. [],
  10036. ICON_SIZE_TINY
  10037. );
  10038. $return .= '</a> ';
  10039. $return .= Display::return_icon('works.png', '', [], ICON_SIZE_TINY);
  10040. $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.'">'.
  10041. Security::remove_XSS(cut(strip_tags($work['title']), 80)).' '.$link.'
  10042. </a>';
  10043. $return .= '</li>';
  10044. }
  10045. }
  10046. $return .= '</ul>';
  10047. return $return;
  10048. }
  10049. /**
  10050. * Creates a list with all the forums in it.
  10051. *
  10052. * @return string
  10053. */
  10054. public function get_forums()
  10055. {
  10056. require_once '../forum/forumfunction.inc.php';
  10057. $forumCategories = get_forum_categories();
  10058. $forumsInNoCategory = get_forums_in_category(0);
  10059. if (!empty($forumsInNoCategory)) {
  10060. $forumCategories = array_merge(
  10061. $forumCategories,
  10062. [
  10063. [
  10064. 'cat_id' => 0,
  10065. 'session_id' => 0,
  10066. 'visibility' => 1,
  10067. 'cat_comment' => null,
  10068. ],
  10069. ]
  10070. );
  10071. }
  10072. $forumList = get_forums();
  10073. $a_forums = [];
  10074. foreach ($forumCategories as $forumCategory) {
  10075. // The forums in this category.
  10076. $forumsInCategory = get_forums_in_category($forumCategory['cat_id']);
  10077. if (!empty($forumsInCategory)) {
  10078. foreach ($forumList as $forum) {
  10079. if (isset($forum['forum_category']) &&
  10080. $forum['forum_category'] == $forumCategory['cat_id']
  10081. ) {
  10082. $a_forums[] = $forum;
  10083. }
  10084. }
  10085. }
  10086. }
  10087. $return = '<ul class="lp_resource">';
  10088. // First add link
  10089. $return .= '<li class="lp_resource_element">';
  10090. $return .= Display::return_icon('new_forum.png');
  10091. $return .= Display::url(
  10092. get_lang('CreateANewForum'),
  10093. api_get_path(WEB_CODE_PATH).'forum/index.php?'.api_get_cidreq().'&'.http_build_query([
  10094. 'action' => 'add',
  10095. 'content' => 'forum',
  10096. 'lp_id' => $this->lp_id,
  10097. ]),
  10098. ['title' => get_lang('CreateANewForum')]
  10099. );
  10100. $return .= '</li>';
  10101. $return .= '<script>
  10102. function toggle_forum(forum_id) {
  10103. if (document.getElementById("forum_"+forum_id+"_content").style.display == "none") {
  10104. document.getElementById("forum_"+forum_id+"_content").style.display = "block";
  10105. document.getElementById("forum_"+forum_id+"_opener").src = "'.Display::returnIconPath('remove.gif').'";
  10106. } else {
  10107. document.getElementById("forum_"+forum_id+"_content").style.display = "none";
  10108. document.getElementById("forum_"+forum_id+"_opener").src = "'.Display::returnIconPath('add.gif').'";
  10109. }
  10110. }
  10111. </script>';
  10112. foreach ($a_forums as $forum) {
  10113. if (!empty($forum['forum_id'])) {
  10114. $link = Display::url(
  10115. Display::return_icon('preview_view.png', get_lang('Preview')),
  10116. api_get_path(WEB_CODE_PATH).'forum/viewforum.php?'.api_get_cidreq().'&forum='.$forum['forum_id'],
  10117. ['target' => '_blank']
  10118. );
  10119. $return .= '<li class="lp_resource_element" data_id="'.$forum['forum_id'].'" data_type="'.TOOL_FORUM.'" title="'.$forum['forum_title'].'" >';
  10120. $return .= '<a class="moved" href="#">';
  10121. $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), [], ICON_SIZE_TINY);
  10122. $return .= ' </a>';
  10123. $return .= Display::return_icon('forum.png', '', [], ICON_SIZE_TINY);
  10124. $return .= '<a onclick="javascript:toggle_forum('.$forum['forum_id'].');" style="cursor:hand; vertical-align:middle">
  10125. <img src="'.Display::returnIconPath('add.gif').'" id="forum_'.$forum['forum_id'].'_opener" align="absbottom" />
  10126. </a>
  10127. <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">'.
  10128. Security::remove_XSS($forum['forum_title']).' '.$link.'</a>';
  10129. $return .= '</li>';
  10130. $return .= '<div style="display:none" id="forum_'.$forum['forum_id'].'_content">';
  10131. $a_threads = get_threads($forum['forum_id']);
  10132. if (is_array($a_threads)) {
  10133. foreach ($a_threads as $thread) {
  10134. $link = Display::url(
  10135. Display::return_icon('preview_view.png', get_lang('Preview')),
  10136. api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.api_get_cidreq().'&forum='.$forum['forum_id'].'&thread='.$thread['thread_id'],
  10137. ['target' => '_blank']
  10138. );
  10139. $return .= '<li class="lp_resource_element" data_id="'.$thread['thread_id'].'" data_type="'.TOOL_THREAD.'" title="'.$thread['thread_title'].'" >';
  10140. $return .= '&nbsp;<a class="moved" href="#">';
  10141. $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), [], ICON_SIZE_TINY);
  10142. $return .= ' </a>';
  10143. $return .= Display::return_icon('forumthread.png', get_lang('Thread'), [], ICON_SIZE_TINY);
  10144. $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.'">'.
  10145. Security::remove_XSS($thread['thread_title']).' '.$link.'</a>';
  10146. $return .= '</li>';
  10147. }
  10148. }
  10149. $return .= '</div>';
  10150. }
  10151. }
  10152. $return .= '</ul>';
  10153. return $return;
  10154. }
  10155. /**
  10156. * // TODO: The output encoding should be equal to the system encoding.
  10157. *
  10158. * Exports the learning path as a SCORM package. This is the main function that
  10159. * gathers the content, transforms it, writes the imsmanifest.xml file, zips the
  10160. * whole thing and returns the zip.
  10161. *
  10162. * This method needs to be called in PHP5, as it will fail with non-adequate
  10163. * XML package (like the ones for PHP4), and it is *not* a static method, so
  10164. * you need to call it on a learnpath object.
  10165. *
  10166. * @TODO The method might be redefined later on in the scorm class itself to avoid
  10167. * creating a SCORM structure if there is one already. However, if the initial SCORM
  10168. * path has been modified, it should use the generic method here below.
  10169. *
  10170. * @return string Returns the zip package string, or null if error
  10171. */
  10172. public function scormExport()
  10173. {
  10174. api_set_more_memory_and_time_limits();
  10175. $_course = api_get_course_info();
  10176. $course_id = $_course['real_id'];
  10177. // Create the zip handler (this will remain available throughout the method).
  10178. $archivePath = api_get_path(SYS_ARCHIVE_PATH);
  10179. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  10180. $temp_dir_short = uniqid('scorm_export', true);
  10181. $temp_zip_dir = $archivePath.'/'.$temp_dir_short;
  10182. $temp_zip_file = $temp_zip_dir.'/'.md5(time()).'.zip';
  10183. $zip_folder = new PclZip($temp_zip_file);
  10184. $current_course_path = api_get_path(SYS_COURSE_PATH).api_get_course_path();
  10185. $root_path = $main_path = api_get_path(SYS_PATH);
  10186. $files_cleanup = [];
  10187. // Place to temporarily stash the zip file.
  10188. // create the temp dir if it doesn't exist
  10189. // or do a cleanup before creating the zip file.
  10190. if (!is_dir($temp_zip_dir)) {
  10191. mkdir($temp_zip_dir, api_get_permissions_for_new_directories());
  10192. } else {
  10193. // Cleanup: Check the temp dir for old files and delete them.
  10194. $handle = opendir($temp_zip_dir);
  10195. while (false !== ($file = readdir($handle))) {
  10196. if ($file != '.' && $file != '..') {
  10197. unlink("$temp_zip_dir/$file");
  10198. }
  10199. }
  10200. closedir($handle);
  10201. }
  10202. $zip_files = $zip_files_abs = $zip_files_dist = [];
  10203. if (is_dir($current_course_path.'/scorm/'.$this->path) &&
  10204. is_file($current_course_path.'/scorm/'.$this->path.'/imsmanifest.xml')
  10205. ) {
  10206. // Remove the possible . at the end of the path.
  10207. $dest_path_to_lp = substr($this->path, -1) == '.' ? substr($this->path, 0, -1) : $this->path;
  10208. $dest_path_to_scorm_folder = str_replace('//', '/', $temp_zip_dir.'/scorm/'.$dest_path_to_lp);
  10209. mkdir(
  10210. $dest_path_to_scorm_folder,
  10211. api_get_permissions_for_new_directories(),
  10212. true
  10213. );
  10214. copyr(
  10215. $current_course_path.'/scorm/'.$this->path,
  10216. $dest_path_to_scorm_folder,
  10217. ['imsmanifest'],
  10218. $zip_files
  10219. );
  10220. }
  10221. // Build a dummy imsmanifest structure.
  10222. // Do not add to the zip yet (we still need it).
  10223. // This structure is developed following regulations for SCORM 1.2 packaging in the SCORM 1.2 Content
  10224. // Aggregation Model official document, section "2.3 Content Packaging".
  10225. // We are going to build a UTF-8 encoded manifest.
  10226. // Later we will recode it to the desired (and supported) encoding.
  10227. $xmldoc = new DOMDocument('1.0');
  10228. $root = $xmldoc->createElement('manifest');
  10229. $root->setAttribute('identifier', 'SingleCourseManifest');
  10230. $root->setAttribute('version', '1.1');
  10231. $root->setAttribute('xmlns', 'http://www.imsproject.org/xsd/imscp_rootv1p1p2');
  10232. $root->setAttribute('xmlns:adlcp', 'http://www.adlnet.org/xsd/adlcp_rootv1p2');
  10233. $root->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
  10234. $root->setAttribute(
  10235. 'xsi:schemaLocation',
  10236. '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'
  10237. );
  10238. // Build mandatory sub-root container elements.
  10239. $metadata = $xmldoc->createElement('metadata');
  10240. $md_schema = $xmldoc->createElement('schema', 'ADL SCORM');
  10241. $metadata->appendChild($md_schema);
  10242. $md_schemaversion = $xmldoc->createElement('schemaversion', '1.2');
  10243. $metadata->appendChild($md_schemaversion);
  10244. $root->appendChild($metadata);
  10245. $organizations = $xmldoc->createElement('organizations');
  10246. $resources = $xmldoc->createElement('resources');
  10247. // Build the only organization we will use in building our learnpaths.
  10248. $organizations->setAttribute('default', 'chamilo_scorm_export');
  10249. $organization = $xmldoc->createElement('organization');
  10250. $organization->setAttribute('identifier', 'chamilo_scorm_export');
  10251. // To set the title of the SCORM entity (=organization), we take the name given
  10252. // in Chamilo and convert it to HTML entities using the Chamilo charset (not the
  10253. // learning path charset) as it is the encoding that defines how it is stored
  10254. // in the database. Then we convert it to HTML entities again as the "&" character
  10255. // alone is not authorized in XML (must be &amp;).
  10256. // The title is then decoded twice when extracting (see scorm::parse_manifest).
  10257. $org_title = $xmldoc->createElement('title', api_utf8_encode($this->get_name()));
  10258. $organization->appendChild($org_title);
  10259. $folder_name = 'document';
  10260. // Removes the learning_path/scorm_folder path when exporting see #4841
  10261. $path_to_remove = '';
  10262. $path_to_replace = '';
  10263. $result = $this->generate_lp_folder($_course);
  10264. if (isset($result['dir']) && strpos($result['dir'], 'learning_path')) {
  10265. $path_to_remove = 'document'.$result['dir'];
  10266. $path_to_replace = $folder_name.'/';
  10267. }
  10268. // Fixes chamilo scorm exports
  10269. if ($this->ref === 'chamilo_scorm_export') {
  10270. $path_to_remove = 'scorm/'.$this->path.'/document/';
  10271. }
  10272. // For each element, add it to the imsmanifest structure, then add it to the zip.
  10273. $link_updates = [];
  10274. $links_to_create = [];
  10275. foreach ($this->ordered_items as $index => $itemId) {
  10276. /** @var learnpathItem $item */
  10277. $item = $this->items[$itemId];
  10278. if (!in_array($item->type, [TOOL_QUIZ, TOOL_FORUM, TOOL_THREAD, TOOL_LINK, TOOL_STUDENTPUBLICATION])) {
  10279. // Get included documents from this item.
  10280. if ($item->type === 'sco') {
  10281. $inc_docs = $item->get_resources_from_source(
  10282. null,
  10283. $current_course_path.'/scorm/'.$this->path.'/'.$item->get_path()
  10284. );
  10285. } else {
  10286. $inc_docs = $item->get_resources_from_source();
  10287. }
  10288. // Give a child element <item> to the <organization> element.
  10289. $my_item_id = $item->get_id();
  10290. $my_item = $xmldoc->createElement('item');
  10291. $my_item->setAttribute('identifier', 'ITEM_'.$my_item_id);
  10292. $my_item->setAttribute('identifierref', 'RESOURCE_'.$my_item_id);
  10293. $my_item->setAttribute('isvisible', 'true');
  10294. // Give a child element <title> to the <item> element.
  10295. $my_title = $xmldoc->createElement(
  10296. 'title',
  10297. htmlspecialchars(
  10298. api_utf8_encode($item->get_title()),
  10299. ENT_QUOTES,
  10300. 'UTF-8'
  10301. )
  10302. );
  10303. $my_item->appendChild($my_title);
  10304. // Give a child element <adlcp:prerequisites> to the <item> element.
  10305. $my_prereqs = $xmldoc->createElement(
  10306. 'adlcp:prerequisites',
  10307. $this->get_scorm_prereq_string($my_item_id)
  10308. );
  10309. $my_prereqs->setAttribute('type', 'aicc_script');
  10310. $my_item->appendChild($my_prereqs);
  10311. // Give a child element <adlcp:maxtimeallowed> to the <item> element - not yet supported.
  10312. //$xmldoc->createElement('adlcp:maxtimeallowed','');
  10313. // Give a child element <adlcp:timelimitaction> to the <item> element - not yet supported.
  10314. //$xmldoc->createElement('adlcp:timelimitaction','');
  10315. // Give a child element <adlcp:datafromlms> to the <item> element - not yet supported.
  10316. //$xmldoc->createElement('adlcp:datafromlms','');
  10317. // Give a child element <adlcp:masteryscore> to the <item> element.
  10318. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  10319. $my_item->appendChild($my_masteryscore);
  10320. // Attach this item to the organization element or hits parent if there is one.
  10321. if (!empty($item->parent) && $item->parent != 0) {
  10322. $children = $organization->childNodes;
  10323. $possible_parent = $this->get_scorm_xml_node($children, 'ITEM_'.$item->parent);
  10324. if (is_object($possible_parent)) {
  10325. $possible_parent->appendChild($my_item);
  10326. } else {
  10327. if ($this->debug > 0) {
  10328. error_log('Parent ITEM_'.$item->parent.' of item ITEM_'.$my_item_id.' not found');
  10329. }
  10330. }
  10331. } else {
  10332. if ($this->debug > 0) {
  10333. error_log('No parent');
  10334. }
  10335. $organization->appendChild($my_item);
  10336. }
  10337. // Get the path of the file(s) from the course directory root.
  10338. $my_file_path = $item->get_file_path('scorm/'.$this->path.'/');
  10339. $my_xml_file_path = $my_file_path;
  10340. if (!empty($path_to_remove)) {
  10341. // From docs
  10342. $my_xml_file_path = str_replace($path_to_remove, $path_to_replace, $my_file_path);
  10343. // From quiz
  10344. if ($this->ref === 'chamilo_scorm_export') {
  10345. $path_to_remove = 'scorm/'.$this->path.'/';
  10346. $my_xml_file_path = str_replace($path_to_remove, '', $my_file_path);
  10347. }
  10348. }
  10349. $my_sub_dir = dirname($my_file_path);
  10350. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  10351. $my_xml_sub_dir = $my_sub_dir;
  10352. // Give a <resource> child to the <resources> element
  10353. $my_resource = $xmldoc->createElement('resource');
  10354. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  10355. $my_resource->setAttribute('type', 'webcontent');
  10356. $my_resource->setAttribute('href', $my_xml_file_path);
  10357. // adlcp:scormtype can be either 'sco' or 'asset'.
  10358. if ($item->type === 'sco') {
  10359. $my_resource->setAttribute('adlcp:scormtype', 'sco');
  10360. } else {
  10361. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  10362. }
  10363. // xml:base is the base directory to find the files declared in this resource.
  10364. $my_resource->setAttribute('xml:base', '');
  10365. // Give a <file> child to the <resource> element.
  10366. $my_file = $xmldoc->createElement('file');
  10367. $my_file->setAttribute('href', $my_xml_file_path);
  10368. $my_resource->appendChild($my_file);
  10369. // Dependency to other files - not yet supported.
  10370. $i = 1;
  10371. if ($inc_docs) {
  10372. foreach ($inc_docs as $doc_info) {
  10373. if (count($doc_info) < 1 || empty($doc_info[0])) {
  10374. continue;
  10375. }
  10376. $my_dep = $xmldoc->createElement('resource');
  10377. $res_id = 'RESOURCE_'.$item->get_id().'_'.$i;
  10378. $my_dep->setAttribute('identifier', $res_id);
  10379. $my_dep->setAttribute('type', 'webcontent');
  10380. $my_dep->setAttribute('adlcp:scormtype', 'asset');
  10381. $my_dep_file = $xmldoc->createElement('file');
  10382. // Check type of URL.
  10383. if ($doc_info[1] == 'remote') {
  10384. // Remote file. Save url as is.
  10385. $my_dep_file->setAttribute('href', $doc_info[0]);
  10386. $my_dep->setAttribute('xml:base', '');
  10387. } elseif ($doc_info[1] === 'local') {
  10388. switch ($doc_info[2]) {
  10389. case 'url':
  10390. // Local URL - save path as url for now, don't zip file.
  10391. $abs_path = api_get_path(SYS_PATH).
  10392. str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  10393. $current_dir = dirname($abs_path);
  10394. $current_dir = str_replace('\\', '/', $current_dir);
  10395. $file_path = realpath($abs_path);
  10396. $file_path = str_replace('\\', '/', $file_path);
  10397. $my_dep_file->setAttribute('href', $file_path);
  10398. $my_dep->setAttribute('xml:base', '');
  10399. if (strstr($file_path, $main_path) !== false) {
  10400. // The calculated real path is really inside Chamilo's root path.
  10401. // Reduce file path to what's under the DocumentRoot.
  10402. $replace = $file_path;
  10403. $file_path = substr($file_path, strlen($root_path) - 1);
  10404. $destinationFile = $file_path;
  10405. if (strstr($file_path, 'upload/users') !== false) {
  10406. $pos = strpos($file_path, 'my_files/');
  10407. if ($pos !== false) {
  10408. $onlyDirectory = str_replace(
  10409. 'upload/users/',
  10410. '',
  10411. substr($file_path, $pos, strlen($file_path))
  10412. );
  10413. }
  10414. $replace = $onlyDirectory;
  10415. $destinationFile = $replace;
  10416. }
  10417. $zip_files_abs[] = $file_path;
  10418. $link_updates[$my_file_path][] = [
  10419. 'orig' => $doc_info[0],
  10420. 'dest' => $destinationFile,
  10421. 'replace' => $replace,
  10422. ];
  10423. $my_dep_file->setAttribute('href', $file_path);
  10424. $my_dep->setAttribute('xml:base', '');
  10425. } elseif (empty($file_path)) {
  10426. $file_path = $_SERVER['DOCUMENT_ROOT'].$abs_path;
  10427. $file_path = str_replace('//', '/', $file_path);
  10428. if (file_exists($file_path)) {
  10429. // We get the relative path.
  10430. $file_path = substr($file_path, strlen($current_dir));
  10431. $zip_files[] = $my_sub_dir.'/'.$file_path;
  10432. $link_updates[$my_file_path][] = [
  10433. 'orig' => $doc_info[0],
  10434. 'dest' => $file_path,
  10435. ];
  10436. $my_dep_file->setAttribute('href', $file_path);
  10437. $my_dep->setAttribute('xml:base', '');
  10438. }
  10439. }
  10440. break;
  10441. case 'abs':
  10442. // Absolute path from DocumentRoot. Save file and leave path as is in the zip.
  10443. $my_dep_file->setAttribute('href', $doc_info[0]);
  10444. $my_dep->setAttribute('xml:base', '');
  10445. // The next lines fix a bug when using the "subdir" mode of Chamilo, whereas
  10446. // an image path would be constructed as /var/www/subdir/subdir/img/foo.bar
  10447. $abs_img_path_without_subdir = $doc_info[0];
  10448. $relp = api_get_path(REL_PATH); // The url-append config param.
  10449. $pos = strpos($abs_img_path_without_subdir, $relp);
  10450. if ($pos === 0) {
  10451. $abs_img_path_without_subdir = trim('/'.substr($abs_img_path_without_subdir, strlen($relp)));
  10452. }
  10453. $file_path = realpath(api_get_path(SYS_APP_PATH).$abs_img_path_without_subdir);
  10454. $file_path = str_replace(['\\', '//'], '/', $file_path);
  10455. // Prepare the current directory path (until just under 'document') with a trailing slash.
  10456. $cur_path = substr($current_course_path, -1) == '/' ? $current_course_path : $current_course_path.'/';
  10457. // Check if the current document is in that path.
  10458. if (strstr($file_path, $cur_path) !== false) {
  10459. $destinationFile = substr($file_path, strlen($cur_path));
  10460. $filePathNoCoursePart = substr($file_path, strlen($cur_path));
  10461. $fileToTest = $cur_path.$my_file_path;
  10462. if (!empty($path_to_remove)) {
  10463. $fileToTest = str_replace(
  10464. $path_to_remove.'/',
  10465. $path_to_replace,
  10466. $cur_path.$my_file_path
  10467. );
  10468. }
  10469. $relative_path = api_get_relative_path($fileToTest, $file_path);
  10470. // Put the current document in the zip (this array is the array
  10471. // that will manage documents already in the course folder - relative).
  10472. $zip_files[] = $filePathNoCoursePart;
  10473. // Update the links to the current document in the
  10474. // containing document (make them relative).
  10475. $link_updates[$my_file_path][] = [
  10476. 'orig' => $doc_info[0],
  10477. 'dest' => $destinationFile,
  10478. 'replace' => $relative_path,
  10479. ];
  10480. $my_dep_file->setAttribute('href', $file_path);
  10481. $my_dep->setAttribute('xml:base', '');
  10482. } elseif (strstr($file_path, $main_path) !== false) {
  10483. // The calculated real path is really inside Chamilo's root path.
  10484. // Reduce file path to what's under the DocumentRoot.
  10485. $file_path = substr($file_path, strlen($root_path));
  10486. $zip_files_abs[] = $file_path;
  10487. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => $file_path];
  10488. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10489. $my_dep->setAttribute('xml:base', '');
  10490. } elseif (empty($file_path)) {
  10491. // Probably this is an image inside "/main" directory
  10492. $file_path = api_get_path(SYS_PATH).$abs_img_path_without_subdir;
  10493. $abs_path = api_get_path(SYS_PATH).str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  10494. if (file_exists($file_path)) {
  10495. if (strstr($file_path, 'main/default_course_document') !== false) {
  10496. // We get the relative path.
  10497. $pos = strpos($file_path, 'main/default_course_document/');
  10498. if ($pos !== false) {
  10499. $onlyDirectory = str_replace(
  10500. 'main/default_course_document/',
  10501. '',
  10502. substr($file_path, $pos, strlen($file_path))
  10503. );
  10504. }
  10505. $destinationFile = 'default_course_document/'.$onlyDirectory;
  10506. $fileAbs = substr($file_path, strlen(api_get_path(SYS_PATH)));
  10507. $zip_files_abs[] = $fileAbs;
  10508. $link_updates[$my_file_path][] = [
  10509. 'orig' => $doc_info[0],
  10510. 'dest' => $destinationFile,
  10511. ];
  10512. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10513. $my_dep->setAttribute('xml:base', '');
  10514. }
  10515. }
  10516. }
  10517. break;
  10518. case 'rel':
  10519. // Path relative to the current document.
  10520. // Save xml:base as current document's directory and save file in zip as subdir.file_path
  10521. if (substr($doc_info[0], 0, 2) === '..') {
  10522. // Relative path going up.
  10523. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  10524. $current_dir = str_replace('\\', '/', $current_dir);
  10525. $file_path = realpath($current_dir.$doc_info[0]);
  10526. $file_path = str_replace('\\', '/', $file_path);
  10527. if (strstr($file_path, $main_path) !== false) {
  10528. // The calculated real path is really inside Chamilo's root path.
  10529. // Reduce file path to what's under the DocumentRoot.
  10530. $file_path = substr($file_path, strlen($root_path));
  10531. $zip_files_abs[] = $file_path;
  10532. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => $file_path];
  10533. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10534. $my_dep->setAttribute('xml:base', '');
  10535. }
  10536. } else {
  10537. $zip_files[] = $my_sub_dir.'/'.$doc_info[0];
  10538. $my_dep_file->setAttribute('href', $doc_info[0]);
  10539. $my_dep->setAttribute('xml:base', $my_xml_sub_dir);
  10540. }
  10541. break;
  10542. default:
  10543. $my_dep_file->setAttribute('href', $doc_info[0]);
  10544. $my_dep->setAttribute('xml:base', '');
  10545. break;
  10546. }
  10547. }
  10548. $my_dep->appendChild($my_dep_file);
  10549. $resources->appendChild($my_dep);
  10550. $dependency = $xmldoc->createElement('dependency');
  10551. $dependency->setAttribute('identifierref', $res_id);
  10552. $my_resource->appendChild($dependency);
  10553. $i++;
  10554. }
  10555. }
  10556. $resources->appendChild($my_resource);
  10557. $zip_files[] = $my_file_path;
  10558. } else {
  10559. // If the item is a quiz or a link or whatever non-exportable, we include a step indicating it.
  10560. switch ($item->type) {
  10561. case TOOL_LINK:
  10562. $my_item = $xmldoc->createElement('item');
  10563. $my_item->setAttribute('identifier', 'ITEM_'.$item->get_id());
  10564. $my_item->setAttribute('identifierref', 'RESOURCE_'.$item->get_id());
  10565. $my_item->setAttribute('isvisible', 'true');
  10566. // Give a child element <title> to the <item> element.
  10567. $my_title = $xmldoc->createElement(
  10568. 'title',
  10569. htmlspecialchars(
  10570. api_utf8_encode($item->get_title()),
  10571. ENT_QUOTES,
  10572. 'UTF-8'
  10573. )
  10574. );
  10575. $my_item->appendChild($my_title);
  10576. // Give a child element <adlcp:prerequisites> to the <item> element.
  10577. $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $item->get_prereq_string());
  10578. $my_prereqs->setAttribute('type', 'aicc_script');
  10579. $my_item->appendChild($my_prereqs);
  10580. // Give a child element <adlcp:maxtimeallowed> to the <item> element - not yet supported.
  10581. //$xmldoc->createElement('adlcp:maxtimeallowed', '');
  10582. // Give a child element <adlcp:timelimitaction> to the <item> element - not yet supported.
  10583. //$xmldoc->createElement('adlcp:timelimitaction', '');
  10584. // Give a child element <adlcp:datafromlms> to the <item> element - not yet supported.
  10585. //$xmldoc->createElement('adlcp:datafromlms', '');
  10586. // Give a child element <adlcp:masteryscore> to the <item> element.
  10587. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  10588. $my_item->appendChild($my_masteryscore);
  10589. // Attach this item to the organization element or its parent if there is one.
  10590. if (!empty($item->parent) && $item->parent != 0) {
  10591. $children = $organization->childNodes;
  10592. for ($i = 0; $i < $children->length; $i++) {
  10593. $item_temp = $children->item($i);
  10594. if ($item_temp->nodeName == 'item') {
  10595. if ($item_temp->getAttribute('identifier') == 'ITEM_'.$item->parent) {
  10596. $item_temp->appendChild($my_item);
  10597. }
  10598. }
  10599. }
  10600. } else {
  10601. $organization->appendChild($my_item);
  10602. }
  10603. $my_file_path = 'link_'.$item->get_id().'.html';
  10604. $sql = 'SELECT url, title FROM '.Database::get_course_table(TABLE_LINK).'
  10605. WHERE c_id = '.$course_id.' AND id = '.$item->path;
  10606. $rs = Database::query($sql);
  10607. if ($link = Database::fetch_array($rs)) {
  10608. $url = $link['url'];
  10609. $title = stripslashes($link['title']);
  10610. $links_to_create[$my_file_path] = ['title' => $title, 'url' => $url];
  10611. $my_xml_file_path = $my_file_path;
  10612. $my_sub_dir = dirname($my_file_path);
  10613. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  10614. $my_xml_sub_dir = $my_sub_dir;
  10615. // Give a <resource> child to the <resources> element.
  10616. $my_resource = $xmldoc->createElement('resource');
  10617. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  10618. $my_resource->setAttribute('type', 'webcontent');
  10619. $my_resource->setAttribute('href', $my_xml_file_path);
  10620. // adlcp:scormtype can be either 'sco' or 'asset'.
  10621. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  10622. // xml:base is the base directory to find the files declared in this resource.
  10623. $my_resource->setAttribute('xml:base', '');
  10624. // give a <file> child to the <resource> element.
  10625. $my_file = $xmldoc->createElement('file');
  10626. $my_file->setAttribute('href', $my_xml_file_path);
  10627. $my_resource->appendChild($my_file);
  10628. $resources->appendChild($my_resource);
  10629. }
  10630. break;
  10631. case TOOL_QUIZ:
  10632. $exe_id = $item->path;
  10633. // Should be using ref when everything will be cleaned up in this regard.
  10634. $exe = new Exercise();
  10635. $exe->read($exe_id);
  10636. $my_item = $xmldoc->createElement('item');
  10637. $my_item->setAttribute('identifier', 'ITEM_'.$item->get_id());
  10638. $my_item->setAttribute('identifierref', 'RESOURCE_'.$item->get_id());
  10639. $my_item->setAttribute('isvisible', 'true');
  10640. // Give a child element <title> to the <item> element.
  10641. $my_title = $xmldoc->createElement(
  10642. 'title',
  10643. htmlspecialchars(
  10644. api_utf8_encode($item->get_title()),
  10645. ENT_QUOTES,
  10646. 'UTF-8'
  10647. )
  10648. );
  10649. $my_item->appendChild($my_title);
  10650. $my_max_score = $xmldoc->createElement('max_score', $item->get_max());
  10651. $my_item->appendChild($my_max_score);
  10652. // Give a child element <adlcp:prerequisites> to the <item> element.
  10653. $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $item->get_prereq_string());
  10654. $my_prereqs->setAttribute('type', 'aicc_script');
  10655. $my_item->appendChild($my_prereqs);
  10656. // Give a child element <adlcp:masteryscore> to the <item> element.
  10657. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  10658. $my_item->appendChild($my_masteryscore);
  10659. // Attach this item to the organization element or hits parent if there is one.
  10660. if (!empty($item->parent) && $item->parent != 0) {
  10661. $children = $organization->childNodes;
  10662. $possible_parent = $this->get_scorm_xml_node($children, 'ITEM_'.$item->parent);
  10663. if ($possible_parent) {
  10664. if ($possible_parent->getAttribute('identifier') === 'ITEM_'.$item->parent) {
  10665. $possible_parent->appendChild($my_item);
  10666. }
  10667. }
  10668. } else {
  10669. $organization->appendChild($my_item);
  10670. }
  10671. // Get the path of the file(s) from the course directory root
  10672. //$my_file_path = $item->get_file_path('scorm/'.$this->path.'/');
  10673. $my_file_path = 'quiz_'.$item->get_id().'.html';
  10674. // Write the contents of the exported exercise into a (big) html file
  10675. // to later pack it into the exported SCORM. The file will be removed afterwards.
  10676. $scormExercise = new ScormExercise($exe, true);
  10677. $contents = $scormExercise->export();
  10678. $tmp_file_path = $archivePath.$temp_dir_short.'/'.$my_file_path;
  10679. $res = file_put_contents($tmp_file_path, $contents);
  10680. if ($res === false) {
  10681. error_log('Could not write into file '.$tmp_file_path.' '.__FILE__.' '.__LINE__, 0);
  10682. }
  10683. $files_cleanup[] = $tmp_file_path;
  10684. $my_xml_file_path = $my_file_path;
  10685. $my_sub_dir = dirname($my_file_path);
  10686. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  10687. $my_xml_sub_dir = $my_sub_dir;
  10688. // Give a <resource> child to the <resources> element.
  10689. $my_resource = $xmldoc->createElement('resource');
  10690. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  10691. $my_resource->setAttribute('type', 'webcontent');
  10692. $my_resource->setAttribute('href', $my_xml_file_path);
  10693. // adlcp:scormtype can be either 'sco' or 'asset'.
  10694. $my_resource->setAttribute('adlcp:scormtype', 'sco');
  10695. // xml:base is the base directory to find the files declared in this resource.
  10696. $my_resource->setAttribute('xml:base', '');
  10697. // Give a <file> child to the <resource> element.
  10698. $my_file = $xmldoc->createElement('file');
  10699. $my_file->setAttribute('href', $my_xml_file_path);
  10700. $my_resource->appendChild($my_file);
  10701. // Get included docs.
  10702. $inc_docs = $item->get_resources_from_source(null, $tmp_file_path);
  10703. // Dependency to other files - not yet supported.
  10704. $i = 1;
  10705. foreach ($inc_docs as $doc_info) {
  10706. if (count($doc_info) < 1 || empty($doc_info[0])) {
  10707. continue;
  10708. }
  10709. $my_dep = $xmldoc->createElement('resource');
  10710. $res_id = 'RESOURCE_'.$item->get_id().'_'.$i;
  10711. $my_dep->setAttribute('identifier', $res_id);
  10712. $my_dep->setAttribute('type', 'webcontent');
  10713. $my_dep->setAttribute('adlcp:scormtype', 'asset');
  10714. $my_dep_file = $xmldoc->createElement('file');
  10715. // Check type of URL.
  10716. if ($doc_info[1] == 'remote') {
  10717. // Remote file. Save url as is.
  10718. $my_dep_file->setAttribute('href', $doc_info[0]);
  10719. $my_dep->setAttribute('xml:base', '');
  10720. } elseif ($doc_info[1] == 'local') {
  10721. switch ($doc_info[2]) {
  10722. case 'url': // Local URL - save path as url for now, don't zip file.
  10723. // Save file but as local file (retrieve from URL).
  10724. $abs_path = api_get_path(SYS_PATH).
  10725. str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  10726. $current_dir = dirname($abs_path);
  10727. $current_dir = str_replace('\\', '/', $current_dir);
  10728. $file_path = realpath($abs_path);
  10729. $file_path = str_replace('\\', '/', $file_path);
  10730. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10731. $my_dep->setAttribute('xml:base', '');
  10732. if (strstr($file_path, $main_path) !== false) {
  10733. // The calculated real path is really inside the chamilo root path.
  10734. // Reduce file path to what's under the DocumentRoot.
  10735. $file_path = substr($file_path, strlen($root_path));
  10736. $zip_files_abs[] = $file_path;
  10737. $link_updates[$my_file_path][] = [
  10738. 'orig' => $doc_info[0],
  10739. 'dest' => 'document/'.$file_path,
  10740. ];
  10741. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10742. $my_dep->setAttribute('xml:base', '');
  10743. } elseif (empty($file_path)) {
  10744. $file_path = $_SERVER['DOCUMENT_ROOT'].$abs_path;
  10745. $file_path = str_replace('//', '/', $file_path);
  10746. if (file_exists($file_path)) {
  10747. $file_path = substr($file_path, strlen($current_dir));
  10748. // We get the relative path.
  10749. $zip_files[] = $my_sub_dir.'/'.$file_path;
  10750. $link_updates[$my_file_path][] = [
  10751. 'orig' => $doc_info[0],
  10752. 'dest' => 'document/'.$file_path,
  10753. ];
  10754. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10755. $my_dep->setAttribute('xml:base', '');
  10756. }
  10757. }
  10758. break;
  10759. case 'abs':
  10760. // Absolute path from DocumentRoot. Save file and leave path as is in the zip.
  10761. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  10762. $current_dir = str_replace('\\', '/', $current_dir);
  10763. $file_path = realpath($doc_info[0]);
  10764. $file_path = str_replace('\\', '/', $file_path);
  10765. $my_dep_file->setAttribute('href', $file_path);
  10766. $my_dep->setAttribute('xml:base', '');
  10767. if (strstr($file_path, $main_path) !== false) {
  10768. // The calculated real path is really inside the chamilo root path.
  10769. // Reduce file path to what's under the DocumentRoot.
  10770. $file_path = substr($file_path, strlen($root_path));
  10771. $zip_files_abs[] = $file_path;
  10772. $link_updates[$my_file_path][] = [
  10773. 'orig' => $doc_info[0],
  10774. 'dest' => $file_path,
  10775. ];
  10776. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10777. $my_dep->setAttribute('xml:base', '');
  10778. } elseif (empty($file_path)) {
  10779. $docSysPartPath = str_replace(
  10780. api_get_path(REL_COURSE_PATH),
  10781. '',
  10782. $doc_info[0]
  10783. );
  10784. $docSysPartPathNoCourseCode = str_replace(
  10785. $_course['directory'].'/',
  10786. '',
  10787. $docSysPartPath
  10788. );
  10789. $docSysPath = api_get_path(SYS_COURSE_PATH).$docSysPartPath;
  10790. if (file_exists($docSysPath)) {
  10791. $file_path = $docSysPartPathNoCourseCode;
  10792. $zip_files[] = $my_sub_dir.'/'.$file_path;
  10793. $link_updates[$my_file_path][] = [
  10794. 'orig' => $doc_info[0],
  10795. 'dest' => $file_path,
  10796. ];
  10797. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10798. $my_dep->setAttribute('xml:base', '');
  10799. }
  10800. }
  10801. break;
  10802. case 'rel':
  10803. // Path relative to the current document. Save xml:base as current document's
  10804. // directory and save file in zip as subdir.file_path
  10805. if (substr($doc_info[0], 0, 2) === '..') {
  10806. // Relative path going up.
  10807. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  10808. $current_dir = str_replace('\\', '/', $current_dir);
  10809. $file_path = realpath($current_dir.$doc_info[0]);
  10810. $file_path = str_replace('\\', '/', $file_path);
  10811. //error_log($file_path.' <-> '.$main_path, 0);
  10812. if (strstr($file_path, $main_path) !== false) {
  10813. // The calculated real path is really inside Chamilo's root path.
  10814. // Reduce file path to what's under the DocumentRoot.
  10815. $file_path = substr($file_path, strlen($root_path));
  10816. $file_path_dest = $file_path;
  10817. // File path is courses/CHAMILO/document/....
  10818. $info_file_path = explode('/', $file_path);
  10819. if ($info_file_path[0] == 'courses') {
  10820. // Add character "/" in file path.
  10821. $file_path_dest = 'document/'.$file_path;
  10822. }
  10823. $zip_files_abs[] = $file_path;
  10824. $link_updates[$my_file_path][] = [
  10825. 'orig' => $doc_info[0],
  10826. 'dest' => $file_path_dest,
  10827. ];
  10828. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10829. $my_dep->setAttribute('xml:base', '');
  10830. }
  10831. } else {
  10832. $zip_files[] = $my_sub_dir.'/'.$doc_info[0];
  10833. $my_dep_file->setAttribute('href', $doc_info[0]);
  10834. $my_dep->setAttribute('xml:base', $my_xml_sub_dir);
  10835. }
  10836. break;
  10837. default:
  10838. $my_dep_file->setAttribute('href', $doc_info[0]); // ../../courses/
  10839. $my_dep->setAttribute('xml:base', '');
  10840. break;
  10841. }
  10842. }
  10843. $my_dep->appendChild($my_dep_file);
  10844. $resources->appendChild($my_dep);
  10845. $dependency = $xmldoc->createElement('dependency');
  10846. $dependency->setAttribute('identifierref', $res_id);
  10847. $my_resource->appendChild($dependency);
  10848. $i++;
  10849. }
  10850. $resources->appendChild($my_resource);
  10851. $zip_files[] = $my_file_path;
  10852. break;
  10853. default:
  10854. // Get the path of the file(s) from the course directory root
  10855. $my_file_path = 'non_exportable.html';
  10856. //$my_xml_file_path = api_htmlentities(api_utf8_encode($my_file_path), ENT_COMPAT, 'UTF-8');
  10857. $my_xml_file_path = $my_file_path;
  10858. $my_sub_dir = dirname($my_file_path);
  10859. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  10860. //$my_xml_sub_dir = api_htmlentities(api_utf8_encode($my_sub_dir), ENT_COMPAT, 'UTF-8');
  10861. $my_xml_sub_dir = $my_sub_dir;
  10862. // Give a <resource> child to the <resources> element.
  10863. $my_resource = $xmldoc->createElement('resource');
  10864. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  10865. $my_resource->setAttribute('type', 'webcontent');
  10866. $my_resource->setAttribute('href', $folder_name.'/'.$my_xml_file_path);
  10867. // adlcp:scormtype can be either 'sco' or 'asset'.
  10868. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  10869. // xml:base is the base directory to find the files declared in this resource.
  10870. $my_resource->setAttribute('xml:base', '');
  10871. // Give a <file> child to the <resource> element.
  10872. $my_file = $xmldoc->createElement('file');
  10873. $my_file->setAttribute('href', 'document/'.$my_xml_file_path);
  10874. $my_resource->appendChild($my_file);
  10875. $resources->appendChild($my_resource);
  10876. break;
  10877. }
  10878. }
  10879. }
  10880. $organizations->appendChild($organization);
  10881. $root->appendChild($organizations);
  10882. $root->appendChild($resources);
  10883. $xmldoc->appendChild($root);
  10884. $copyAll = api_get_configuration_value('add_all_files_in_lp_export');
  10885. // then add the file to the zip, then destroy the file (this is done automatically).
  10886. // http://www.reload.ac.uk/scormplayer.html - once done, don't forget to close FS#138
  10887. foreach ($zip_files as $file_path) {
  10888. if (empty($file_path)) {
  10889. continue;
  10890. }
  10891. $filePath = $sys_course_path.$_course['path'].'/'.$file_path;
  10892. $dest_file = $archivePath.$temp_dir_short.'/'.$file_path;
  10893. if (!empty($path_to_remove) && !empty($path_to_replace)) {
  10894. $dest_file = str_replace($path_to_remove, $path_to_replace, $dest_file);
  10895. }
  10896. $this->create_path($dest_file);
  10897. @copy($filePath, $dest_file);
  10898. // Check if the file needs a link update.
  10899. if (in_array($file_path, array_keys($link_updates))) {
  10900. $string = file_get_contents($dest_file);
  10901. unlink($dest_file);
  10902. foreach ($link_updates[$file_path] as $old_new) {
  10903. // This is an ugly hack that allows .flv files to be found by the flv player that
  10904. // will be added in document/main/inc/lib/flv_player/flv_player.swf and that needs
  10905. // to find the flv to play in document/main/, so we replace main/ in the flv path by
  10906. // ../../.. to return from inc/lib/flv_player to the document/main path.
  10907. if (substr($old_new['dest'], -3) === 'flv' &&
  10908. substr($old_new['dest'], 0, 5) === 'main/'
  10909. ) {
  10910. $old_new['dest'] = str_replace('main/', '../../../', $old_new['dest']);
  10911. } elseif (substr($old_new['dest'], -3) === 'flv' &&
  10912. substr($old_new['dest'], 0, 6) === 'video/'
  10913. ) {
  10914. $old_new['dest'] = str_replace('video/', '../../../../video/', $old_new['dest']);
  10915. }
  10916. // Fix to avoid problems with default_course_document
  10917. if (strpos('main/default_course_document', $old_new['dest']) === false) {
  10918. $newDestination = $old_new['dest'];
  10919. if (isset($old_new['replace']) && !empty($old_new['replace'])) {
  10920. $newDestination = $old_new['replace'];
  10921. }
  10922. } else {
  10923. $newDestination = str_replace('document/', '', $old_new['dest']);
  10924. }
  10925. $string = str_replace($old_new['orig'], $newDestination, $string);
  10926. // Add files inside the HTMLs
  10927. $new_path = str_replace(api_get_path(REL_COURSE_PATH), '', $old_new['orig']);
  10928. $destinationFile = $archivePath.$temp_dir_short.'/'.$old_new['dest'];
  10929. if (file_exists($sys_course_path.$new_path) && is_file($sys_course_path.$new_path)) {
  10930. copy(
  10931. $sys_course_path.$new_path,
  10932. $destinationFile
  10933. );
  10934. }
  10935. }
  10936. file_put_contents($dest_file, $string);
  10937. }
  10938. if (file_exists($filePath) && $copyAll) {
  10939. $extension = $this->get_extension($filePath);
  10940. if (in_array($extension, ['html', 'html'])) {
  10941. $containerOrigin = dirname($filePath);
  10942. $containerDestination = dirname($dest_file);
  10943. $finder = new Finder();
  10944. $finder->files()->in($containerOrigin)
  10945. ->notName('*_DELETED_*')
  10946. ->exclude('share_folder')
  10947. ->exclude('chat_files')
  10948. ->exclude('certificates')
  10949. ;
  10950. if (is_dir($containerOrigin) &&
  10951. is_dir($containerDestination)
  10952. ) {
  10953. $fs = new Filesystem();
  10954. $fs->mirror(
  10955. $containerOrigin,
  10956. $containerDestination,
  10957. $finder
  10958. );
  10959. }
  10960. }
  10961. }
  10962. }
  10963. foreach ($zip_files_abs as $file_path) {
  10964. if (empty($file_path)) {
  10965. continue;
  10966. }
  10967. if (!is_file($main_path.$file_path) || !is_readable($main_path.$file_path)) {
  10968. continue;
  10969. }
  10970. $dest_file = $archivePath.$temp_dir_short.'/document/'.$file_path;
  10971. if (strstr($file_path, 'upload/users') !== false) {
  10972. $pos = strpos($file_path, 'my_files/');
  10973. if ($pos !== false) {
  10974. $onlyDirectory = str_replace(
  10975. 'upload/users/',
  10976. '',
  10977. substr($file_path, $pos, strlen($file_path))
  10978. );
  10979. $dest_file = $archivePath.$temp_dir_short.'/document/'.$onlyDirectory;
  10980. }
  10981. }
  10982. if (strstr($file_path, 'default_course_document/') !== false) {
  10983. $replace = str_replace('/main', '', $file_path);
  10984. $dest_file = $archivePath.$temp_dir_short.'/document/'.$replace;
  10985. }
  10986. if (empty($dest_file)) {
  10987. continue;
  10988. }
  10989. $this->create_path($dest_file);
  10990. copy($main_path.$file_path, $dest_file);
  10991. // Check if the file needs a link update.
  10992. if (in_array($file_path, array_keys($link_updates))) {
  10993. $string = file_get_contents($dest_file);
  10994. unlink($dest_file);
  10995. foreach ($link_updates[$file_path] as $old_new) {
  10996. // This is an ugly hack that allows .flv files to be found by the flv player that
  10997. // will be added in document/main/inc/lib/flv_player/flv_player.swf and that needs
  10998. // to find the flv to play in document/main/, so we replace main/ in the flv path by
  10999. // ../../.. to return from inc/lib/flv_player to the document/main path.
  11000. if (substr($old_new['dest'], -3) == 'flv' &&
  11001. substr($old_new['dest'], 0, 5) == 'main/'
  11002. ) {
  11003. $old_new['dest'] = str_replace('main/', '../../../', $old_new['dest']);
  11004. }
  11005. $string = str_replace($old_new['orig'], $old_new['dest'], $string);
  11006. }
  11007. file_put_contents($dest_file, $string);
  11008. }
  11009. }
  11010. if (is_array($links_to_create)) {
  11011. foreach ($links_to_create as $file => $link) {
  11012. $content = '<!DOCTYPE html><head>
  11013. <meta charset="'.api_get_language_isocode().'" />
  11014. <title>'.$link['title'].'</title>
  11015. </head>
  11016. <body dir="'.api_get_text_direction().'">
  11017. <div style="text-align:center">
  11018. <a href="'.$link['url'].'">'.$link['title'].'</a></div>
  11019. </body>
  11020. </html>';
  11021. file_put_contents($archivePath.$temp_dir_short.'/'.$file, $content);
  11022. }
  11023. }
  11024. // Add non exportable message explanation.
  11025. $lang_not_exportable = get_lang('ThisItemIsNotExportable');
  11026. $file_content = '<!DOCTYPE html><head>
  11027. <meta charset="'.api_get_language_isocode().'" />
  11028. <title>'.$lang_not_exportable.'</title>
  11029. <meta http-equiv="Content-Type" content="text/html; charset='.api_get_system_encoding().'" />
  11030. </head>
  11031. <body dir="'.api_get_text_direction().'">';
  11032. $file_content .=
  11033. <<<EOD
  11034. <style>
  11035. .error-message {
  11036. font-family: arial, verdana, helvetica, sans-serif;
  11037. border-width: 1px;
  11038. border-style: solid;
  11039. left: 50%;
  11040. margin: 10px auto;
  11041. min-height: 30px;
  11042. padding: 5px;
  11043. right: 50%;
  11044. width: 500px;
  11045. background-color: #FFD1D1;
  11046. border-color: #FF0000;
  11047. color: #000;
  11048. }
  11049. </style>
  11050. <body>
  11051. <div class="error-message">
  11052. $lang_not_exportable
  11053. </div>
  11054. </body>
  11055. </html>
  11056. EOD;
  11057. if (!is_dir($archivePath.$temp_dir_short.'/document')) {
  11058. @mkdir($archivePath.$temp_dir_short.'/document', api_get_permissions_for_new_directories());
  11059. }
  11060. file_put_contents($archivePath.$temp_dir_short.'/document/non_exportable.html', $file_content);
  11061. // Add the extra files that go along with a SCORM package.
  11062. $main_code_path = api_get_path(SYS_CODE_PATH).'lp/packaging/';
  11063. $fs = new Filesystem();
  11064. $fs->mirror($main_code_path, $archivePath.$temp_dir_short);
  11065. // Finalize the imsmanifest structure, add to the zip, then return the zip.
  11066. $manifest = @$xmldoc->saveXML();
  11067. $manifest = api_utf8_decode_xml($manifest); // The manifest gets the system encoding now.
  11068. file_put_contents($archivePath.'/'.$temp_dir_short.'/imsmanifest.xml', $manifest);
  11069. $zip_folder->add(
  11070. $archivePath.'/'.$temp_dir_short,
  11071. PCLZIP_OPT_REMOVE_PATH,
  11072. $archivePath.'/'.$temp_dir_short.'/'
  11073. );
  11074. // Clean possible temporary files.
  11075. foreach ($files_cleanup as $file) {
  11076. $res = unlink($file);
  11077. if ($res === false) {
  11078. error_log(
  11079. 'Could not delete temp file '.$file.' '.__FILE__.' '.__LINE__,
  11080. 0
  11081. );
  11082. }
  11083. }
  11084. $name = api_replace_dangerous_char($this->get_name()).'.zip';
  11085. DocumentManager::file_send_for_download($temp_zip_file, true, $name);
  11086. }
  11087. /**
  11088. * @param int $lp_id
  11089. *
  11090. * @return bool
  11091. */
  11092. public function scorm_export_to_pdf($lp_id)
  11093. {
  11094. $lp_id = (int) $lp_id;
  11095. $files_to_export = [];
  11096. $sessionId = api_get_session_id();
  11097. $course_data = api_get_course_info($this->cc);
  11098. if (!empty($course_data)) {
  11099. $scorm_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/scorm/'.$this->path;
  11100. $list = self::get_flat_ordered_items_list($lp_id);
  11101. if (!empty($list)) {
  11102. foreach ($list as $item_id) {
  11103. $item = $this->items[$item_id];
  11104. switch ($item->type) {
  11105. case 'document':
  11106. // Getting documents from a LP with chamilo documents
  11107. $file_data = DocumentManager::get_document_data_by_id($item->path, $this->cc);
  11108. // Try loading document from the base course.
  11109. if (empty($file_data) && !empty($sessionId)) {
  11110. $file_data = DocumentManager::get_document_data_by_id(
  11111. $item->path,
  11112. $this->cc,
  11113. false,
  11114. 0
  11115. );
  11116. }
  11117. $file_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/document'.$file_data['path'];
  11118. if (file_exists($file_path)) {
  11119. $files_to_export[] = [
  11120. 'title' => $item->get_title(),
  11121. 'path' => $file_path,
  11122. ];
  11123. }
  11124. break;
  11125. case 'asset': //commes from a scorm package generated by chamilo
  11126. case 'sco':
  11127. $file_path = $scorm_path.'/'.$item->path;
  11128. if (file_exists($file_path)) {
  11129. $files_to_export[] = [
  11130. 'title' => $item->get_title(),
  11131. 'path' => $file_path,
  11132. ];
  11133. }
  11134. break;
  11135. case 'dir':
  11136. $files_to_export[] = [
  11137. 'title' => $item->get_title(),
  11138. 'path' => null,
  11139. ];
  11140. break;
  11141. }
  11142. }
  11143. }
  11144. $pdf = new PDF();
  11145. $result = $pdf->html_to_pdf(
  11146. $files_to_export,
  11147. $this->name,
  11148. $this->cc,
  11149. true,
  11150. true,
  11151. true,
  11152. $this->get_name()
  11153. );
  11154. return $result;
  11155. }
  11156. return false;
  11157. }
  11158. /**
  11159. * Temp function to be moved in main_api or the best place around for this.
  11160. * Creates a file path if it doesn't exist.
  11161. *
  11162. * @param string $path
  11163. */
  11164. public function create_path($path)
  11165. {
  11166. $path_bits = explode('/', dirname($path));
  11167. // IS_WINDOWS_OS has been defined in main_api.lib.php
  11168. $path_built = IS_WINDOWS_OS ? '' : '/';
  11169. foreach ($path_bits as $bit) {
  11170. if (!empty($bit)) {
  11171. $new_path = $path_built.$bit;
  11172. if (is_dir($new_path)) {
  11173. $path_built = $new_path.'/';
  11174. } else {
  11175. mkdir($new_path, api_get_permissions_for_new_directories());
  11176. $path_built = $new_path.'/';
  11177. }
  11178. }
  11179. }
  11180. }
  11181. /**
  11182. * Delete the image relative to this learning path. No parameter. Only works on instanciated object.
  11183. *
  11184. * @return bool The results of the unlink function, or false if there was no image to start with
  11185. */
  11186. public function delete_lp_image()
  11187. {
  11188. $img = $this->get_preview_image();
  11189. if ($img != '') {
  11190. $del_file = $this->get_preview_image_path(null, 'sys');
  11191. if (isset($del_file) && file_exists($del_file)) {
  11192. $del_file_2 = $this->get_preview_image_path(64, 'sys');
  11193. if (file_exists($del_file_2)) {
  11194. unlink($del_file_2);
  11195. }
  11196. $this->set_preview_image('');
  11197. return @unlink($del_file);
  11198. }
  11199. }
  11200. return false;
  11201. }
  11202. /**
  11203. * Uploads an author image to the upload/learning_path/images directory.
  11204. *
  11205. * @param array The image array, coming from the $_FILES superglobal
  11206. *
  11207. * @return bool True on success, false on error
  11208. */
  11209. public function upload_image($image_array)
  11210. {
  11211. if (!empty($image_array['name'])) {
  11212. $upload_ok = process_uploaded_file($image_array);
  11213. $has_attachment = true;
  11214. }
  11215. if ($upload_ok && $has_attachment) {
  11216. $courseDir = api_get_course_path().'/upload/learning_path/images';
  11217. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  11218. $updir = $sys_course_path.$courseDir;
  11219. // Try to add an extension to the file if it hasn't one.
  11220. $new_file_name = add_ext_on_mime(stripslashes($image_array['name']), $image_array['type']);
  11221. if (filter_extension($new_file_name)) {
  11222. $file_extension = explode('.', $image_array['name']);
  11223. $file_extension = strtolower($file_extension[sizeof($file_extension) - 1]);
  11224. $filename = uniqid('');
  11225. $new_file_name = $filename.'.'.$file_extension;
  11226. $new_path = $updir.'/'.$new_file_name;
  11227. // Resize the image.
  11228. $temp = new Image($image_array['tmp_name']);
  11229. $temp->resize(104);
  11230. $result = $temp->send_image($new_path);
  11231. // Storing the image filename.
  11232. if ($result) {
  11233. $this->set_preview_image($new_file_name);
  11234. //Resize to 64px to use on course homepage
  11235. $temp->resize(64);
  11236. $temp->send_image($updir.'/'.$filename.'.64.'.$file_extension);
  11237. return true;
  11238. }
  11239. }
  11240. }
  11241. return false;
  11242. }
  11243. /**
  11244. * @param int $lp_id
  11245. * @param string $status
  11246. */
  11247. public function set_autolaunch($lp_id, $status)
  11248. {
  11249. $course_id = api_get_course_int_id();
  11250. $lp_id = (int) $lp_id;
  11251. $status = (int) $status;
  11252. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  11253. // Setting everything to autolaunch = 0
  11254. $attributes['autolaunch'] = 0;
  11255. $where = [
  11256. 'session_id = ? AND c_id = ? ' => [
  11257. api_get_session_id(),
  11258. $course_id,
  11259. ],
  11260. ];
  11261. Database::update($lp_table, $attributes, $where);
  11262. if ($status == 1) {
  11263. //Setting my lp_id to autolaunch = 1
  11264. $attributes['autolaunch'] = 1;
  11265. $where = [
  11266. 'iid = ? AND session_id = ? AND c_id = ?' => [
  11267. $lp_id,
  11268. api_get_session_id(),
  11269. $course_id,
  11270. ],
  11271. ];
  11272. Database::update($lp_table, $attributes, $where);
  11273. }
  11274. }
  11275. /**
  11276. * Gets previous_item_id for the next element of the lp_item table.
  11277. *
  11278. * @author Isaac flores paz
  11279. *
  11280. * @return int Previous item ID
  11281. */
  11282. public function select_previous_item_id()
  11283. {
  11284. $course_id = api_get_course_int_id();
  11285. if ($this->debug > 0) {
  11286. error_log('In learnpath::select_previous_item_id()', 0);
  11287. }
  11288. $table_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  11289. // Get the max order of the items
  11290. $sql = "SELECT max(display_order) AS display_order FROM $table_lp_item
  11291. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  11292. $rs_max_order = Database::query($sql);
  11293. $row_max_order = Database::fetch_object($rs_max_order);
  11294. $max_order = $row_max_order->display_order;
  11295. // Get the previous item ID
  11296. $sql = "SELECT iid as previous FROM $table_lp_item
  11297. WHERE
  11298. c_id = $course_id AND
  11299. lp_id = ".$this->lp_id." AND
  11300. display_order = '$max_order' ";
  11301. $rs_max = Database::query($sql);
  11302. $row_max = Database::fetch_object($rs_max);
  11303. // Return the previous item ID
  11304. return $row_max->previous;
  11305. }
  11306. /**
  11307. * Copies an LP.
  11308. */
  11309. public function copy()
  11310. {
  11311. // Course builder
  11312. $cb = new CourseBuilder();
  11313. //Setting tools that will be copied
  11314. $cb->set_tools_to_build(['learnpaths']);
  11315. //Setting elements that will be copied
  11316. $cb->set_tools_specific_id_list(
  11317. ['learnpaths' => [$this->lp_id]]
  11318. );
  11319. $course = $cb->build();
  11320. //Course restorer
  11321. $course_restorer = new CourseRestorer($course);
  11322. $course_restorer->set_add_text_in_items(true);
  11323. $course_restorer->set_tool_copy_settings(
  11324. ['learnpaths' => ['reset_dates' => true]]
  11325. );
  11326. $course_restorer->restore(
  11327. api_get_course_id(),
  11328. api_get_session_id(),
  11329. false,
  11330. false
  11331. );
  11332. }
  11333. /**
  11334. * Verify document size.
  11335. *
  11336. * @param string $s
  11337. *
  11338. * @return bool
  11339. */
  11340. public static function verify_document_size($s)
  11341. {
  11342. $post_max = ini_get('post_max_size');
  11343. if (substr($post_max, -1, 1) == 'M') {
  11344. $post_max = intval(substr($post_max, 0, -1)) * 1024 * 1024;
  11345. } elseif (substr($post_max, -1, 1) == 'G') {
  11346. $post_max = intval(substr($post_max, 0, -1)) * 1024 * 1024 * 1024;
  11347. }
  11348. $upl_max = ini_get('upload_max_filesize');
  11349. if (substr($upl_max, -1, 1) == 'M') {
  11350. $upl_max = intval(substr($upl_max, 0, -1)) * 1024 * 1024;
  11351. } elseif (substr($upl_max, -1, 1) == 'G') {
  11352. $upl_max = intval(substr($upl_max, 0, -1)) * 1024 * 1024 * 1024;
  11353. }
  11354. $documents_total_space = DocumentManager::documents_total_space();
  11355. $course_max_space = DocumentManager::get_course_quota();
  11356. $total_size = filesize($s) + $documents_total_space;
  11357. if (filesize($s) > $post_max || filesize($s) > $upl_max || $total_size > $course_max_space) {
  11358. return true;
  11359. }
  11360. return false;
  11361. }
  11362. /**
  11363. * Clear LP prerequisites.
  11364. */
  11365. public function clear_prerequisites()
  11366. {
  11367. $course_id = $this->get_course_int_id();
  11368. if ($this->debug > 0) {
  11369. error_log('In learnpath::clear_prerequisites()', 0);
  11370. }
  11371. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  11372. $lp_id = $this->get_id();
  11373. //Cleaning prerequisites
  11374. $sql = "UPDATE $tbl_lp_item SET prerequisite = ''
  11375. WHERE c_id = $course_id AND lp_id = $lp_id";
  11376. Database::query($sql);
  11377. //Cleaning mastery score for exercises
  11378. $sql = "UPDATE $tbl_lp_item SET mastery_score = ''
  11379. WHERE c_id = $course_id AND lp_id = $lp_id AND item_type = 'quiz'";
  11380. Database::query($sql);
  11381. }
  11382. public function set_previous_step_as_prerequisite_for_all_items()
  11383. {
  11384. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  11385. $course_id = $this->get_course_int_id();
  11386. $lp_id = $this->get_id();
  11387. if (!empty($this->items)) {
  11388. $previous_item_id = null;
  11389. $previous_item_max = 0;
  11390. $previous_item_type = null;
  11391. $last_item_not_dir = null;
  11392. $last_item_not_dir_type = null;
  11393. $last_item_not_dir_max = null;
  11394. foreach ($this->ordered_items as $itemId) {
  11395. $item = $this->getItem($itemId);
  11396. // if there was a previous item... (otherwise jump to set it)
  11397. if (!empty($previous_item_id)) {
  11398. $current_item_id = $item->get_id(); //save current id
  11399. if ($item->get_type() != 'dir') {
  11400. // Current item is not a folder, so it qualifies to get a prerequisites
  11401. if ($last_item_not_dir_type == 'quiz') {
  11402. // if previous is quiz, mark its max score as default score to be achieved
  11403. $sql = "UPDATE $tbl_lp_item SET mastery_score = '$last_item_not_dir_max'
  11404. WHERE c_id = $course_id AND lp_id = $lp_id AND iid = $last_item_not_dir";
  11405. Database::query($sql);
  11406. }
  11407. // now simply update the prerequisite to set it to the last non-chapter item
  11408. $sql = "UPDATE $tbl_lp_item SET prerequisite = '$last_item_not_dir'
  11409. WHERE c_id = $course_id AND lp_id = $lp_id AND iid = $current_item_id";
  11410. Database::query($sql);
  11411. // record item as 'non-chapter' reference
  11412. $last_item_not_dir = $item->get_id();
  11413. $last_item_not_dir_type = $item->get_type();
  11414. $last_item_not_dir_max = $item->get_max();
  11415. }
  11416. } else {
  11417. if ($item->get_type() != 'dir') {
  11418. // Current item is not a folder (but it is the first item) so record as last "non-chapter" item
  11419. $last_item_not_dir = $item->get_id();
  11420. $last_item_not_dir_type = $item->get_type();
  11421. $last_item_not_dir_max = $item->get_max();
  11422. }
  11423. }
  11424. // Saving the item as "previous item" for the next loop
  11425. $previous_item_id = $item->get_id();
  11426. $previous_item_max = $item->get_max();
  11427. $previous_item_type = $item->get_type();
  11428. }
  11429. }
  11430. }
  11431. /**
  11432. * @param array $params
  11433. *
  11434. * @throws \Doctrine\ORM\OptimisticLockException
  11435. *
  11436. * @return int
  11437. */
  11438. public static function createCategory($params)
  11439. {
  11440. $em = Database::getManager();
  11441. $item = new CLpCategory();
  11442. $item->setName($params['name']);
  11443. $item->setCId($params['c_id']);
  11444. $em->persist($item);
  11445. $em->flush();
  11446. api_item_property_update(
  11447. api_get_course_info(),
  11448. TOOL_LEARNPATH_CATEGORY,
  11449. $item->getId(),
  11450. 'visible',
  11451. api_get_user_id()
  11452. );
  11453. return $item->getId();
  11454. }
  11455. /**
  11456. * @param array $params
  11457. *
  11458. * @throws \Doctrine\ORM\ORMException
  11459. * @throws \Doctrine\ORM\OptimisticLockException
  11460. * @throws \Doctrine\ORM\TransactionRequiredException
  11461. */
  11462. public static function updateCategory($params)
  11463. {
  11464. $em = Database::getManager();
  11465. /** @var CLpCategory $item */
  11466. $item = $em->find('ChamiloCourseBundle:CLpCategory', $params['id']);
  11467. if ($item) {
  11468. $item->setName($params['name']);
  11469. $em->merge($item);
  11470. $em->flush();
  11471. }
  11472. }
  11473. /**
  11474. * @param int $id
  11475. *
  11476. * @throws \Doctrine\ORM\ORMException
  11477. * @throws \Doctrine\ORM\OptimisticLockException
  11478. * @throws \Doctrine\ORM\TransactionRequiredException
  11479. */
  11480. public static function moveUpCategory($id)
  11481. {
  11482. $id = (int) $id;
  11483. $em = Database::getManager();
  11484. /** @var CLpCategory $item */
  11485. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  11486. if ($item) {
  11487. $position = $item->getPosition() - 1;
  11488. $item->setPosition($position);
  11489. $em->persist($item);
  11490. $em->flush();
  11491. }
  11492. }
  11493. /**
  11494. * @param int $id
  11495. *
  11496. * @throws \Doctrine\ORM\ORMException
  11497. * @throws \Doctrine\ORM\OptimisticLockException
  11498. * @throws \Doctrine\ORM\TransactionRequiredException
  11499. */
  11500. public static function moveDownCategory($id)
  11501. {
  11502. $id = (int) $id;
  11503. $em = Database::getManager();
  11504. /** @var CLpCategory $item */
  11505. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  11506. if ($item) {
  11507. $position = $item->getPosition() + 1;
  11508. $item->setPosition($position);
  11509. $em->persist($item);
  11510. $em->flush();
  11511. }
  11512. }
  11513. /**
  11514. * @param int $courseId
  11515. *
  11516. * @throws \Doctrine\ORM\Query\QueryException
  11517. *
  11518. * @return int|mixed
  11519. */
  11520. public static function getCountCategories($courseId)
  11521. {
  11522. if (empty($courseId)) {
  11523. return 0;
  11524. }
  11525. $em = Database::getManager();
  11526. $query = $em->createQuery('SELECT COUNT(u.id) FROM ChamiloCourseBundle:CLpCategory u WHERE u.cId = :id');
  11527. $query->setParameter('id', $courseId);
  11528. return $query->getSingleScalarResult();
  11529. }
  11530. /**
  11531. * @param int $courseId
  11532. *
  11533. * @return mixed
  11534. */
  11535. public static function getCategories($courseId)
  11536. {
  11537. $em = Database::getManager();
  11538. // Using doctrine extensions
  11539. /** @var SortableRepository $repo */
  11540. $repo = $em->getRepository('ChamiloCourseBundle:CLpCategory');
  11541. $items = $repo
  11542. ->getBySortableGroupsQuery(['cId' => $courseId])
  11543. ->getResult();
  11544. return $items;
  11545. }
  11546. /**
  11547. * @param int $id
  11548. *
  11549. * @throws \Doctrine\ORM\ORMException
  11550. * @throws \Doctrine\ORM\OptimisticLockException
  11551. * @throws \Doctrine\ORM\TransactionRequiredException
  11552. *
  11553. * @return CLpCategory
  11554. */
  11555. public static function getCategory($id)
  11556. {
  11557. $id = (int) $id;
  11558. $em = Database::getManager();
  11559. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  11560. return $item;
  11561. }
  11562. /**
  11563. * @param int $courseId
  11564. *
  11565. * @return array
  11566. */
  11567. public static function getCategoryByCourse($courseId)
  11568. {
  11569. $em = Database::getManager();
  11570. $items = $em->getRepository('ChamiloCourseBundle:CLpCategory')->findBy(
  11571. ['cId' => $courseId]
  11572. );
  11573. return $items;
  11574. }
  11575. /**
  11576. * @param int $id
  11577. *
  11578. * @throws \Doctrine\ORM\ORMException
  11579. * @throws \Doctrine\ORM\OptimisticLockException
  11580. * @throws \Doctrine\ORM\TransactionRequiredException
  11581. *
  11582. * @return mixed
  11583. */
  11584. public static function deleteCategory($id)
  11585. {
  11586. $em = Database::getManager();
  11587. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  11588. if ($item) {
  11589. $courseId = $item->getCId();
  11590. $query = $em->createQuery('SELECT u FROM ChamiloCourseBundle:CLp u WHERE u.cId = :id AND u.categoryId = :catId');
  11591. $query->setParameter('id', $courseId);
  11592. $query->setParameter('catId', $item->getId());
  11593. $lps = $query->getResult();
  11594. // Setting category = 0.
  11595. if ($lps) {
  11596. foreach ($lps as $lpItem) {
  11597. $lpItem->setCategoryId(0);
  11598. }
  11599. }
  11600. // Removing category.
  11601. $em->remove($item);
  11602. $em->flush();
  11603. $courseInfo = api_get_course_info_by_id($courseId);
  11604. $sessionId = api_get_session_id();
  11605. // Delete link tool
  11606. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  11607. $link = 'lp/lp_controller.php?cidReq='.$courseInfo['code'].'&id_session='.$sessionId.'&gidReq=0&gradebook=0&origin=&action=view_category&id='.$id;
  11608. // Delete tools
  11609. $sql = "DELETE FROM $tbl_tool
  11610. WHERE c_id = ".$courseId." AND (link LIKE '$link%' AND image='lp_category.gif')";
  11611. Database::query($sql);
  11612. return true;
  11613. }
  11614. return false;
  11615. }
  11616. /**
  11617. * @param int $courseId
  11618. * @param bool $addSelectOption
  11619. *
  11620. * @return mixed
  11621. */
  11622. public static function getCategoryFromCourseIntoSelect($courseId, $addSelectOption = false)
  11623. {
  11624. $items = self::getCategoryByCourse($courseId);
  11625. $cats = [];
  11626. if ($addSelectOption) {
  11627. $cats = [get_lang('SelectACategory')];
  11628. }
  11629. if (!empty($items)) {
  11630. foreach ($items as $cat) {
  11631. $cats[$cat->getId()] = $cat->getName();
  11632. }
  11633. }
  11634. return $cats;
  11635. }
  11636. /**
  11637. * @param string $courseCode
  11638. * @param int $lpId
  11639. * @param int $user_id
  11640. *
  11641. * @return learnpath
  11642. */
  11643. public static function getLpFromSession($courseCode, $lpId, $user_id)
  11644. {
  11645. $debug = 0;
  11646. $learnPath = null;
  11647. $lpObject = Session::read('lpobject');
  11648. if ($lpObject !== null) {
  11649. $learnPath = UnserializeApi::unserialize('lp', $lpObject);
  11650. if ($debug) {
  11651. error_log('getLpFromSession: unserialize');
  11652. error_log('------getLpFromSession------');
  11653. error_log('------unserialize------');
  11654. error_log("lp_view_session_id: ".$learnPath->lp_view_session_id);
  11655. error_log("api_get_sessionid: ".api_get_session_id());
  11656. }
  11657. }
  11658. if (!is_object($learnPath)) {
  11659. $learnPath = new learnpath($courseCode, $lpId, $user_id);
  11660. if ($debug) {
  11661. error_log('------getLpFromSession------');
  11662. error_log('getLpFromSession: create new learnpath');
  11663. error_log("create new LP with $courseCode - $lpId - $user_id");
  11664. error_log("lp_view_session_id: ".$learnPath->lp_view_session_id);
  11665. error_log("api_get_sessionid: ".api_get_session_id());
  11666. }
  11667. }
  11668. return $learnPath;
  11669. }
  11670. /**
  11671. * @param int $itemId
  11672. *
  11673. * @return learnpathItem|false
  11674. */
  11675. public function getItem($itemId)
  11676. {
  11677. if (isset($this->items[$itemId]) && is_object($this->items[$itemId])) {
  11678. return $this->items[$itemId];
  11679. }
  11680. return false;
  11681. }
  11682. /**
  11683. * @return int
  11684. */
  11685. public function getCategoryId()
  11686. {
  11687. return (int) $this->categoryId;
  11688. }
  11689. /**
  11690. * @param int $categoryId
  11691. *
  11692. * @return bool
  11693. */
  11694. public function setCategoryId($categoryId)
  11695. {
  11696. $this->categoryId = (int) $categoryId;
  11697. $table = Database::get_course_table(TABLE_LP_MAIN);
  11698. $lp_id = $this->get_id();
  11699. $sql = "UPDATE $table SET category_id = ".$this->categoryId."
  11700. WHERE iid = $lp_id";
  11701. Database::query($sql);
  11702. return true;
  11703. }
  11704. /**
  11705. * Get whether this is a learning path with the possibility to subscribe
  11706. * users or not.
  11707. *
  11708. * @return int
  11709. */
  11710. public function getSubscribeUsers()
  11711. {
  11712. return $this->subscribeUsers;
  11713. }
  11714. /**
  11715. * Set whether this is a learning path with the possibility to subscribe
  11716. * users or not.
  11717. *
  11718. * @param int $value (0 = false, 1 = true)
  11719. *
  11720. * @return bool
  11721. */
  11722. public function setSubscribeUsers($value)
  11723. {
  11724. if ($this->debug > 0) {
  11725. error_log('In learnpath::set_subscribe_users()', 0);
  11726. }
  11727. $this->subscribeUsers = (int) $value;
  11728. $table = Database::get_course_table(TABLE_LP_MAIN);
  11729. $lp_id = $this->get_id();
  11730. $sql = "UPDATE $table SET subscribe_users = ".$this->subscribeUsers."
  11731. WHERE iid = $lp_id";
  11732. Database::query($sql);
  11733. return true;
  11734. }
  11735. /**
  11736. * Calculate the count of stars for a user in this LP
  11737. * This calculation is based on the following rules:
  11738. * - the student gets one star when he gets to 50% of the learning path
  11739. * - the student gets a second star when the average score of all tests inside the learning path >= 50%
  11740. * - the student gets a third star when the average score of all tests inside the learning path >= 80%
  11741. * - the student gets the final star when the score for the *last* test is >= 80%.
  11742. *
  11743. * @param int $sessionId Optional. The session ID
  11744. *
  11745. * @return int The count of stars
  11746. */
  11747. public function getCalculateStars($sessionId = 0)
  11748. {
  11749. $stars = 0;
  11750. $progress = self::getProgress(
  11751. $this->lp_id,
  11752. $this->user_id,
  11753. $this->course_int_id,
  11754. $sessionId
  11755. );
  11756. if ($progress >= 50) {
  11757. $stars++;
  11758. }
  11759. // Calculate stars chapters evaluation
  11760. $exercisesItems = $this->getExercisesItems();
  11761. if (!empty($exercisesItems)) {
  11762. $totalResult = 0;
  11763. foreach ($exercisesItems as $exerciseItem) {
  11764. $exerciseResultInfo = Event::getExerciseResultsByUser(
  11765. $this->user_id,
  11766. $exerciseItem->path,
  11767. $this->course_int_id,
  11768. $sessionId,
  11769. $this->lp_id,
  11770. $exerciseItem->db_id
  11771. );
  11772. $exerciseResultInfo = end($exerciseResultInfo);
  11773. if (!$exerciseResultInfo) {
  11774. continue;
  11775. }
  11776. if (!empty($exerciseResultInfo['exe_weighting'])) {
  11777. $exerciseResult = $exerciseResultInfo['exe_result'] * 100 / $exerciseResultInfo['exe_weighting'];
  11778. } else {
  11779. $exerciseResult = 0;
  11780. }
  11781. $totalResult += $exerciseResult;
  11782. }
  11783. $totalExerciseAverage = $totalResult / (count($exercisesItems) > 0 ? count($exercisesItems) : 1);
  11784. if ($totalExerciseAverage >= 50) {
  11785. $stars++;
  11786. }
  11787. if ($totalExerciseAverage >= 80) {
  11788. $stars++;
  11789. }
  11790. }
  11791. // Calculate star for final evaluation
  11792. $finalEvaluationItem = $this->getFinalEvaluationItem();
  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. $evaluationResult = $evaluationResultInfo['exe_result'] * 100 / $evaluationResultInfo['exe_weighting'];
  11805. if ($evaluationResult >= 80) {
  11806. $stars++;
  11807. }
  11808. }
  11809. }
  11810. return $stars;
  11811. }
  11812. /**
  11813. * Get the items of exercise type.
  11814. *
  11815. * @return array The items. Otherwise return false
  11816. */
  11817. public function getExercisesItems()
  11818. {
  11819. $exercises = [];
  11820. foreach ($this->items as $item) {
  11821. if ($item->type != 'quiz') {
  11822. continue;
  11823. }
  11824. $exercises[] = $item;
  11825. }
  11826. array_pop($exercises);
  11827. return $exercises;
  11828. }
  11829. /**
  11830. * Get the item of exercise type (evaluation type).
  11831. *
  11832. * @return array The final evaluation. Otherwise return false
  11833. */
  11834. public function getFinalEvaluationItem()
  11835. {
  11836. $exercises = [];
  11837. foreach ($this->items as $item) {
  11838. if ($item->type != 'quiz') {
  11839. continue;
  11840. }
  11841. $exercises[] = $item;
  11842. }
  11843. return array_pop($exercises);
  11844. }
  11845. /**
  11846. * Calculate the total points achieved for the current user in this learning path.
  11847. *
  11848. * @param int $sessionId Optional. The session Id
  11849. *
  11850. * @return int
  11851. */
  11852. public function getCalculateScore($sessionId = 0)
  11853. {
  11854. // Calculate stars chapters evaluation
  11855. $exercisesItems = $this->getExercisesItems();
  11856. $finalEvaluationItem = $this->getFinalEvaluationItem();
  11857. $totalExercisesResult = 0;
  11858. $totalEvaluationResult = 0;
  11859. if ($exercisesItems !== false) {
  11860. foreach ($exercisesItems as $exerciseItem) {
  11861. $exerciseResultInfo = Event::getExerciseResultsByUser(
  11862. $this->user_id,
  11863. $exerciseItem->path,
  11864. $this->course_int_id,
  11865. $sessionId,
  11866. $this->lp_id,
  11867. $exerciseItem->db_id
  11868. );
  11869. $exerciseResultInfo = end($exerciseResultInfo);
  11870. if (!$exerciseResultInfo) {
  11871. continue;
  11872. }
  11873. $totalExercisesResult += $exerciseResultInfo['exe_result'];
  11874. }
  11875. }
  11876. if (!empty($finalEvaluationItem)) {
  11877. $evaluationResultInfo = Event::getExerciseResultsByUser(
  11878. $this->user_id,
  11879. $finalEvaluationItem->path,
  11880. $this->course_int_id,
  11881. $sessionId,
  11882. $this->lp_id,
  11883. $finalEvaluationItem->db_id
  11884. );
  11885. $evaluationResultInfo = end($evaluationResultInfo);
  11886. if ($evaluationResultInfo) {
  11887. $totalEvaluationResult += $evaluationResultInfo['exe_result'];
  11888. }
  11889. }
  11890. return $totalExercisesResult + $totalEvaluationResult;
  11891. }
  11892. /**
  11893. * Check if URL is not allowed to be show in a iframe.
  11894. *
  11895. * @param string $src
  11896. *
  11897. * @return string
  11898. */
  11899. public function fixBlockedLinks($src)
  11900. {
  11901. $urlInfo = parse_url($src);
  11902. $platformProtocol = 'https';
  11903. if (strpos(api_get_path(WEB_CODE_PATH), 'https') === false) {
  11904. $platformProtocol = 'http';
  11905. }
  11906. $protocolFixApplied = false;
  11907. //Scheme validation to avoid "Notices" when the lesson doesn't contain a valid scheme
  11908. $scheme = isset($urlInfo['scheme']) ? $urlInfo['scheme'] : null;
  11909. $host = isset($urlInfo['host']) ? $urlInfo['host'] : null;
  11910. if ($platformProtocol != $scheme) {
  11911. Session::write('x_frame_source', $src);
  11912. $src = 'blank.php?error=x_frames_options';
  11913. $protocolFixApplied = true;
  11914. }
  11915. if ($protocolFixApplied == false) {
  11916. if (strpos(api_get_path(WEB_PATH), $host) === false) {
  11917. // Check X-Frame-Options
  11918. $ch = curl_init();
  11919. $options = [
  11920. CURLOPT_URL => $src,
  11921. CURLOPT_RETURNTRANSFER => true,
  11922. CURLOPT_HEADER => true,
  11923. CURLOPT_FOLLOWLOCATION => true,
  11924. CURLOPT_ENCODING => "",
  11925. CURLOPT_AUTOREFERER => true,
  11926. CURLOPT_CONNECTTIMEOUT => 120,
  11927. CURLOPT_TIMEOUT => 120,
  11928. CURLOPT_MAXREDIRS => 10,
  11929. ];
  11930. $proxySettings = api_get_configuration_value('proxy_settings');
  11931. if (!empty($proxySettings) &&
  11932. isset($proxySettings['curl_setopt_array'])
  11933. ) {
  11934. $options[CURLOPT_PROXY] = $proxySettings['curl_setopt_array']['CURLOPT_PROXY'];
  11935. $options[CURLOPT_PROXYPORT] = $proxySettings['curl_setopt_array']['CURLOPT_PROXYPORT'];
  11936. }
  11937. curl_setopt_array($ch, $options);
  11938. $response = curl_exec($ch);
  11939. $httpCode = curl_getinfo($ch);
  11940. $headers = substr($response, 0, $httpCode['header_size']);
  11941. $error = false;
  11942. if (stripos($headers, 'X-Frame-Options: DENY') > -1
  11943. //|| stripos($headers, 'X-Frame-Options: SAMEORIGIN') > -1
  11944. ) {
  11945. $error = true;
  11946. }
  11947. if ($error) {
  11948. Session::write('x_frame_source', $src);
  11949. $src = 'blank.php?error=x_frames_options';
  11950. }
  11951. }
  11952. }
  11953. return $src;
  11954. }
  11955. /**
  11956. * Check if this LP has a created forum in the basis course.
  11957. *
  11958. * @return bool
  11959. */
  11960. public function lpHasForum()
  11961. {
  11962. $forumTable = Database::get_course_table(TABLE_FORUM);
  11963. $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  11964. $fakeFrom = "
  11965. $forumTable f
  11966. INNER JOIN $itemProperty ip
  11967. ON (f.forum_id = ip.ref AND f.c_id = ip.c_id)
  11968. ";
  11969. $resultData = Database::select(
  11970. 'COUNT(f.iid) AS qty',
  11971. $fakeFrom,
  11972. [
  11973. 'where' => [
  11974. 'ip.visibility != ? AND ' => 2,
  11975. 'ip.tool = ? AND ' => TOOL_FORUM,
  11976. 'f.c_id = ? AND ' => intval($this->course_int_id),
  11977. 'f.lp_id = ?' => intval($this->lp_id),
  11978. ],
  11979. ],
  11980. 'first'
  11981. );
  11982. return $resultData['qty'] > 0;
  11983. }
  11984. /**
  11985. * Get the forum for this learning path.
  11986. *
  11987. * @param int $sessionId
  11988. *
  11989. * @return bool
  11990. */
  11991. public function getForum($sessionId = 0)
  11992. {
  11993. $forumTable = Database::get_course_table(TABLE_FORUM);
  11994. $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  11995. $fakeFrom = "$forumTable f
  11996. INNER JOIN $itemProperty ip ";
  11997. if ($this->lp_session_id == 0) {
  11998. $fakeFrom .= "
  11999. ON (
  12000. f.forum_id = ip.ref AND f.c_id = ip.c_id AND (
  12001. f.session_id = ip.session_id OR ip.session_id IS NULL
  12002. )
  12003. )
  12004. ";
  12005. } else {
  12006. $fakeFrom .= "
  12007. ON (
  12008. f.forum_id = ip.ref AND f.c_id = ip.c_id AND f.session_id = ip.session_id
  12009. )
  12010. ";
  12011. }
  12012. $resultData = Database::select(
  12013. 'f.*',
  12014. $fakeFrom,
  12015. [
  12016. 'where' => [
  12017. 'ip.visibility != ? AND ' => 2,
  12018. 'ip.tool = ? AND ' => TOOL_FORUM,
  12019. 'f.session_id = ? AND ' => $sessionId,
  12020. 'f.c_id = ? AND ' => intval($this->course_int_id),
  12021. 'f.lp_id = ?' => intval($this->lp_id),
  12022. ],
  12023. ],
  12024. 'first'
  12025. );
  12026. if (empty($resultData)) {
  12027. return false;
  12028. }
  12029. return $resultData;
  12030. }
  12031. /**
  12032. * Create a forum for this learning path.
  12033. *
  12034. * @param int $forumCategoryId
  12035. *
  12036. * @return int The forum ID if was created. Otherwise return false
  12037. */
  12038. public function createForum($forumCategoryId)
  12039. {
  12040. require_once api_get_path(SYS_CODE_PATH).'/forum/forumfunction.inc.php';
  12041. $forumId = store_forum(
  12042. [
  12043. 'lp_id' => $this->lp_id,
  12044. 'forum_title' => $this->name,
  12045. 'forum_comment' => null,
  12046. 'forum_category' => (int) $forumCategoryId,
  12047. 'students_can_edit_group' => ['students_can_edit' => 0],
  12048. 'allow_new_threads_group' => ['allow_new_threads' => 0],
  12049. 'default_view_type_group' => ['default_view_type' => 'flat'],
  12050. 'group_forum' => 0,
  12051. 'public_private_group_forum_group' => ['public_private_group_forum' => 'public'],
  12052. ],
  12053. [],
  12054. true
  12055. );
  12056. return $forumId;
  12057. }
  12058. /**
  12059. * Get the LP Final Item form.
  12060. *
  12061. * @throws Exception
  12062. * @throws HTML_QuickForm_Error
  12063. *
  12064. * @return string
  12065. */
  12066. public function getFinalItemForm()
  12067. {
  12068. $finalItem = $this->getFinalItem();
  12069. $title = '';
  12070. if ($finalItem) {
  12071. $title = $finalItem->get_title();
  12072. $buttonText = get_lang('Save');
  12073. $content = $this->getSavedFinalItem();
  12074. } else {
  12075. $buttonText = get_lang('LPCreateDocument');
  12076. $content = $this->getFinalItemTemplate();
  12077. }
  12078. $courseInfo = api_get_course_info();
  12079. $result = $this->generate_lp_folder($courseInfo);
  12080. $relative_path = api_substr($result['dir'], 1, strlen($result['dir']));
  12081. $relative_prefix = '../../';
  12082. $editorConfig = [
  12083. 'ToolbarSet' => 'LearningPathDocuments',
  12084. 'Width' => '100%',
  12085. 'Height' => '500',
  12086. 'FullPage' => true,
  12087. 'CreateDocumentDir' => $relative_prefix,
  12088. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/',
  12089. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/'.$relative_path,
  12090. ];
  12091. $url = api_get_self().'?'.api_get_cidreq().'&'.http_build_query([
  12092. 'type' => 'document',
  12093. 'lp_id' => $this->lp_id,
  12094. ]);
  12095. $form = new FormValidator('final_item', 'POST', $url);
  12096. $form->addText('title', get_lang('Title'));
  12097. $form->addButtonSave($buttonText);
  12098. $form->addHtml(
  12099. Display::return_message(
  12100. 'Variables :</br></br> <b>((certificate))</b> </br> <b>((skill))</b>',
  12101. 'normal',
  12102. false
  12103. )
  12104. );
  12105. $renderer = $form->defaultRenderer();
  12106. $renderer->setElementTemplate('&nbsp;{label}{element}', 'content_lp_certificate');
  12107. $form->addHtmlEditor(
  12108. 'content_lp_certificate',
  12109. null,
  12110. true,
  12111. false,
  12112. $editorConfig,
  12113. true
  12114. );
  12115. $form->addHidden('action', 'add_final_item');
  12116. $form->addHidden('path', Session::read('pathItem'));
  12117. $form->addHidden('previous', $this->get_last());
  12118. $form->setDefaults(
  12119. ['title' => $title, 'content_lp_certificate' => $content]
  12120. );
  12121. if ($form->validate()) {
  12122. $values = $form->exportValues();
  12123. $lastItemId = $this->getLastInFirstLevel();
  12124. if (!$finalItem) {
  12125. $documentId = $this->create_document(
  12126. $this->course_info,
  12127. $values['content_lp_certificate'],
  12128. $values['title']
  12129. );
  12130. $this->add_item(
  12131. 0,
  12132. $lastItemId,
  12133. 'final_item',
  12134. $documentId,
  12135. $values['title'],
  12136. ''
  12137. );
  12138. Display::addFlash(
  12139. Display::return_message(get_lang('Added'))
  12140. );
  12141. } else {
  12142. $this->edit_document($this->course_info);
  12143. }
  12144. }
  12145. return $form->returnForm();
  12146. }
  12147. /**
  12148. * Check if the current lp item is first, both, last or none from lp list.
  12149. *
  12150. * @param int $currentItemId
  12151. *
  12152. * @return string
  12153. */
  12154. public function isFirstOrLastItem($currentItemId)
  12155. {
  12156. if ($this->debug > 0) {
  12157. error_log('In learnpath::isFirstOrLastItem('.$currentItemId.')', 0);
  12158. }
  12159. $lpItemId = [];
  12160. $typeListNotToVerify = self::getChapterTypes();
  12161. // Using get_toc() function instead $this->items because returns the correct order of the items
  12162. foreach ($this->get_toc() as $item) {
  12163. if (!in_array($item['type'], $typeListNotToVerify)) {
  12164. $lpItemId[] = $item['id'];
  12165. }
  12166. }
  12167. $lastLpItemIndex = count($lpItemId) - 1;
  12168. $position = array_search($currentItemId, $lpItemId);
  12169. switch ($position) {
  12170. case 0:
  12171. if (!$lastLpItemIndex) {
  12172. $answer = 'both';
  12173. break;
  12174. }
  12175. $answer = 'first';
  12176. break;
  12177. case $lastLpItemIndex:
  12178. $answer = 'last';
  12179. break;
  12180. default:
  12181. $answer = 'none';
  12182. }
  12183. return $answer;
  12184. }
  12185. /**
  12186. * Get whether this is a learning path with the accumulated SCORM time or not.
  12187. *
  12188. * @return int
  12189. */
  12190. public function getAccumulateScormTime()
  12191. {
  12192. return $this->accumulateScormTime;
  12193. }
  12194. /**
  12195. * Set whether this is a learning path with the accumulated SCORM time or not.
  12196. *
  12197. * @param int $value (0 = false, 1 = true)
  12198. *
  12199. * @return bool Always returns true
  12200. */
  12201. public function setAccumulateScormTime($value)
  12202. {
  12203. if ($this->debug > 0) {
  12204. error_log('In learnpath::setAccumulateScormTime()', 0);
  12205. }
  12206. $this->accumulateScormTime = (int) $value;
  12207. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  12208. $lp_id = $this->get_id();
  12209. $sql = "UPDATE $lp_table
  12210. SET accumulate_scorm_time = ".$this->accumulateScormTime."
  12211. WHERE iid = $lp_id";
  12212. Database::query($sql);
  12213. return true;
  12214. }
  12215. /**
  12216. * Returns an HTML-formatted link to a resource, to incorporate directly into
  12217. * the new learning path tool.
  12218. *
  12219. * The function is a big switch on tool type.
  12220. * In each case, we query the corresponding table for information and build the link
  12221. * with that information.
  12222. *
  12223. * @author Yannick Warnier <ywarnier@beeznest.org> - rebranding based on
  12224. * previous work (display_addedresource_link_in_learnpath())
  12225. *
  12226. * @param int $course_id Course code
  12227. * @param int $learningPathId The learning path ID (in lp table)
  12228. * @param int $id_in_path the unique index in the items table
  12229. * @param int $lpViewId
  12230. *
  12231. * @return string
  12232. */
  12233. public static function rl_get_resource_link_for_learnpath(
  12234. $course_id,
  12235. $learningPathId,
  12236. $id_in_path,
  12237. $lpViewId
  12238. ) {
  12239. $session_id = api_get_session_id();
  12240. $course_info = api_get_course_info_by_id($course_id);
  12241. $learningPathId = (int) $learningPathId;
  12242. $id_in_path = (int) $id_in_path;
  12243. $lpViewId = (int) $lpViewId;
  12244. $em = Database::getManager();
  12245. $lpItemRepo = $em->getRepository('ChamiloCourseBundle:CLpItem');
  12246. /** @var CLpItem $rowItem */
  12247. $rowItem = $lpItemRepo->findOneBy([
  12248. 'cId' => $course_id,
  12249. 'lpId' => $learningPathId,
  12250. 'iid' => $id_in_path,
  12251. ]);
  12252. if (!$rowItem) {
  12253. // Try one more time with "id"
  12254. /** @var CLpItem $rowItem */
  12255. $rowItem = $lpItemRepo->findOneBy([
  12256. 'cId' => $course_id,
  12257. 'lpId' => $learningPathId,
  12258. 'id' => $id_in_path,
  12259. ]);
  12260. if (!$rowItem) {
  12261. return -1;
  12262. }
  12263. }
  12264. $course_code = $course_info['code'];
  12265. $type = $rowItem->getItemType();
  12266. $id = empty($rowItem->getPath()) ? '0' : $rowItem->getPath();
  12267. $main_dir_path = api_get_path(WEB_CODE_PATH);
  12268. $main_course_path = api_get_path(WEB_COURSE_PATH).$course_info['directory'].'/';
  12269. $link = '';
  12270. $extraParams = api_get_cidreq(true, true, 'learnpath').'&session_id='.$session_id;
  12271. switch ($type) {
  12272. case 'dir':
  12273. return $main_dir_path.'lp/blank.php';
  12274. case TOOL_CALENDAR_EVENT:
  12275. return $main_dir_path.'calendar/agenda.php?agenda_id='.$id.'&'.$extraParams;
  12276. case TOOL_ANNOUNCEMENT:
  12277. return $main_dir_path.'announcements/announcements.php?ann_id='.$id.'&'.$extraParams;
  12278. case TOOL_LINK:
  12279. $linkInfo = Link::getLinkInfo($id);
  12280. if (isset($linkInfo['url'])) {
  12281. return $linkInfo['url'];
  12282. }
  12283. return '';
  12284. case TOOL_QUIZ:
  12285. if (empty($id)) {
  12286. return '';
  12287. }
  12288. // Get the lp_item_view with the highest view_count.
  12289. $learnpathItemViewResult = $em
  12290. ->getRepository('ChamiloCourseBundle:CLpItemView')
  12291. ->findBy(
  12292. ['cId' => $course_id, 'lpItemId' => $rowItem->getId(), 'lpViewId' => $lpViewId],
  12293. ['viewCount' => 'DESC'],
  12294. 1
  12295. );
  12296. /** @var CLpItemView $learnpathItemViewData */
  12297. $learnpathItemViewData = current($learnpathItemViewResult);
  12298. $learnpathItemViewId = $learnpathItemViewData ? $learnpathItemViewData->getId() : 0;
  12299. return $main_dir_path.'exercise/overview.php?'.$extraParams.'&'
  12300. .http_build_query([
  12301. 'lp_init' => 1,
  12302. 'learnpath_item_view_id' => $learnpathItemViewId,
  12303. 'learnpath_id' => $learningPathId,
  12304. 'learnpath_item_id' => $id_in_path,
  12305. 'exerciseId' => $id,
  12306. ]);
  12307. case TOOL_HOTPOTATOES: //lowercase because of strtolower above
  12308. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  12309. $result = Database::query("SELECT * FROM ".$TBL_DOCUMENT." WHERE c_id = $course_id AND iid=$id");
  12310. $myrow = Database::fetch_array($result);
  12311. $path = $myrow['path'];
  12312. return $main_dir_path.'exercise/showinframes.php?file='.$path.'&cid='.$course_code.'&uid='
  12313. .api_get_user_id().'&learnpath_id='.$learningPathId.'&learnpath_item_id='.$id_in_path
  12314. .'&lp_view_id='.$lpViewId.'&'.$extraParams;
  12315. case TOOL_FORUM:
  12316. return $main_dir_path.'forum/viewforum.php?forum='.$id.'&lp=true&'.$extraParams;
  12317. case TOOL_THREAD:
  12318. // forum post
  12319. $tbl_topics = Database::get_course_table(TABLE_FORUM_THREAD);
  12320. if (empty($id)) {
  12321. return '';
  12322. }
  12323. $sql = "SELECT * FROM $tbl_topics WHERE c_id = $course_id AND thread_id=$id";
  12324. $result = Database::query($sql);
  12325. $myrow = Database::fetch_array($result);
  12326. return $main_dir_path.'forum/viewthread.php?thread='.$id.'&forum='.$myrow['forum_id'].'&lp=true&'
  12327. .$extraParams;
  12328. case TOOL_POST:
  12329. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  12330. $result = Database::query("SELECT * FROM $tbl_post WHERE c_id = $course_id AND post_id=$id");
  12331. $myrow = Database::fetch_array($result);
  12332. return $main_dir_path.'forum/viewthread.php?post='.$id.'&thread='.$myrow['thread_id'].'&forum='
  12333. .$myrow['forum_id'].'&lp=true&'.$extraParams;
  12334. case TOOL_READOUT_TEXT:
  12335. return api_get_path(WEB_CODE_PATH).
  12336. 'lp/readout_text.php?&id='.$id.'&lp_id='.$learningPathId.'&'.$extraParams;
  12337. case TOOL_DOCUMENT:
  12338. $repo = $em->getRepository('ChamiloCourseBundle:CDocument');
  12339. $document = $repo->findOneBy(['cId' => $course_id, 'iid' => $id]);
  12340. if (empty($document)) {
  12341. // Try with normal id
  12342. $document = $repo->findOneBy(['cId' => $course_id, 'id' => $id]);
  12343. if (empty($document)) {
  12344. return '';
  12345. }
  12346. }
  12347. $documentPathInfo = pathinfo($document->getPath());
  12348. $mediaSupportedFiles = ['mp3', 'mp4', 'ogv', 'flv', 'm4v'];
  12349. $extension = isset($documentPathInfo['extension']) ? $documentPathInfo['extension'] : '';
  12350. $showDirectUrl = !in_array($extension, $mediaSupportedFiles);
  12351. $openmethod = 2;
  12352. $officedoc = false;
  12353. Session::write('openmethod', $openmethod);
  12354. Session::write('officedoc', $officedoc);
  12355. if ($showDirectUrl) {
  12356. $file = $main_course_path.'document'.$document->getPath().'?'.$extraParams;
  12357. if (api_get_configuration_value('allow_pdf_viewerjs_in_lp')) {
  12358. if (Link::isPdfLink($file)) {
  12359. $pdfUrl = api_get_path(WEB_LIBRARY_PATH).'javascript/ViewerJS/index.html#'.$file;
  12360. return $pdfUrl;
  12361. }
  12362. }
  12363. return $file;
  12364. }
  12365. return api_get_path(WEB_CODE_PATH).'document/showinframes.php?id='.$id.'&'.$extraParams;
  12366. case TOOL_LP_FINAL_ITEM:
  12367. return api_get_path(WEB_CODE_PATH).'lp/lp_final_item.php?&id='.$id.'&lp_id='.$learningPathId.'&'
  12368. .$extraParams;
  12369. case 'assignments':
  12370. return $main_dir_path.'work/work.php?'.$extraParams;
  12371. case TOOL_DROPBOX:
  12372. return $main_dir_path.'dropbox/index.php?'.$extraParams;
  12373. case 'introduction_text': //DEPRECATED
  12374. return '';
  12375. case TOOL_COURSE_DESCRIPTION:
  12376. return $main_dir_path.'course_description?'.$extraParams;
  12377. case TOOL_GROUP:
  12378. return $main_dir_path.'group/group.php?'.$extraParams;
  12379. case TOOL_USER:
  12380. return $main_dir_path.'user/user.php?'.$extraParams;
  12381. case TOOL_STUDENTPUBLICATION:
  12382. if (!empty($rowItem->getPath())) {
  12383. return $main_dir_path.'work/work_list.php?id='.$rowItem->getPath().'&'.$extraParams;
  12384. }
  12385. return $main_dir_path.'work/work.php?'.api_get_cidreq().'&id='.$rowItem->getPath().'&'.$extraParams;
  12386. }
  12387. return $link;
  12388. }
  12389. /**
  12390. * Gets the name of a resource (generally used in learnpath when no name is provided).
  12391. *
  12392. * @author Yannick Warnier <ywarnier@beeznest.org>
  12393. *
  12394. * @param string $course_code Course code
  12395. * @param int $learningPathId
  12396. * @param int $id_in_path The resource ID
  12397. *
  12398. * @return string
  12399. */
  12400. public static function rl_get_resource_name($course_code, $learningPathId, $id_in_path)
  12401. {
  12402. $_course = api_get_course_info($course_code);
  12403. $course_id = $_course['real_id'];
  12404. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  12405. $learningPathId = (int) $learningPathId;
  12406. $id_in_path = (int) $id_in_path;
  12407. $sql = "SELECT item_type, title, ref
  12408. FROM $tbl_lp_item
  12409. WHERE c_id = $course_id AND lp_id = $learningPathId AND iid = $id_in_path";
  12410. $res_item = Database::query($sql);
  12411. if (Database::num_rows($res_item) < 1) {
  12412. return '';
  12413. }
  12414. $row_item = Database::fetch_array($res_item);
  12415. $type = strtolower($row_item['item_type']);
  12416. $id = $row_item['ref'];
  12417. $output = '';
  12418. switch ($type) {
  12419. case TOOL_CALENDAR_EVENT:
  12420. $TABLEAGENDA = Database::get_course_table(TABLE_AGENDA);
  12421. $result = Database::query("SELECT * FROM $TABLEAGENDA WHERE c_id = $course_id AND id=$id");
  12422. $myrow = Database::fetch_array($result);
  12423. $output = $myrow['title'];
  12424. break;
  12425. case TOOL_ANNOUNCEMENT:
  12426. $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
  12427. $result = Database::query("SELECT * FROM $tbl_announcement WHERE c_id = $course_id AND id=$id");
  12428. $myrow = Database::fetch_array($result);
  12429. $output = $myrow['title'];
  12430. break;
  12431. case TOOL_LINK:
  12432. // Doesn't take $target into account.
  12433. $TABLETOOLLINK = Database::get_course_table(TABLE_LINK);
  12434. $result = Database::query("SELECT * FROM $TABLETOOLLINK WHERE c_id = $course_id AND id=$id");
  12435. $myrow = Database::fetch_array($result);
  12436. $output = $myrow['title'];
  12437. break;
  12438. case TOOL_QUIZ:
  12439. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  12440. $result = Database::query("SELECT * FROM $TBL_EXERCICES WHERE c_id = $course_id AND id = $id");
  12441. $myrow = Database::fetch_array($result);
  12442. $output = $myrow['title'];
  12443. break;
  12444. case TOOL_FORUM:
  12445. $TBL_FORUMS = Database::get_course_table(TABLE_FORUM);
  12446. $result = Database::query("SELECT * FROM $TBL_FORUMS WHERE c_id = $course_id AND forum_id = $id");
  12447. $myrow = Database::fetch_array($result);
  12448. $output = $myrow['forum_name'];
  12449. break;
  12450. case TOOL_THREAD: //=topics
  12451. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  12452. // Grabbing the title of the post.
  12453. $sql_title = "SELECT * FROM $tbl_post WHERE c_id = $course_id AND post_id=".$id;
  12454. $result_title = Database::query($sql_title);
  12455. $myrow_title = Database::fetch_array($result_title);
  12456. $output = $myrow_title['post_title'];
  12457. break;
  12458. case TOOL_POST:
  12459. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  12460. //$tbl_post_text = Database::get_course_table(FORUM_POST_TEXT_TABLE);
  12461. $sql = "SELECT * FROM $tbl_post p WHERE c_id = $course_id AND p.post_id = $id";
  12462. $result = Database::query($sql);
  12463. $post = Database::fetch_array($result);
  12464. $output = $post['post_title'];
  12465. break;
  12466. case 'dir':
  12467. $title = $row_item['title'];
  12468. if (!empty($title)) {
  12469. $output = $title;
  12470. } else {
  12471. $output = '-';
  12472. }
  12473. break;
  12474. case TOOL_DOCUMENT:
  12475. $title = $row_item['title'];
  12476. if (!empty($title)) {
  12477. $output = $title;
  12478. } else {
  12479. $output = '-';
  12480. }
  12481. break;
  12482. case 'hotpotatoes':
  12483. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  12484. $result = Database::query("SELECT * FROM $tbl_doc WHERE c_id = $course_id AND iid = $id");
  12485. $myrow = Database::fetch_array($result);
  12486. $pathname = explode('/', $myrow['path']); // Making a correct name for the link.
  12487. $last = count($pathname) - 1; // Making a correct name for the link.
  12488. $filename = $pathname[$last]; // Making a correct name for the link.
  12489. $ext = explode('.', $filename);
  12490. $ext = strtolower($ext[sizeof($ext) - 1]);
  12491. $myrow['path'] = rawurlencode($myrow['path']);
  12492. $output = $filename;
  12493. break;
  12494. }
  12495. return stripslashes($output);
  12496. }
  12497. /**
  12498. * Get the parent names for the current item.
  12499. *
  12500. * @param int $newItemId Optional. The item ID
  12501. *
  12502. * @return array
  12503. */
  12504. public function getCurrentItemParentNames($newItemId = 0)
  12505. {
  12506. $newItemId = $newItemId ?: $this->get_current_item_id();
  12507. $return = [];
  12508. $item = $this->getItem($newItemId);
  12509. $parent = $this->getItem($item->get_parent());
  12510. while ($parent) {
  12511. $return[] = $parent->get_title();
  12512. $parent = $this->getItem($parent->get_parent());
  12513. }
  12514. return array_reverse($return);
  12515. }
  12516. /**
  12517. * Reads and process "lp_subscription_settings" setting.
  12518. *
  12519. * @return array
  12520. */
  12521. public static function getSubscriptionSettings()
  12522. {
  12523. $subscriptionSettings = api_get_configuration_value('lp_subscription_settings');
  12524. if (empty($subscriptionSettings)) {
  12525. // By default allow both settings
  12526. $subscriptionSettings = [
  12527. 'allow_add_users_to_lp' => true,
  12528. 'allow_add_users_to_lp_category' => true,
  12529. ];
  12530. } else {
  12531. $subscriptionSettings = $subscriptionSettings['options'];
  12532. }
  12533. return $subscriptionSettings;
  12534. }
  12535. /**
  12536. * Exports a LP to a courseBuilder zip file. It adds the documents related to the LP.
  12537. */
  12538. public function exportToCourseBuildFormat()
  12539. {
  12540. if (!api_is_allowed_to_edit()) {
  12541. return false;
  12542. }
  12543. $courseBuilder = new CourseBuilder();
  12544. $itemList = [];
  12545. /** @var learnpathItem $item */
  12546. foreach ($this->items as $item) {
  12547. $itemList[$item->get_type()][] = $item->get_path();
  12548. }
  12549. if (empty($itemList)) {
  12550. return false;
  12551. }
  12552. if (isset($itemList['document'])) {
  12553. // Get parents
  12554. foreach ($itemList['document'] as $documentId) {
  12555. $documentInfo = DocumentManager::get_document_data_by_id($documentId, api_get_course_id(), true);
  12556. if (!empty($documentInfo['parents'])) {
  12557. foreach ($documentInfo['parents'] as $parentInfo) {
  12558. if (in_array($parentInfo['iid'], $itemList['document'])) {
  12559. continue;
  12560. }
  12561. $itemList['document'][] = $parentInfo['iid'];
  12562. }
  12563. }
  12564. }
  12565. $courseInfo = api_get_course_info();
  12566. foreach ($itemList['document'] as $documentId) {
  12567. $documentInfo = DocumentManager::get_document_data_by_id($documentId, api_get_course_id());
  12568. $items = DocumentManager::get_resources_from_source_html(
  12569. $documentInfo['absolute_path'],
  12570. true,
  12571. TOOL_DOCUMENT
  12572. );
  12573. if (!empty($items)) {
  12574. foreach ($items as $item) {
  12575. // Get information about source url
  12576. $url = $item[0]; // url
  12577. $scope = $item[1]; // scope (local, remote)
  12578. $type = $item[2]; // type (rel, abs, url)
  12579. $origParseUrl = parse_url($url);
  12580. $realOrigPath = isset($origParseUrl['path']) ? $origParseUrl['path'] : null;
  12581. if ($scope == 'local') {
  12582. if ($type == 'abs' || $type == 'rel') {
  12583. $documentFile = strstr($realOrigPath, 'document');
  12584. if (strpos($realOrigPath, $documentFile) !== false) {
  12585. $documentFile = str_replace('document', '', $documentFile);
  12586. $itemDocumentId = DocumentManager::get_document_id($courseInfo, $documentFile);
  12587. // Document found! Add it to the list
  12588. if ($itemDocumentId) {
  12589. $itemList['document'][] = $itemDocumentId;
  12590. }
  12591. }
  12592. }
  12593. }
  12594. }
  12595. }
  12596. }
  12597. $courseBuilder->build_documents(
  12598. api_get_session_id(),
  12599. $this->get_course_int_id(),
  12600. true,
  12601. $itemList['document']
  12602. );
  12603. }
  12604. if (isset($itemList['quiz'])) {
  12605. $courseBuilder->build_quizzes(
  12606. api_get_session_id(),
  12607. $this->get_course_int_id(),
  12608. true,
  12609. $itemList['quiz']
  12610. );
  12611. }
  12612. require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
  12613. /*if (!empty($itemList['thread'])) {
  12614. $postList = [];
  12615. foreach ($itemList['thread'] as $postId) {
  12616. $post = get_post_information($postId);
  12617. if ($post) {
  12618. if (!isset($itemList['forum'])) {
  12619. $itemList['forum'] = [];
  12620. }
  12621. $itemList['forum'][] = $post['forum_id'];
  12622. $postList[] = $postId;
  12623. }
  12624. }
  12625. if (!empty($postList)) {
  12626. $courseBuilder->build_forum_posts(
  12627. $this->get_course_int_id(),
  12628. null,
  12629. null,
  12630. $postList
  12631. );
  12632. }
  12633. }*/
  12634. if (!empty($itemList['thread'])) {
  12635. $threadList = [];
  12636. $em = Database::getManager();
  12637. $repo = $em->getRepository('ChamiloCourseBundle:CForumThread');
  12638. foreach ($itemList['thread'] as $threadId) {
  12639. /** @var \Chamilo\CourseBundle\Entity\CForumThread $thread */
  12640. $thread = $repo->find($threadId);
  12641. if ($thread) {
  12642. $itemList['forum'][] = $thread->getForumId();
  12643. $threadList[] = $thread->getIid();
  12644. }
  12645. }
  12646. if (!empty($threadList)) {
  12647. $courseBuilder->build_forum_topics(
  12648. api_get_session_id(),
  12649. $this->get_course_int_id(),
  12650. null,
  12651. $threadList
  12652. );
  12653. }
  12654. }
  12655. $forumCategoryList = [];
  12656. if (isset($itemList['forum'])) {
  12657. foreach ($itemList['forum'] as $forumId) {
  12658. $forumInfo = get_forums($forumId);
  12659. $forumCategoryList[] = $forumInfo['forum_category'];
  12660. }
  12661. }
  12662. if (!empty($forumCategoryList)) {
  12663. $courseBuilder->build_forum_category(
  12664. api_get_session_id(),
  12665. $this->get_course_int_id(),
  12666. true,
  12667. $forumCategoryList
  12668. );
  12669. }
  12670. if (!empty($itemList['forum'])) {
  12671. $courseBuilder->build_forums(
  12672. api_get_session_id(),
  12673. $this->get_course_int_id(),
  12674. true,
  12675. $itemList['forum']
  12676. );
  12677. }
  12678. if (isset($itemList['link'])) {
  12679. $courseBuilder->build_links(
  12680. api_get_session_id(),
  12681. $this->get_course_int_id(),
  12682. true,
  12683. $itemList['link']
  12684. );
  12685. }
  12686. if (!empty($itemList['student_publication'])) {
  12687. $courseBuilder->build_works(
  12688. api_get_session_id(),
  12689. $this->get_course_int_id(),
  12690. true,
  12691. $itemList['student_publication']
  12692. );
  12693. }
  12694. $courseBuilder->build_learnpaths(
  12695. api_get_session_id(),
  12696. $this->get_course_int_id(),
  12697. true,
  12698. [$this->get_id()],
  12699. false
  12700. );
  12701. $courseBuilder->restoreDocumentsFromList();
  12702. $zipFile = CourseArchiver::createBackup($courseBuilder->course);
  12703. $zipPath = CourseArchiver::getBackupDir().$zipFile;
  12704. $result = DocumentManager::file_send_for_download(
  12705. $zipPath,
  12706. true,
  12707. $this->get_name().'.zip'
  12708. );
  12709. if ($result) {
  12710. api_not_allowed();
  12711. }
  12712. return true;
  12713. }
  12714. /**
  12715. * Get whether this is a learning path with the accumulated work time or not.
  12716. *
  12717. * @return int
  12718. */
  12719. public function getAccumulateWorkTime()
  12720. {
  12721. return (int) $this->accumulateWorkTime;
  12722. }
  12723. /**
  12724. * Get whether this is a learning path with the accumulated work time or not.
  12725. *
  12726. * @return int
  12727. */
  12728. public function getAccumulateWorkTimeTotalCourse()
  12729. {
  12730. $table = Database::get_course_table(TABLE_LP_MAIN);
  12731. $sql = "SELECT SUM(accumulate_work_time) AS total
  12732. FROM $table
  12733. WHERE c_id = ".$this->course_int_id;
  12734. $result = Database::query($sql);
  12735. $row = Database::fetch_array($result);
  12736. return (int) $row['total'];
  12737. }
  12738. /**
  12739. * Set whether this is a learning path with the accumulated work time or not.
  12740. *
  12741. * @param int $value (0 = false, 1 = true)
  12742. *
  12743. * @return bool
  12744. */
  12745. public function setAccumulateWorkTime($value)
  12746. {
  12747. if (!api_get_configuration_value('lp_minimum_time')) {
  12748. return false;
  12749. }
  12750. $this->accumulateWorkTime = (int) $value;
  12751. $table = Database::get_course_table(TABLE_LP_MAIN);
  12752. $lp_id = $this->get_id();
  12753. $sql = "UPDATE $table SET accumulate_work_time = ".$this->accumulateWorkTime."
  12754. WHERE c_id = ".$this->course_int_id." AND id = $lp_id";
  12755. Database::query($sql);
  12756. return true;
  12757. }
  12758. /**
  12759. * @param int $lpId
  12760. * @param int $courseId
  12761. *
  12762. * @return mixed
  12763. */
  12764. public static function getAccumulateWorkTimePrerequisite($lpId, $courseId)
  12765. {
  12766. $lpId = (int) $lpId;
  12767. $courseId = (int) $courseId;
  12768. $table = Database::get_course_table(TABLE_LP_MAIN);
  12769. $sql = "SELECT accumulate_work_time
  12770. FROM $table
  12771. WHERE c_id = $courseId AND id = $lpId";
  12772. $result = Database::query($sql);
  12773. $row = Database::fetch_array($result);
  12774. return $row['accumulate_work_time'];
  12775. }
  12776. /**
  12777. * @param int $courseId
  12778. *
  12779. * @return int
  12780. */
  12781. public static function getAccumulateWorkTimeTotal($courseId)
  12782. {
  12783. $table = Database::get_course_table(TABLE_LP_MAIN);
  12784. $courseId = (int) $courseId;
  12785. $sql = "SELECT SUM(accumulate_work_time) AS total
  12786. FROM $table
  12787. WHERE c_id = $courseId";
  12788. $result = Database::query($sql);
  12789. $row = Database::fetch_array($result);
  12790. return (int) $row['total'];
  12791. }
  12792. /**
  12793. * In order to use the lp icon option you need to create the "lp_icon" LP extra field
  12794. * and put the images in.
  12795. *
  12796. * @return array
  12797. */
  12798. public static function getIconSelect()
  12799. {
  12800. $theme = api_get_visual_theme();
  12801. $path = api_get_path(SYS_PUBLIC_PATH).'css/themes/'.$theme.'/lp_icons/';
  12802. $icons = ['' => get_lang('SelectAnOption')];
  12803. if (is_dir($path)) {
  12804. $finder = new Finder();
  12805. $finder->files()->in($path);
  12806. $allowedExtensions = ['jpeg', 'jpg', 'png'];
  12807. /** @var SplFileInfo $file */
  12808. foreach ($finder as $file) {
  12809. if (in_array(strtolower($file->getExtension()), $allowedExtensions)) {
  12810. $icons[$file->getFilename()] = $file->getFilename();
  12811. }
  12812. }
  12813. }
  12814. return $icons;
  12815. }
  12816. /**
  12817. * @param int $lpId
  12818. *
  12819. * @return string
  12820. */
  12821. public static function getSelectedIcon($lpId)
  12822. {
  12823. $extraFieldValue = new ExtraFieldValue('lp');
  12824. $lpIcon = $extraFieldValue->get_values_by_handler_and_field_variable($lpId, 'lp_icon');
  12825. $icon = '';
  12826. if (!empty($lpIcon) && isset($lpIcon['value'])) {
  12827. $icon = $lpIcon['value'];
  12828. }
  12829. return $icon;
  12830. }
  12831. /**
  12832. * @param int $lpId
  12833. *
  12834. * @return string
  12835. */
  12836. public static function getSelectedIconHtml($lpId)
  12837. {
  12838. $icon = self::getSelectedIcon($lpId);
  12839. if (empty($icon)) {
  12840. return '';
  12841. }
  12842. $theme = api_get_visual_theme();
  12843. $path = api_get_path(WEB_PUBLIC_PATH).'css/themes/'.$theme.'/lp_icons/'.$icon;
  12844. return Display::img($path);
  12845. }
  12846. /**
  12847. * Get the depth level of LP item.
  12848. *
  12849. * @param array $items
  12850. * @param int $currentItemId
  12851. *
  12852. * @return int
  12853. */
  12854. private static function get_level_for_item($items, $currentItemId)
  12855. {
  12856. $parentItemId = 0;
  12857. if (isset($items[$currentItemId])) {
  12858. $parentItemId = $items[$currentItemId]->parent;
  12859. }
  12860. if ($parentItemId == 0) {
  12861. return 0;
  12862. } else {
  12863. return self::get_level_for_item($items, $parentItemId) + 1;
  12864. }
  12865. }
  12866. /**
  12867. * Generate the link for a learnpath category as course tool.
  12868. *
  12869. * @param int $categoryId
  12870. *
  12871. * @return string
  12872. */
  12873. private static function getCategoryLinkForTool($categoryId)
  12874. {
  12875. $categoryId = (int) $categoryId;
  12876. $link = 'lp/lp_controller.php?'.api_get_cidreq().'&'
  12877. .http_build_query(
  12878. [
  12879. 'action' => 'view_category',
  12880. 'id' => $categoryId,
  12881. ]
  12882. );
  12883. return $link;
  12884. }
  12885. /**
  12886. * Return the scorm item type object with spaces replaced with _
  12887. * The return result is use to build a css classname like scorm_type_$return.
  12888. *
  12889. * @param $in_type
  12890. *
  12891. * @return mixed
  12892. */
  12893. private static function format_scorm_type_item($in_type)
  12894. {
  12895. return str_replace(' ', '_', $in_type);
  12896. }
  12897. /**
  12898. * Check and obtain the lp final item if exist.
  12899. *
  12900. * @return learnpathItem
  12901. */
  12902. private function getFinalItem()
  12903. {
  12904. if (empty($this->items)) {
  12905. return null;
  12906. }
  12907. foreach ($this->items as $item) {
  12908. if ($item->type !== 'final_item') {
  12909. continue;
  12910. }
  12911. return $item;
  12912. }
  12913. }
  12914. /**
  12915. * Get the LP Final Item Template.
  12916. *
  12917. * @return string
  12918. */
  12919. private function getFinalItemTemplate()
  12920. {
  12921. return file_get_contents(api_get_path(SYS_CODE_PATH).'lp/final_item_template/template.html');
  12922. }
  12923. /**
  12924. * Get the LP Final Item Url.
  12925. *
  12926. * @return string
  12927. */
  12928. private function getSavedFinalItem()
  12929. {
  12930. $finalItem = $this->getFinalItem();
  12931. $doc = DocumentManager::get_document_data_by_id(
  12932. $finalItem->path,
  12933. $this->cc
  12934. );
  12935. if ($doc && file_exists($doc['absolute_path'])) {
  12936. return file_get_contents($doc['absolute_path']);
  12937. }
  12938. return '';
  12939. }
  12940. }