course.lib.php 233 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456
  1. <?php
  2. /* For licensing terms, see /license.txt*/
  3. use Chamilo\CoreBundle\Entity\Course;
  4. use Chamilo\CoreBundle\Entity\ExtraField as EntityExtraField;
  5. use Chamilo\CourseBundle\Component\CourseCopy\CourseBuilder;
  6. use Chamilo\CourseBundle\Component\CourseCopy\CourseRestorer;
  7. use ChamiloSession as Session;
  8. /**
  9. * Class CourseManager.
  10. *
  11. * This is the course library for Chamilo.
  12. *
  13. * All main course functions should be placed here.
  14. *
  15. * Many functions of this library deal with providing support for
  16. * virtual/linked/combined courses (this was already used in several universities
  17. * but not available in standard Chamilo).
  18. *
  19. * There are probably some places left with the wrong code.
  20. *
  21. * @package chamilo.library
  22. */
  23. class CourseManager
  24. {
  25. const MAX_COURSE_LENGTH_CODE = 40;
  26. /** This constant is used to show separate user names in the course
  27. * list (userportal), footer, etc */
  28. const USER_SEPARATOR = ' |';
  29. const COURSE_FIELD_TYPE_CHECKBOX = 10;
  30. public $columns = [];
  31. /**
  32. * Creates a course.
  33. *
  34. * @param array $params Columns in the main.course table.
  35. * @param int $authorId Optional.
  36. * @param int $accessUrlId Optional.
  37. *
  38. * @return mixed false if the course was not created, array with the course info
  39. */
  40. public static function create_course($params, $authorId = 0, $accessUrlId = 0)
  41. {
  42. global $_configuration;
  43. $hook = HookCreateCourse::create();
  44. // Check portal limits
  45. $accessUrlId = empty($accessUrlId)
  46. ? (api_get_multiple_access_url() ? api_get_current_access_url_id() : 1)
  47. : $accessUrlId;
  48. $authorId = empty($authorId) ? api_get_user_id() : (int) $authorId;
  49. if (isset($_configuration[$accessUrlId]) && is_array($_configuration[$accessUrlId])) {
  50. $return = self::checkCreateCourseAccessUrlParam(
  51. $_configuration,
  52. $accessUrlId,
  53. 'hosting_limit_courses',
  54. 'PortalCoursesLimitReached'
  55. );
  56. if ($return != false) {
  57. return $return;
  58. }
  59. $return = self::checkCreateCourseAccessUrlParam(
  60. $_configuration,
  61. $accessUrlId,
  62. 'hosting_limit_active_courses',
  63. 'PortalActiveCoursesLimitReached'
  64. );
  65. if ($return != false) {
  66. return $return;
  67. }
  68. }
  69. if (empty($params['title'])) {
  70. return false;
  71. }
  72. if (empty($params['wanted_code'])) {
  73. $params['wanted_code'] = $params['title'];
  74. // Check whether the requested course code has already been occupied.
  75. $substring = api_substr($params['title'], 0, self::MAX_COURSE_LENGTH_CODE);
  76. if ($substring === false || empty($substring)) {
  77. return false;
  78. } else {
  79. $params['wanted_code'] = self::generate_course_code($substring);
  80. }
  81. }
  82. // Create the course keys
  83. $keys = AddCourse::define_course_keys($params['wanted_code']);
  84. $params['exemplary_content'] = isset($params['exemplary_content']) ? $params['exemplary_content'] : false;
  85. if (count($keys)) {
  86. $params['code'] = $keys['currentCourseCode'];
  87. $params['visual_code'] = $keys['currentCourseId'];
  88. $params['directory'] = $keys['currentCourseRepository'];
  89. $course_info = api_get_course_info($params['code']);
  90. if (empty($course_info)) {
  91. $course_id = AddCourse::register_course($params, $accessUrlId);
  92. $course_info = api_get_course_info_by_id($course_id);
  93. if ($hook) {
  94. $hook->setEventData(['course_info' => $course_info]);
  95. $hook->notifyCreateCourse(HOOK_EVENT_TYPE_POST);
  96. }
  97. if (!empty($course_info)) {
  98. self::fillCourse($course_info, $params, $authorId);
  99. return $course_info;
  100. }
  101. }
  102. }
  103. return false;
  104. }
  105. /**
  106. * Returns all the information of a given course code.
  107. *
  108. * @param string $course_code , the course code
  109. *
  110. * @return array with all the fields of the course table
  111. *
  112. * @deprecated Use api_get_course_info() instead
  113. *
  114. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  115. * @assert ('') === false
  116. */
  117. public static function get_course_information($course_code)
  118. {
  119. return Database::fetch_array(
  120. Database::query(
  121. "SELECT *, id as real_id FROM ".Database::get_main_table(TABLE_MAIN_COURSE)."
  122. WHERE code = '".Database::escape_string($course_code)."'"
  123. ),
  124. 'ASSOC'
  125. );
  126. }
  127. /**
  128. * Returns a list of courses. Should work with quickform syntax.
  129. *
  130. * @param int $from Offset (from the 7th = '6'). Optional.
  131. * @param int $howmany Number of results we want. Optional.
  132. * @param int $orderby The column we want to order it by. Optional, defaults to first column.
  133. * @param string $orderdirection The direction of the order (ASC or DESC). Optional, defaults to ASC.
  134. * @param int $visibility the visibility of the course, or all by default
  135. * @param string $startwith If defined, only return results for which the course *title* begins with this string
  136. * @param string $urlId The Access URL ID, if using multiple URLs
  137. * @param bool $alsoSearchCode An extension option to indicate that we also want to search for course codes (not *only* titles)
  138. * @param array $conditionsLike
  139. * @param array $onlyThisCourseList
  140. *
  141. * @return array
  142. */
  143. public static function get_courses_list(
  144. $from = 0,
  145. $howmany = 0,
  146. $orderby = 1,
  147. $orderdirection = 'ASC',
  148. $visibility = -1,
  149. $startwith = '',
  150. $urlId = null,
  151. $alsoSearchCode = false,
  152. $conditionsLike = [],
  153. $onlyThisCourseList = []
  154. ) {
  155. $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
  156. $sql = "SELECT course.*, course.id as real_id
  157. FROM $courseTable course ";
  158. if (!empty($urlId)) {
  159. $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  160. $sql .= " INNER JOIN $table url ON (url.c_id = course.id) ";
  161. }
  162. $visibility = (int) $visibility;
  163. if (!empty($startwith)) {
  164. $sql .= "WHERE (title LIKE '".Database::escape_string($startwith)."%' ";
  165. if ($alsoSearchCode) {
  166. $sql .= "OR code LIKE '".Database::escape_string($startwith)."%' ";
  167. }
  168. $sql .= ') ';
  169. if ($visibility !== -1) {
  170. $sql .= " AND visibility = $visibility ";
  171. }
  172. } else {
  173. $sql .= 'WHERE 1 ';
  174. if ($visibility !== -1) {
  175. $sql .= " AND visibility = $visibility ";
  176. }
  177. }
  178. if (!empty($urlId)) {
  179. $urlId = (int) $urlId;
  180. $sql .= " AND access_url_id = $urlId";
  181. }
  182. if (!empty($onlyThisCourseList)) {
  183. $onlyThisCourseList = array_map('intval', $onlyThisCourseList);
  184. $onlyThisCourseList = implode("','", $onlyThisCourseList);
  185. $sql .= " AND course.id IN ('$onlyThisCourseList') ";
  186. }
  187. $allowedFields = [
  188. 'title',
  189. 'code',
  190. ];
  191. if (count($conditionsLike) > 0) {
  192. $sql .= ' AND ';
  193. $temp_conditions = [];
  194. foreach ($conditionsLike as $field => $value) {
  195. if (!in_array($field, $allowedFields)) {
  196. continue;
  197. }
  198. $field = Database::escape_string($field);
  199. $value = Database::escape_string($value);
  200. $simple_like = false;
  201. if ($simple_like) {
  202. $temp_conditions[] = $field." LIKE '$value%'";
  203. } else {
  204. $temp_conditions[] = $field.' LIKE \'%'.$value.'%\'';
  205. }
  206. }
  207. $condition = ' AND ';
  208. if (!empty($temp_conditions)) {
  209. $sql .= implode(' '.$condition.' ', $temp_conditions);
  210. }
  211. }
  212. if (!empty($orderby)) {
  213. $sql .= " ORDER BY ".Database::escape_string($orderby)." ";
  214. } else {
  215. $sql .= ' ORDER BY 1 ';
  216. }
  217. if (!in_array($orderdirection, ['ASC', 'DESC'])) {
  218. $sql .= 'ASC';
  219. } else {
  220. $sql .= ($orderdirection == 'ASC' ? 'ASC' : 'DESC');
  221. }
  222. if (!empty($howmany) && is_int($howmany) and $howmany > 0) {
  223. $sql .= ' LIMIT '.Database::escape_string($howmany);
  224. } else {
  225. $sql .= ' LIMIT 1000000'; //virtually no limit
  226. }
  227. if (!empty($from)) {
  228. $from = intval($from);
  229. $sql .= ' OFFSET '.intval($from);
  230. } else {
  231. $sql .= ' OFFSET 0';
  232. }
  233. $data = [];
  234. $res = Database::query($sql);
  235. if (Database::num_rows($res) > 0) {
  236. while ($row = Database::fetch_array($res, 'ASSOC')) {
  237. $data[] = $row;
  238. }
  239. }
  240. return $data;
  241. }
  242. /**
  243. * Returns the status of a user in a course, which is COURSEMANAGER or STUDENT.
  244. *
  245. * @param int $userId
  246. * @param int $courseId
  247. *
  248. * @return int|bool the status of the user in that course (or false if the user is not in that course)
  249. */
  250. public static function getUserInCourseStatus($userId, $courseId)
  251. {
  252. $courseId = (int) $courseId;
  253. $userId = (int) $userId;
  254. if (empty($courseId)) {
  255. return false;
  256. }
  257. $result = Database::fetch_array(
  258. Database::query(
  259. "SELECT status FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  260. WHERE
  261. c_id = $courseId AND
  262. user_id = $userId"
  263. )
  264. );
  265. return $result['status'];
  266. }
  267. /**
  268. * @param int $userId
  269. * @param int $courseId
  270. *
  271. * @return mixed
  272. */
  273. public static function getUserCourseInfo($userId, $courseId)
  274. {
  275. $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  276. WHERE
  277. c_id = ".intval($courseId)." AND
  278. user_id = ".intval($userId);
  279. $result = Database::fetch_array(Database::query($sql));
  280. return $result;
  281. }
  282. /**
  283. * @param int $userId
  284. * @param int $courseId
  285. * @param bool $isTutor
  286. *
  287. * @return bool
  288. */
  289. public static function updateUserCourseTutor($userId, $courseId, $isTutor)
  290. {
  291. $table = Database::escape_string(TABLE_MAIN_COURSE_USER);
  292. $courseId = intval($courseId);
  293. $isTutor = intval($isTutor);
  294. $sql = "UPDATE $table SET is_tutor = '".$isTutor."'
  295. WHERE
  296. user_id = ".$userId." AND
  297. c_id = ".$courseId;
  298. $result = Database::query($sql);
  299. if (Database::affected_rows($result) > 0) {
  300. return true;
  301. } else {
  302. return false;
  303. }
  304. }
  305. /**
  306. * @param int $userId
  307. * @param int $courseId
  308. *
  309. * @return mixed
  310. */
  311. public static function get_tutor_in_course_status($userId, $courseId)
  312. {
  313. $userId = intval($userId);
  314. $courseId = intval($courseId);
  315. $result = Database::fetch_array(
  316. Database::query(
  317. "SELECT is_tutor
  318. FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  319. WHERE
  320. c_id = $courseId AND
  321. user_id = $userId"
  322. )
  323. );
  324. return $result['is_tutor'];
  325. }
  326. /**
  327. * Unsubscribe one or more users from a course.
  328. *
  329. * @param mixed user_id or an array with user ids
  330. * @param string course code
  331. * @param int session id
  332. *
  333. * @return bool
  334. *
  335. * @assert ('', '') === false
  336. */
  337. public static function unsubscribe_user($user_id, $course_code, $session_id = 0)
  338. {
  339. if (empty($user_id)) {
  340. return false;
  341. }
  342. if (!is_array($user_id)) {
  343. $user_id = [$user_id];
  344. }
  345. if (count($user_id) == 0) {
  346. return false;
  347. }
  348. if (!empty($session_id)) {
  349. $session_id = (int) $session_id;
  350. } else {
  351. $session_id = api_get_session_id();
  352. }
  353. if (empty($course_code)) {
  354. return false;
  355. }
  356. $userList = [];
  357. // Cleaning the $user_id variable
  358. if (is_array($user_id)) {
  359. $new_user_id_list = [];
  360. foreach ($user_id as $my_user_id) {
  361. $new_user_id_list[] = (int) $my_user_id;
  362. }
  363. $new_user_id_list = array_filter($new_user_id_list);
  364. $userList = $new_user_id_list;
  365. $user_ids = implode(',', $new_user_id_list);
  366. } else {
  367. $user_ids = (int) $user_id;
  368. $userList[] = $user_id;
  369. }
  370. $course_info = api_get_course_info($course_code);
  371. $course_id = $course_info['real_id'];
  372. // Unsubscribe user from all groups in the course.
  373. $sql = "DELETE FROM ".Database::get_course_table(TABLE_GROUP_USER)."
  374. WHERE c_id = $course_id AND user_id IN (".$user_ids.")";
  375. Database::query($sql);
  376. $sql = "DELETE FROM ".Database::get_course_table(TABLE_GROUP_TUTOR)."
  377. WHERE c_id = $course_id AND user_id IN (".$user_ids.")";
  378. Database::query($sql);
  379. // Erase user student publications (works) in the course - by André Boivin
  380. if (!empty($userList)) {
  381. require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
  382. foreach ($userList as $userId) {
  383. // Getting all work from user
  384. $workList = getWorkPerUser($userId);
  385. if (!empty($workList)) {
  386. foreach ($workList as $work) {
  387. $work = $work['work'];
  388. // Getting user results
  389. if (!empty($work->user_results)) {
  390. foreach ($work->user_results as $workSent) {
  391. deleteWorkItem($workSent['id'], $course_info);
  392. }
  393. }
  394. }
  395. }
  396. }
  397. }
  398. // Unsubscribe user from all blogs in the course.
  399. $sql = "DELETE FROM ".Database::get_course_table(TABLE_BLOGS_REL_USER)."
  400. WHERE c_id = $course_id AND user_id IN ($user_ids)";
  401. Database::query($sql);
  402. $sql = "DELETE FROM ".Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER)."
  403. WHERE c_id = $course_id AND user_id IN ($user_ids)";
  404. Database::query($sql);
  405. // Deleting users in forum_notification and mailqueue course tables
  406. $sql = "DELETE FROM ".Database::get_course_table(TABLE_FORUM_NOTIFICATION)."
  407. WHERE c_id = $course_id AND user_id IN ($user_ids)";
  408. Database::query($sql);
  409. $sql = "DELETE FROM ".Database::get_course_table(TABLE_FORUM_MAIL_QUEUE)."
  410. WHERE c_id = $course_id AND user_id IN ($user_ids)";
  411. Database::query($sql);
  412. // Unsubscribe user from the course.
  413. if (!empty($session_id)) {
  414. foreach ($userList as $uid) {
  415. SessionManager::unSubscribeUserFromCourseSession($uid, $course_id, $session_id);
  416. // check if a user is register in the session with other course
  417. $sql = "SELECT user_id FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)."
  418. WHERE session_id = $session_id AND user_id = $uid";
  419. $rs = Database::query($sql);
  420. if (Database::num_rows($rs) == 0) {
  421. SessionManager::unsubscribe_user_from_session($uid, $session_id);
  422. }
  423. }
  424. Event::addEvent(
  425. LOG_UNSUBSCRIBE_USER_FROM_COURSE,
  426. LOG_COURSE_CODE,
  427. $course_code,
  428. api_get_utc_datetime(),
  429. $user_id,
  430. $course_id,
  431. $session_id
  432. );
  433. } else {
  434. $sql = "DELETE FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  435. WHERE
  436. user_id IN ($user_ids) AND
  437. relation_type <> ".COURSE_RELATION_TYPE_RRHH." AND
  438. c_id = $course_id";
  439. Database::query($sql);
  440. // add event to system log
  441. $user_id = api_get_user_id();
  442. Event::addEvent(
  443. LOG_UNSUBSCRIBE_USER_FROM_COURSE,
  444. LOG_COURSE_CODE,
  445. $course_code,
  446. api_get_utc_datetime(),
  447. $user_id,
  448. $course_id
  449. );
  450. foreach ($userList as $userId) {
  451. $userInfo = api_get_user_info($userId);
  452. Event::addEvent(
  453. LOG_UNSUBSCRIBE_USER_FROM_COURSE,
  454. LOG_USER_OBJECT,
  455. $userInfo,
  456. api_get_utc_datetime(),
  457. $user_id,
  458. $course_id
  459. );
  460. }
  461. }
  462. }
  463. /**
  464. * @param string $courseCode
  465. * @param int $status
  466. *
  467. * @return bool
  468. */
  469. public static function autoSubscribeToCourse($courseCode, $status = STUDENT)
  470. {
  471. $courseInfo = api_get_course_info($courseCode);
  472. if (empty($courseInfo)) {
  473. return false;
  474. }
  475. if (api_is_anonymous()) {
  476. return false;
  477. }
  478. if (in_array(
  479. $courseInfo['visibility'],
  480. [
  481. COURSE_VISIBILITY_CLOSED,
  482. COURSE_VISIBILITY_REGISTERED,
  483. COURSE_VISIBILITY_HIDDEN,
  484. ]
  485. )
  486. ) {
  487. Display::addFlash(
  488. Display::return_message(
  489. get_lang('SubscribingNotAllowed'),
  490. 'warning'
  491. )
  492. );
  493. return false;
  494. }
  495. return self::subscribeUser(api_get_user_id(), $courseInfo['code'], $status);
  496. }
  497. /**
  498. * Subscribe a user to a course. No checks are performed here to see if
  499. * course subscription is allowed.
  500. *
  501. * @param int $userId
  502. * @param string $courseCode
  503. * @param int $status (STUDENT, COURSEMANAGER, COURSE_ADMIN, NORMAL_COURSE_MEMBER)
  504. * @param int $sessionId
  505. * @param int $userCourseCategoryId
  506. * @param bool $checkTeacherPermission
  507. *
  508. * @return bool True on success, false on failure
  509. *
  510. * @assert ('', '') === false
  511. */
  512. public static function subscribeUser(
  513. $userId,
  514. $courseCode,
  515. $status = STUDENT,
  516. $sessionId = 0,
  517. $userCourseCategoryId = 0,
  518. $checkTeacherPermission = true
  519. ) {
  520. $userId = (int) $userId;
  521. $status = (int) $status;
  522. if (empty($userId) || empty($courseCode)) {
  523. return false;
  524. }
  525. $courseInfo = api_get_course_info($courseCode);
  526. if (empty($courseInfo)) {
  527. Display::addFlash(Display::return_message(get_lang('CourseDoesNotExist'), 'warning'));
  528. return false;
  529. }
  530. $userInfo = api_get_user_info($userId);
  531. if (empty($userInfo)) {
  532. Display::addFlash(Display::return_message(get_lang('UserDoesNotExist'), 'warning'));
  533. return false;
  534. }
  535. $courseId = $courseInfo['real_id'];
  536. $courseCode = $courseInfo['code'];
  537. $userCourseCategoryId = (int) $userCourseCategoryId;
  538. $sessionId = empty($sessionId) ? api_get_session_id() : (int) $sessionId;
  539. $status = $status === STUDENT || $status === COURSEMANAGER ? $status : STUDENT;
  540. $courseUserTable = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  541. if (!empty($sessionId)) {
  542. SessionManager::subscribe_users_to_session_course(
  543. [$userId],
  544. $sessionId,
  545. $courseCode
  546. );
  547. // Add event to the system log
  548. Event::addEvent(
  549. LOG_SUBSCRIBE_USER_TO_COURSE,
  550. LOG_COURSE_CODE,
  551. $courseCode,
  552. api_get_utc_datetime(),
  553. api_get_user_id(),
  554. $courseId,
  555. $sessionId
  556. );
  557. Event::addEvent(
  558. LOG_SUBSCRIBE_USER_TO_COURSE,
  559. LOG_USER_OBJECT,
  560. $userInfo,
  561. api_get_utc_datetime(),
  562. api_get_user_id(),
  563. $courseId,
  564. $sessionId
  565. );
  566. return true;
  567. } else {
  568. // Check whether the user has not been already subscribed to the course.
  569. $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  570. WHERE
  571. user_id = $userId AND
  572. relation_type <> ".COURSE_RELATION_TYPE_RRHH." AND
  573. c_id = $courseId
  574. ";
  575. if (Database::num_rows(Database::query($sql)) > 0) {
  576. Display::addFlash(Display::return_message(get_lang('AlreadyRegisteredToCourse'), 'warning'));
  577. return false;
  578. }
  579. if ($checkTeacherPermission && !api_is_course_admin()) {
  580. // Check in advance whether subscription is allowed or not for this course.
  581. if ((int) $courseInfo['subscribe'] === SUBSCRIBE_NOT_ALLOWED) {
  582. Display::addFlash(Display::return_message(get_lang('SubscriptionNotAllowed'), 'warning'));
  583. return false;
  584. }
  585. }
  586. if ($status === STUDENT) {
  587. // Check if max students per course extra field is set
  588. $extraFieldValue = new ExtraFieldValue('course');
  589. $value = $extraFieldValue->get_values_by_handler_and_field_variable($courseId, 'max_subscribed_students');
  590. if (!empty($value) && isset($value['value'])) {
  591. $maxStudents = $value['value'];
  592. if ($maxStudents !== '') {
  593. $maxStudents = (int) $maxStudents;
  594. $count = self::get_user_list_from_course_code(
  595. $courseCode,
  596. 0,
  597. null,
  598. null,
  599. STUDENT,
  600. true,
  601. false
  602. );
  603. if ($count >= $maxStudents) {
  604. Display::addFlash(Display::return_message(get_lang('MaxNumberSubscribedStudentsReached'), 'warning'));
  605. return false;
  606. }
  607. }
  608. }
  609. }
  610. $maxSort = api_max_sort_value('0', $userId);
  611. $params = [
  612. 'c_id' => $courseId,
  613. 'user_id' => $userId,
  614. 'status' => $status,
  615. 'sort' => $maxSort + 1,
  616. 'relation_type' => 0,
  617. 'user_course_cat' => (int) $userCourseCategoryId,
  618. ];
  619. $insertId = Database::insert($courseUserTable, $params);
  620. if ($insertId) {
  621. Display::addFlash(
  622. Display::return_message(
  623. sprintf(
  624. get_lang('UserXAddedToCourseX'),
  625. $userInfo['complete_name_with_username'],
  626. $courseInfo['title']
  627. )
  628. )
  629. );
  630. $send = api_get_course_setting('email_alert_to_teacher_on_new_user_in_course', $courseCode);
  631. if ($send == 1) {
  632. self::email_to_tutor(
  633. $userId,
  634. $courseInfo['real_id'],
  635. false
  636. );
  637. } elseif ($send == 2) {
  638. self::email_to_tutor(
  639. $userId,
  640. $courseInfo['real_id'],
  641. true
  642. );
  643. }
  644. $subscribe = (int) api_get_course_setting('subscribe_users_to_forum_notifications', $courseCode);
  645. if ($subscribe === 1) {
  646. require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
  647. $forums = get_forums(0, $courseCode, true, $sessionId);
  648. foreach ($forums as $forum) {
  649. $forumId = $forum['iid'];
  650. set_notification('forum', $forumId, false, $userInfo, $courseInfo);
  651. }
  652. }
  653. // Add event to the system log
  654. Event::addEvent(
  655. LOG_SUBSCRIBE_USER_TO_COURSE,
  656. LOG_COURSE_CODE,
  657. $courseCode,
  658. api_get_utc_datetime(),
  659. api_get_user_id(),
  660. $courseId
  661. );
  662. Event::addEvent(
  663. LOG_SUBSCRIBE_USER_TO_COURSE,
  664. LOG_USER_OBJECT,
  665. $userInfo,
  666. api_get_utc_datetime(),
  667. api_get_user_id(),
  668. $courseId
  669. );
  670. return true;
  671. }
  672. return false;
  673. }
  674. }
  675. /**
  676. * Get the course id based on the original id and field name in the
  677. * extra fields. Returns 0 if course was not found.
  678. *
  679. * @param string $original_course_id_value
  680. * @param string $original_course_id_name
  681. *
  682. * @return int Course id
  683. *
  684. * @assert ('', '') === false
  685. */
  686. public static function get_course_code_from_original_id(
  687. $original_course_id_value,
  688. $original_course_id_name
  689. ) {
  690. $t_cfv = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  691. $table_field = Database::get_main_table(TABLE_EXTRA_FIELD);
  692. $extraFieldType = EntityExtraField::COURSE_FIELD_TYPE;
  693. $original_course_id_value = Database::escape_string($original_course_id_value);
  694. $original_course_id_name = Database::escape_string($original_course_id_name);
  695. $sql = "SELECT item_id
  696. FROM $table_field cf
  697. INNER JOIN $t_cfv cfv
  698. ON cfv.field_id=cf.id
  699. WHERE
  700. variable = '$original_course_id_name' AND
  701. value = '$original_course_id_value' AND
  702. cf.extra_field_type = $extraFieldType
  703. ";
  704. $res = Database::query($sql);
  705. $row = Database::fetch_object($res);
  706. if ($row) {
  707. return $row->item_id;
  708. } else {
  709. return 0;
  710. }
  711. }
  712. /**
  713. * Gets the course code from the course id. Returns null if course id was not found.
  714. *
  715. * @param int $id Course id
  716. *
  717. * @return string Course code
  718. * @assert ('') === false
  719. */
  720. public static function get_course_code_from_course_id($id)
  721. {
  722. $table = Database::get_main_table(TABLE_MAIN_COURSE);
  723. $id = intval($id);
  724. $sql = "SELECT code FROM $table WHERE id = $id ";
  725. $res = Database::query($sql);
  726. $row = Database::fetch_object($res);
  727. if ($row) {
  728. return $row->code;
  729. } else {
  730. return null;
  731. }
  732. }
  733. /**
  734. * Add the user $userId visibility to the course $courseCode in the catalogue.
  735. *
  736. * @author David Nos (https://github.com/dnos)
  737. *
  738. * @param int $userId the id of the user
  739. * @param string $courseCode the course code
  740. * @param int $visible (optional) The course visibility in the catalogue to the user (1=visible, 0=invisible)
  741. *
  742. * @return bool true if added succesfully, false otherwise
  743. */
  744. public static function addUserVisibilityToCourseInCatalogue(
  745. $userId,
  746. $courseCode,
  747. $visible = 1
  748. ) {
  749. $debug = false;
  750. $userTable = Database::get_main_table(TABLE_MAIN_USER);
  751. $courseUserTable = Database::get_main_table(TABLE_MAIN_COURSE_CATALOGUE_USER);
  752. $visible = (int) $visible;
  753. if (empty($userId) || empty($courseCode) || ($userId != strval(intval($userId)))) {
  754. return false;
  755. }
  756. $courseCode = Database::escape_string($courseCode);
  757. $courseInfo = api_get_course_info($courseCode);
  758. $courseId = $courseInfo['real_id'];
  759. // Check in advance whether the user has already been registered on the platform.
  760. $sql = "SELECT status FROM ".$userTable." WHERE user_id = $userId ";
  761. if (Database::num_rows(Database::query($sql)) == 0) {
  762. if ($debug) {
  763. error_log('The user has not been registered to the platform');
  764. }
  765. return false; // The user has not been registered to the platform.
  766. }
  767. // Check whether the user has already been registered to the course visibility in the catalogue.
  768. $sql = "SELECT * FROM $courseUserTable
  769. WHERE
  770. user_id = $userId AND
  771. visible = $visible AND
  772. c_id = $courseId";
  773. if (Database::num_rows(Database::query($sql)) > 0) {
  774. if ($debug) {
  775. error_log('The user has been already registered to the course visibility in the catalogue');
  776. }
  777. return true; // The visibility of the user to the course in the catalogue does already exist.
  778. }
  779. // Register the user visibility to course in catalogue.
  780. $params = [
  781. 'user_id' => $userId,
  782. 'c_id' => $courseId,
  783. 'visible' => $visible,
  784. ];
  785. $insertId = Database::insert($courseUserTable, $params);
  786. return $insertId;
  787. }
  788. /**
  789. * Remove the user $userId visibility to the course $courseCode in the catalogue.
  790. *
  791. * @author David Nos (https://github.com/dnos)
  792. *
  793. * @param int $userId the id of the user
  794. * @param string $courseCode the course code
  795. * @param int $visible (optional) The course visibility in the catalogue to the user (1=visible, 0=invisible)
  796. *
  797. * @return bool true if removed succesfully or register not found, false otherwise
  798. */
  799. public static function removeUserVisibilityToCourseInCatalogue(
  800. $userId,
  801. $courseCode,
  802. $visible = 1
  803. ) {
  804. $courseUserTable = Database::get_main_table(TABLE_MAIN_COURSE_CATALOGUE_USER);
  805. if (empty($userId) || empty($courseCode) || ($userId != strval(intval($userId)))) {
  806. return false;
  807. }
  808. $courseCode = Database::escape_string($courseCode);
  809. $courseInfo = api_get_course_info($courseCode);
  810. $courseId = $courseInfo['real_id'];
  811. // Check whether the user has already been registered to the course visibility in the catalogue.
  812. $sql = "SELECT * FROM $courseUserTable
  813. WHERE
  814. user_id = $userId AND
  815. visible = $visible AND
  816. c_id = $courseId";
  817. if (Database::num_rows(Database::query($sql)) > 0) {
  818. $cond = [
  819. 'user_id = ? AND c_id = ? AND visible = ? ' => [
  820. $userId,
  821. $courseId,
  822. $visible,
  823. ],
  824. ];
  825. return Database::delete($courseUserTable, $cond);
  826. } else {
  827. return true; // Register does not exist
  828. }
  829. }
  830. /**
  831. * @param string $code
  832. *
  833. * @return bool if there already are one or more courses
  834. * with the same code OR visual_code (visualcode), false otherwise
  835. */
  836. public static function course_code_exists($code)
  837. {
  838. $code = Database::escape_string($code);
  839. $sql = "SELECT COUNT(*) as number
  840. FROM ".Database::get_main_table(TABLE_MAIN_COURSE)."
  841. WHERE code = '$code' OR visual_code = '$code'";
  842. $result = Database::fetch_array(Database::query($sql));
  843. return $result['number'] > 0;
  844. }
  845. /**
  846. * @param int $user_id
  847. * @param string $startsWith Optional
  848. *
  849. * @return array an array with the course info of all the courses (real and virtual)
  850. * of which the current user is course admin
  851. */
  852. public static function get_course_list_of_user_as_course_admin($user_id, $startsWith = '')
  853. {
  854. if ($user_id != strval(intval($user_id))) {
  855. return [];
  856. }
  857. // Definitions database tables and variables
  858. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  859. $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  860. $user_id = intval($user_id);
  861. $data = [];
  862. $sql = "SELECT
  863. course.code,
  864. course.title,
  865. course.id,
  866. course.id as real_id,
  867. course.category_code
  868. FROM $tbl_course_user as course_rel_user
  869. INNER JOIN $tbl_course as course
  870. ON course.id = course_rel_user.c_id
  871. WHERE
  872. course_rel_user.user_id = $user_id AND
  873. course_rel_user.status = 1
  874. ";
  875. if (api_get_multiple_access_url()) {
  876. $tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  877. $access_url_id = api_get_current_access_url_id();
  878. if ($access_url_id != -1) {
  879. $sql = "
  880. SELECT
  881. course.code,
  882. course.title,
  883. course.id,
  884. course.id as real_id
  885. FROM $tbl_course_user as course_rel_user
  886. INNER JOIN $tbl_course as course
  887. ON course.id = course_rel_user.c_id
  888. INNER JOIN $tbl_course_rel_access_url course_rel_url
  889. ON (course_rel_url.c_id = course.id)
  890. WHERE
  891. access_url_id = $access_url_id AND
  892. course_rel_user.user_id = $user_id AND
  893. course_rel_user.status = 1
  894. ";
  895. }
  896. }
  897. if (!empty($startsWith)) {
  898. $startsWith = Database::escape_string($startsWith);
  899. $sql .= " AND (course.title LIKE '$startsWith%' OR course.code LIKE '$startsWith%')";
  900. }
  901. $sql .= ' ORDER BY course.title';
  902. $result_nb_cours = Database::query($sql);
  903. if (Database::num_rows($result_nb_cours) > 0) {
  904. while ($row = Database::fetch_array($result_nb_cours, 'ASSOC')) {
  905. $data[$row['id']] = $row;
  906. }
  907. }
  908. return $data;
  909. }
  910. /**
  911. * @param int $userId
  912. * @param array $courseInfo
  913. *
  914. * @return bool|null
  915. */
  916. public static function isUserSubscribedInCourseAsDrh($userId, $courseInfo)
  917. {
  918. $userId = intval($userId);
  919. if (!api_is_drh()) {
  920. return false;
  921. }
  922. if (empty($courseInfo) || empty($userId)) {
  923. return false;
  924. }
  925. $courseId = intval($courseInfo['real_id']);
  926. $table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  927. $sql = "SELECT * FROM $table
  928. WHERE
  929. user_id = $userId AND
  930. relation_type = ".COURSE_RELATION_TYPE_RRHH." AND
  931. c_id = $courseId";
  932. $result = Database::fetch_array(Database::query($sql));
  933. if (!empty($result)) {
  934. // The user has been registered in this course.
  935. return true;
  936. }
  937. }
  938. /**
  939. * Check if user is subscribed inside a course.
  940. *
  941. * @param int $user_id
  942. * @param string $course_code , if this parameter is null, it'll check for all courses
  943. * @param bool $in_a_session True for checking inside sessions too, by default is not checked
  944. * @param int $session_id
  945. *
  946. * @return bool $session_id true if the user is registered in the course, false otherwise
  947. */
  948. public static function is_user_subscribed_in_course(
  949. $user_id,
  950. $course_code = null,
  951. $in_a_session = false,
  952. $session_id = 0
  953. ) {
  954. $user_id = (int) $user_id;
  955. $session_id = (int) $session_id;
  956. if (empty($session_id)) {
  957. $session_id = api_get_session_id();
  958. }
  959. $condition_course = '';
  960. if (isset($course_code)) {
  961. $courseInfo = api_get_course_info($course_code);
  962. if (empty($courseInfo)) {
  963. return false;
  964. }
  965. $courseId = $courseInfo['real_id'];
  966. $condition_course = " AND c_id = $courseId";
  967. }
  968. $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  969. WHERE
  970. user_id = $user_id AND
  971. relation_type<>".COURSE_RELATION_TYPE_RRHH."
  972. $condition_course ";
  973. $result = Database::fetch_array(Database::query($sql));
  974. if (!empty($result)) {
  975. // The user has been registered in this course.
  976. return true;
  977. }
  978. if (!$in_a_session) {
  979. // The user has not been registered in this course.
  980. return false;
  981. }
  982. $tableSessionCourseUser = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  983. $sql = "SELECT 1 FROM $tableSessionCourseUser
  984. WHERE user_id = $user_id AND session_id = $session_id $condition_course";
  985. if (Database::num_rows(Database::query($sql)) > 0) {
  986. return true;
  987. }
  988. $sql = "SELECT 1 FROM $tableSessionCourseUser
  989. WHERE user_id = $user_id AND session_id = $session_id AND status = 2 $condition_course";
  990. if (Database::num_rows(Database::query($sql)) > 0) {
  991. return true;
  992. }
  993. $sql = 'SELECT 1 FROM '.Database::get_main_table(TABLE_MAIN_SESSION).
  994. " WHERE id = $session_id AND id_coach = $user_id";
  995. if (Database::num_rows(Database::query($sql)) > 0) {
  996. return true;
  997. }
  998. return false;
  999. }
  1000. /**
  1001. * Is the user a teacher in the given course?
  1002. *
  1003. * @param int $user_id , the id (int) of the user
  1004. * @param string $course_code , the course code
  1005. *
  1006. * @return bool if the user is a teacher in the course, false otherwise
  1007. */
  1008. public static function is_course_teacher($user_id, $course_code)
  1009. {
  1010. if ($user_id != strval(intval($user_id))) {
  1011. return false;
  1012. }
  1013. $courseInfo = api_get_course_info($course_code);
  1014. if (empty($courseInfo)) {
  1015. return false;
  1016. }
  1017. $courseId = $courseInfo['real_id'];
  1018. $sql = "SELECT status FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  1019. WHERE c_id = $courseId AND user_id = $user_id ";
  1020. $result = Database::query($sql);
  1021. if (Database::num_rows($result) > 0) {
  1022. return Database::result($result, 0, 'status') == 1;
  1023. }
  1024. return false;
  1025. }
  1026. /**
  1027. * Is the user subscribed in the real course or linked courses?
  1028. *
  1029. * @param int the id of the user
  1030. * @param int $courseId
  1031. *
  1032. * @deprecated linked_courses definition doesn't exists
  1033. *
  1034. * @return bool if the user is registered in the real course or linked courses, false otherwise
  1035. */
  1036. public static function is_user_subscribed_in_real_or_linked_course($user_id, $courseId, $session_id = 0)
  1037. {
  1038. if ($user_id != strval(intval($user_id))) {
  1039. return false;
  1040. }
  1041. $courseId = intval($courseId);
  1042. $session_id = intval($session_id);
  1043. if (empty($session_id)) {
  1044. $result = Database::fetch_array(
  1045. Database::query(
  1046. "SELECT *
  1047. FROM ".Database::get_main_table(TABLE_MAIN_COURSE)." course
  1048. LEFT JOIN ".Database::get_main_table(TABLE_MAIN_COURSE_USER)." course_user
  1049. ON course.id = course_user.c_id
  1050. WHERE
  1051. course_user.user_id = $user_id AND
  1052. course_user.relation_type<>".COURSE_RELATION_TYPE_RRHH." AND
  1053. ( course.id = $courseId)"
  1054. )
  1055. );
  1056. return !empty($result);
  1057. }
  1058. // From here we trust session id.
  1059. // Is he/she subscribed to the session's course?
  1060. // A user?
  1061. if (Database::num_rows(Database::query("SELECT user_id
  1062. FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)."
  1063. WHERE session_id = $session_id
  1064. AND user_id = $user_id"))
  1065. ) {
  1066. return true;
  1067. }
  1068. // A course coach?
  1069. if (Database::num_rows(Database::query("SELECT user_id
  1070. FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)."
  1071. WHERE session_id = $session_id
  1072. AND user_id = $user_id AND status = 2
  1073. AND c_id = $courseId"))
  1074. ) {
  1075. return true;
  1076. }
  1077. // A session coach?
  1078. if (Database::num_rows(Database::query("SELECT id_coach
  1079. FROM ".Database::get_main_table(TABLE_MAIN_SESSION)." AS session
  1080. WHERE session.id = $session_id
  1081. AND id_coach = $user_id"))
  1082. ) {
  1083. return true;
  1084. }
  1085. return false;
  1086. }
  1087. /**
  1088. * Return user info array of all users registered in a course
  1089. * This only returns the users that are registered in this actual course, not linked courses.
  1090. *
  1091. * @param string $course_code
  1092. * @param int $session_id
  1093. * @param string $limit
  1094. * @param string $order_by the field to order the users by.
  1095. * Valid values are 'lastname', 'firstname', 'username', 'email', 'official_code' OR a part of a SQL statement
  1096. * that starts with ORDER BY ...
  1097. * @param int|null $filter_by_status if using the session_id: 0 or 2 (student, coach),
  1098. * if using session_id = 0 STUDENT or COURSEMANAGER
  1099. * @param bool|null $return_count
  1100. * @param bool $add_reports
  1101. * @param bool $resumed_report
  1102. * @param array $extra_field
  1103. * @param array $courseCodeList
  1104. * @param array $userIdList
  1105. * @param string $filterByActive
  1106. * @param array $sessionIdList
  1107. * @param string $searchByKeyword
  1108. *
  1109. * @return array|int
  1110. */
  1111. public static function get_user_list_from_course_code(
  1112. $course_code = null,
  1113. $session_id = 0,
  1114. $limit = null,
  1115. $order_by = null,
  1116. $filter_by_status = null,
  1117. $return_count = null,
  1118. $add_reports = false,
  1119. $resumed_report = false,
  1120. $extra_field = [],
  1121. $courseCodeList = [],
  1122. $userIdList = [],
  1123. $filterByActive = null,
  1124. $sessionIdList = [],
  1125. $searchByKeyword = ''
  1126. ) {
  1127. $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
  1128. $sessionTable = Database::get_main_table(TABLE_MAIN_SESSION);
  1129. $session_id = (int) $session_id;
  1130. $course_code = Database::escape_string($course_code);
  1131. $courseInfo = api_get_course_info($course_code);
  1132. $courseId = 0;
  1133. if (!empty($courseInfo)) {
  1134. $courseId = $courseInfo['real_id'];
  1135. }
  1136. $where = [];
  1137. if (empty($order_by)) {
  1138. $order_by = 'user.lastname, user.firstname';
  1139. if (api_is_western_name_order()) {
  1140. $order_by = 'user.firstname, user.lastname';
  1141. }
  1142. }
  1143. // if the $order_by does not contain 'ORDER BY'
  1144. // we have to check if it is a valid field that can be sorted on
  1145. if (!strstr($order_by, 'ORDER BY')) {
  1146. if (!empty($order_by)) {
  1147. $order_by = "ORDER BY $order_by";
  1148. } else {
  1149. $order_by = '';
  1150. }
  1151. }
  1152. $filter_by_status_condition = null;
  1153. if (!empty($session_id) || !empty($sessionIdList)) {
  1154. $sql = 'SELECT DISTINCT
  1155. user.user_id,
  1156. user.email,
  1157. session_course_user.status as status_session,
  1158. session_id,
  1159. user.*,
  1160. course.*,
  1161. course.id AS c_id,
  1162. session.name as session_name
  1163. ';
  1164. if ($return_count) {
  1165. $sql = " SELECT COUNT(user.user_id) as count";
  1166. }
  1167. $sessionCondition = " session_course_user.session_id = $session_id";
  1168. if (!empty($sessionIdList)) {
  1169. $sessionIdListTostring = implode("','", array_map('intval', $sessionIdList));
  1170. $sessionCondition = " session_course_user.session_id IN ('$sessionIdListTostring') ";
  1171. }
  1172. $courseCondition = " course.id = $courseId";
  1173. if (!empty($courseCodeList)) {
  1174. $courseCodeListForSession = array_map(['Database', 'escape_string'], $courseCodeList);
  1175. $courseCodeListForSession = implode('","', $courseCodeListForSession);
  1176. $courseCondition = " course.code IN ('$courseCodeListForSession') ";
  1177. }
  1178. $sql .= ' FROM '.Database::get_main_table(TABLE_MAIN_USER).' as user ';
  1179. $sql .= " LEFT JOIN ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)." as session_course_user
  1180. ON
  1181. user.id = session_course_user.user_id AND
  1182. $sessionCondition
  1183. INNER JOIN $course_table course
  1184. ON session_course_user.c_id = course.id AND
  1185. $courseCondition
  1186. INNER JOIN $sessionTable session
  1187. ON session_course_user.session_id = session.id
  1188. ";
  1189. $where[] = ' session_course_user.c_id IS NOT NULL ';
  1190. // 2 = coach
  1191. // 0 = student
  1192. if (isset($filter_by_status)) {
  1193. $filter_by_status = intval($filter_by_status);
  1194. $filter_by_status_condition = " session_course_user.status = $filter_by_status AND ";
  1195. }
  1196. } else {
  1197. if ($return_count) {
  1198. $sql = " SELECT COUNT(*) as count";
  1199. } else {
  1200. if (empty($course_code)) {
  1201. $sql = 'SELECT DISTINCT
  1202. course.title,
  1203. course.code,
  1204. course.id AS c_id,
  1205. course_rel_user.status as status_rel,
  1206. user.id as user_id,
  1207. user.email,
  1208. course_rel_user.is_tutor,
  1209. user.* ';
  1210. } else {
  1211. $sql = 'SELECT DISTINCT
  1212. course_rel_user.status as status_rel,
  1213. user.id as user_id,
  1214. user.email,
  1215. course_rel_user.is_tutor,
  1216. user.* ';
  1217. }
  1218. }
  1219. $sql .= " FROM ".Database::get_main_table(TABLE_MAIN_USER)." as user
  1220. LEFT JOIN ".Database::get_main_table(TABLE_MAIN_COURSE_USER)." as course_rel_user
  1221. ON
  1222. user.id = course_rel_user.user_id AND
  1223. course_rel_user.relation_type <> ".COURSE_RELATION_TYPE_RRHH."
  1224. INNER JOIN $course_table course
  1225. ON course_rel_user.c_id = course.id ";
  1226. if (!empty($course_code)) {
  1227. $sql .= " AND course_rel_user.c_id = $courseId";
  1228. }
  1229. $where[] = ' course_rel_user.c_id IS NOT NULL ';
  1230. if (isset($filter_by_status) && is_numeric($filter_by_status)) {
  1231. $filter_by_status = (int) $filter_by_status;
  1232. $filter_by_status_condition = " course_rel_user.status = $filter_by_status AND ";
  1233. }
  1234. }
  1235. $multiple_access_url = api_get_multiple_access_url();
  1236. if ($multiple_access_url) {
  1237. $sql .= ' LEFT JOIN '.Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER).' au
  1238. ON (au.user_id = user.id) ';
  1239. }
  1240. $extraFieldWasAdded = false;
  1241. if ($return_count && $resumed_report) {
  1242. foreach ($extra_field as $extraField) {
  1243. $extraFieldInfo = UserManager::get_extra_field_information_by_name($extraField);
  1244. if (!empty($extraFieldInfo)) {
  1245. $fieldValuesTable = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  1246. $sql .= " LEFT JOIN $fieldValuesTable as ufv
  1247. ON (
  1248. user.id = ufv.item_id AND
  1249. (field_id = ".$extraFieldInfo['id']." OR field_id IS NULL)
  1250. )";
  1251. $extraFieldWasAdded = true;
  1252. }
  1253. }
  1254. }
  1255. $sql .= " WHERE $filter_by_status_condition ".implode(' OR ', $where);
  1256. if ($multiple_access_url) {
  1257. $current_access_url_id = api_get_current_access_url_id();
  1258. $sql .= " AND (access_url_id = $current_access_url_id ) ";
  1259. }
  1260. if ($return_count && $resumed_report && $extraFieldWasAdded) {
  1261. $sql .= ' AND field_id IS NOT NULL GROUP BY value ';
  1262. }
  1263. if (!empty($courseCodeList)) {
  1264. $courseCodeList = array_map(['Database', 'escape_string'], $courseCodeList);
  1265. $courseCodeList = implode('","', $courseCodeList);
  1266. if (empty($sessionIdList)) {
  1267. $sql .= ' AND course.code IN ("'.$courseCodeList.'")';
  1268. }
  1269. }
  1270. if (!empty($userIdList)) {
  1271. $userIdList = array_map('intval', $userIdList);
  1272. $userIdList = implode('","', $userIdList);
  1273. $sql .= ' AND user.id IN ("'.$userIdList.'")';
  1274. }
  1275. if (isset($filterByActive)) {
  1276. $filterByActive = (int) $filterByActive;
  1277. $sql .= " AND user.active = $filterByActive";
  1278. }
  1279. if (!empty($searchByKeyword)) {
  1280. $searchByKeyword = Database::escape_string($searchByKeyword);
  1281. $sql .= " AND (
  1282. user.firstname LIKE '$searchByKeyword' OR
  1283. user.username LIKE '$searchByKeyword' OR
  1284. user.lastname LIKE '$searchByKeyword'
  1285. ) ";
  1286. }
  1287. $sql .= " $order_by $limit";
  1288. $rs = Database::query($sql);
  1289. $users = [];
  1290. $extra_fields = UserManager::get_extra_fields(
  1291. 0,
  1292. 100,
  1293. null,
  1294. null,
  1295. true,
  1296. true
  1297. );
  1298. $counter = 1;
  1299. $count_rows = Database::num_rows($rs);
  1300. if ($return_count && $resumed_report) {
  1301. return $count_rows;
  1302. }
  1303. $table_user_field_value = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  1304. $tableExtraField = Database::get_main_table(TABLE_EXTRA_FIELD);
  1305. if ($count_rows) {
  1306. while ($user = Database::fetch_array($rs)) {
  1307. if ($return_count) {
  1308. return $user['count'];
  1309. }
  1310. $report_info = [];
  1311. $user_info = $user;
  1312. $user_info['status'] = $user['status'];
  1313. if (isset($user['is_tutor'])) {
  1314. $user_info['is_tutor'] = $user['is_tutor'];
  1315. }
  1316. if (!empty($session_id)) {
  1317. $user_info['status_session'] = $user['status_session'];
  1318. }
  1319. $sessionId = isset($user['session_id']) ? $user['session_id'] : 0;
  1320. $course_code = isset($user['code']) ? $user['code'] : null;
  1321. if ($add_reports) {
  1322. if ($resumed_report) {
  1323. $extra = [];
  1324. if (!empty($extra_fields)) {
  1325. foreach ($extra_fields as $extra) {
  1326. if (in_array($extra['1'], $extra_field)) {
  1327. $user_data = UserManager::get_extra_user_data_by_field(
  1328. $user['user_id'],
  1329. $extra['1']
  1330. );
  1331. break;
  1332. }
  1333. }
  1334. }
  1335. $row_key = '-1';
  1336. $name = '-';
  1337. if (!empty($extra)) {
  1338. if (!empty($user_data[$extra['1']])) {
  1339. $row_key = $user_data[$extra['1']];
  1340. $name = $user_data[$extra['1']];
  1341. $users[$row_key]['extra_'.$extra['1']] = $name;
  1342. }
  1343. }
  1344. if (empty($users[$row_key])) {
  1345. $users[$row_key] = [];
  1346. }
  1347. if (!array_key_exists('training_hours', $users[$row_key])) {
  1348. $users[$row_key]['training_hours'] = 0;
  1349. }
  1350. $users[$row_key]['training_hours'] += Tracking::get_time_spent_on_the_course(
  1351. $user['user_id'],
  1352. $courseId,
  1353. $sessionId
  1354. );
  1355. if (!array_key_exists('count_users', $users[$row_key])) {
  1356. $users[$row_key]['count_users'] = 0;
  1357. }
  1358. $users[$row_key]['count_users'] += $counter;
  1359. $registered_users_with_extra_field = self::getCountRegisteredUsersWithCourseExtraField(
  1360. $name,
  1361. $tableExtraField,
  1362. $table_user_field_value
  1363. );
  1364. $users[$row_key]['count_users_registered'] = $registered_users_with_extra_field;
  1365. $users[$row_key]['average_hours_per_user'] = $users[$row_key]['training_hours'] / $users[$row_key]['count_users'];
  1366. $category = Category:: load(
  1367. null,
  1368. null,
  1369. $course_code,
  1370. null,
  1371. null,
  1372. $sessionId
  1373. );
  1374. if (!isset($users[$row_key]['count_certificates'])) {
  1375. $users[$row_key]['count_certificates'] = 0;
  1376. }
  1377. if (isset($category[0]) && $category[0]->is_certificate_available($user['user_id'])) {
  1378. $users[$row_key]['count_certificates']++;
  1379. }
  1380. foreach ($extra_fields as $extra) {
  1381. if ($extra['1'] == 'ruc') {
  1382. continue;
  1383. }
  1384. if (!isset($users[$row_key][$extra['1']])) {
  1385. $user_data = UserManager::get_extra_user_data_by_field($user['user_id'], $extra['1']);
  1386. if (!empty($user_data[$extra['1']])) {
  1387. $users[$row_key][$extra['1']] = $user_data[$extra['1']];
  1388. }
  1389. }
  1390. }
  1391. } else {
  1392. $sessionName = !empty($sessionId) ? ' - '.$user['session_name'] : '';
  1393. $report_info['course'] = $user['title'].$sessionName;
  1394. $report_info['user'] = api_get_person_name($user['firstname'], $user['lastname']);
  1395. $report_info['email'] = $user['email'];
  1396. $report_info['time'] = api_time_to_hms(
  1397. Tracking::get_time_spent_on_the_course(
  1398. $user['user_id'],
  1399. empty($user['c_id']) ? $courseId : $user['c_id'],
  1400. $sessionId
  1401. )
  1402. );
  1403. $category = Category:: load(
  1404. null,
  1405. null,
  1406. $course_code,
  1407. null,
  1408. null,
  1409. $sessionId
  1410. );
  1411. $report_info['certificate'] = Display::label(get_lang('No'));
  1412. if (isset($category[0]) && $category[0]->is_certificate_available($user['user_id'])) {
  1413. $report_info['certificate'] = Display::label(get_lang('Yes'), 'success');
  1414. }
  1415. $progress = intval(
  1416. Tracking::get_avg_student_progress(
  1417. $user['user_id'],
  1418. $course_code,
  1419. [],
  1420. $sessionId
  1421. )
  1422. );
  1423. $report_info['progress_100'] = $progress == 100 ? Display::label(get_lang('Yes'), 'success') : Display::label(get_lang('No'));
  1424. $report_info['progress'] = $progress."%";
  1425. foreach ($extra_fields as $extra) {
  1426. $user_data = UserManager::get_extra_user_data_by_field($user['user_id'], $extra['1']);
  1427. $report_info[$extra['1']] = $user_data[$extra['1']];
  1428. }
  1429. $report_info['user_id'] = $user['user_id'];
  1430. $users[] = $report_info;
  1431. }
  1432. } else {
  1433. $users[$user['user_id']] = $user_info;
  1434. }
  1435. }
  1436. }
  1437. return $users;
  1438. }
  1439. /**
  1440. * @param bool $resumed_report
  1441. * @param array $extra_field
  1442. * @param array $courseCodeList
  1443. * @param array $userIdList
  1444. * @param array $sessionIdList
  1445. *
  1446. * @return array|int
  1447. */
  1448. public static function get_count_user_list_from_course_code(
  1449. $resumed_report = false,
  1450. $extra_field = [],
  1451. $courseCodeList = [],
  1452. $userIdList = [],
  1453. $sessionIdList = []
  1454. ) {
  1455. return self::get_user_list_from_course_code(
  1456. null,
  1457. 0,
  1458. null,
  1459. null,
  1460. null,
  1461. true,
  1462. false,
  1463. $resumed_report,
  1464. $extra_field,
  1465. $courseCodeList,
  1466. $userIdList,
  1467. null,
  1468. $sessionIdList
  1469. );
  1470. }
  1471. /**
  1472. * Gets subscribed users in a course or in a course/session.
  1473. *
  1474. * @param string $course_code
  1475. * @param int $session_id
  1476. *
  1477. * @return int
  1478. */
  1479. public static function get_users_count_in_course(
  1480. $course_code,
  1481. $session_id = 0,
  1482. $status = null
  1483. ) {
  1484. // variable initialisation
  1485. $session_id = (int) $session_id;
  1486. $course_code = Database::escape_string($course_code);
  1487. $tblUser = Database::get_main_table(TABLE_MAIN_USER);
  1488. $tblSessionCourseUser = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1489. $tblCourseUser = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  1490. $tblUrlUser = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  1491. $courseInfo = api_get_course_info($course_code);
  1492. $courseId = $courseInfo['real_id'];
  1493. $sql = "
  1494. SELECT DISTINCT count(user.id) as count
  1495. FROM $tblUser as user
  1496. ";
  1497. $where = [];
  1498. if (!empty($session_id)) {
  1499. $sql .= "
  1500. LEFT JOIN $tblSessionCourseUser as session_course_user
  1501. ON user.user_id = session_course_user.user_id
  1502. AND session_course_user.c_id = $courseId
  1503. AND session_course_user.session_id = $session_id
  1504. ";
  1505. $where[] = ' session_course_user.c_id IS NOT NULL ';
  1506. } else {
  1507. $sql .= "
  1508. LEFT JOIN $tblCourseUser as course_rel_user
  1509. ON user.user_id = course_rel_user.user_id
  1510. AND course_rel_user.relation_type <> ".COURSE_RELATION_TYPE_RRHH."
  1511. AND course_rel_user.c_id = $courseId
  1512. ";
  1513. $where[] = ' course_rel_user.c_id IS NOT NULL ';
  1514. }
  1515. $multiple_access_url = api_get_multiple_access_url();
  1516. if ($multiple_access_url) {
  1517. $sql .= " LEFT JOIN $tblUrlUser au ON (au.user_id = user.user_id) ";
  1518. }
  1519. $sql .= ' WHERE '.implode(' OR ', $where);
  1520. if ($multiple_access_url) {
  1521. $current_access_url_id = api_get_current_access_url_id();
  1522. $sql .= " AND (access_url_id = $current_access_url_id ) ";
  1523. }
  1524. $rs = Database::query($sql);
  1525. $count = 0;
  1526. if (Database::num_rows($rs)) {
  1527. $user = Database::fetch_array($rs);
  1528. $count = $user['count'];
  1529. }
  1530. return $count;
  1531. }
  1532. /**
  1533. * Get a list of coaches of a course and a session.
  1534. *
  1535. * @param string $course_code
  1536. * @param int $session_id
  1537. * @param bool $addGeneralCoach
  1538. *
  1539. * @return array List of users
  1540. */
  1541. public static function get_coach_list_from_course_code(
  1542. $course_code,
  1543. $session_id,
  1544. $addGeneralCoach = true
  1545. ) {
  1546. if (empty($course_code) || empty($session_id)) {
  1547. return [];
  1548. }
  1549. $course_code = Database::escape_string($course_code);
  1550. $courseInfo = api_get_course_info($course_code);
  1551. $courseId = $courseInfo['real_id'];
  1552. $session_id = (int) $session_id;
  1553. $users = [];
  1554. // We get the coach for the given course in a given session.
  1555. $sql = 'SELECT user_id FROM '.Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER).
  1556. " WHERE session_id = $session_id AND c_id = $courseId AND status = 2";
  1557. $rs = Database::query($sql);
  1558. while ($user = Database::fetch_array($rs)) {
  1559. $userInfo = api_get_user_info($user['user_id']);
  1560. if ($userInfo) {
  1561. $users[$user['user_id']] = $userInfo;
  1562. }
  1563. }
  1564. if ($addGeneralCoach) {
  1565. $table = Database::get_main_table(TABLE_MAIN_SESSION);
  1566. // We get the session coach.
  1567. $sql = "SELECT id_coach FROM $table WHERE id = $session_id";
  1568. $rs = Database::query($sql);
  1569. $session_id_coach = Database::result($rs, 0, 'id_coach');
  1570. if (is_int($session_id_coach)) {
  1571. $userInfo = api_get_user_info($session_id_coach);
  1572. if ($userInfo) {
  1573. $users[$session_id_coach] = $userInfo;
  1574. }
  1575. }
  1576. }
  1577. return $users;
  1578. }
  1579. /**
  1580. * Return user info array of all users registered in a course
  1581. * This only returns the users that are registered in this actual course, not linked courses.
  1582. *
  1583. * @param string $course_code
  1584. * @param bool $with_session
  1585. * @param int $session_id
  1586. * @param string $date_from
  1587. * @param string $date_to
  1588. * @param bool $includeInvitedUsers Whether include the invited users
  1589. * @param int $groupId
  1590. *
  1591. * @return array with user id
  1592. */
  1593. public static function get_student_list_from_course_code(
  1594. $course_code,
  1595. $with_session = false,
  1596. $session_id = 0,
  1597. $date_from = null,
  1598. $date_to = null,
  1599. $includeInvitedUsers = true,
  1600. $groupId = 0
  1601. ) {
  1602. $userTable = Database::get_main_table(TABLE_MAIN_USER);
  1603. $session_id = (int) $session_id;
  1604. $courseInfo = api_get_course_info($course_code);
  1605. if (empty($courseInfo)) {
  1606. return [];
  1607. }
  1608. $courseId = $courseInfo['real_id'];
  1609. $students = [];
  1610. if ($session_id == 0) {
  1611. if (empty($groupId)) {
  1612. // students directly subscribed to the course
  1613. $sql = "SELECT *
  1614. FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)." cu
  1615. INNER JOIN $userTable u
  1616. ON cu.user_id = u.user_id
  1617. WHERE c_id = $courseId AND cu.status = ".STUDENT;
  1618. if (!$includeInvitedUsers) {
  1619. $sql .= " AND u.status != ".INVITEE;
  1620. }
  1621. $rs = Database::query($sql);
  1622. while ($student = Database::fetch_array($rs)) {
  1623. $students[$student['user_id']] = $student;
  1624. }
  1625. } else {
  1626. $students = GroupManager::get_users(
  1627. $groupId,
  1628. false,
  1629. null,
  1630. null,
  1631. false,
  1632. $courseInfo['real_id']
  1633. );
  1634. $students = array_flip($students);
  1635. }
  1636. }
  1637. // students subscribed to the course through a session
  1638. if ($with_session) {
  1639. $joinSession = '';
  1640. //Session creation date
  1641. if (!empty($date_from) && !empty($date_to)) {
  1642. $joinSession = "INNER JOIN ".Database::get_main_table(TABLE_MAIN_SESSION)." s";
  1643. }
  1644. $sql_query = "SELECT *
  1645. FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)." scu
  1646. $joinSession
  1647. INNER JOIN $userTable u ON scu.user_id = u.user_id
  1648. WHERE scu.c_id = $courseId AND scu.status <> 2";
  1649. if (!empty($date_from) && !empty($date_to)) {
  1650. $date_from = Database::escape_string($date_from);
  1651. $date_to = Database::escape_string($date_to);
  1652. $sql_query .= " AND s.access_start_date >= '$date_from' AND s.access_end_date <= '$date_to'";
  1653. }
  1654. if ($session_id != 0) {
  1655. $sql_query .= " AND scu.session_id = $session_id";
  1656. }
  1657. if (!$includeInvitedUsers) {
  1658. $sql_query .= " AND u.status != ".INVITEE;
  1659. }
  1660. $rs = Database::query($sql_query);
  1661. while ($student = Database::fetch_array($rs)) {
  1662. $students[$student['user_id']] = $student;
  1663. }
  1664. }
  1665. return $students;
  1666. }
  1667. /**
  1668. * Return user info array of all teacher-users registered in a course
  1669. * This only returns the users that are registered in this actual course, not linked courses.
  1670. *
  1671. * @param string $course_code
  1672. *
  1673. * @return array with user id
  1674. */
  1675. public static function get_teacher_list_from_course_code($course_code)
  1676. {
  1677. $courseInfo = api_get_course_info($course_code);
  1678. $courseId = $courseInfo['real_id'];
  1679. if (empty($courseId)) {
  1680. return false;
  1681. }
  1682. $sql = "SELECT DISTINCT
  1683. u.id as user_id,
  1684. u.lastname,
  1685. u.firstname,
  1686. u.email,
  1687. u.username,
  1688. u.status
  1689. FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)." cu
  1690. INNER JOIN ".Database::get_main_table(TABLE_MAIN_USER)." u
  1691. ON (cu.user_id = u.id)
  1692. WHERE
  1693. cu.c_id = $courseId AND
  1694. cu.status = 1 ";
  1695. $rs = Database::query($sql);
  1696. $teachers = [];
  1697. while ($teacher = Database::fetch_array($rs)) {
  1698. $teachers[$teacher['user_id']] = $teacher;
  1699. }
  1700. return $teachers;
  1701. }
  1702. /**
  1703. * Return user info array of all teacher-users registered in a course
  1704. * This only returns the users that are registered in this actual course, not linked courses.
  1705. *
  1706. * @param int $courseId
  1707. * @param bool $loadAvatars
  1708. *
  1709. * @return array with user id
  1710. */
  1711. public static function getTeachersFromCourse($courseId, $loadAvatars = true)
  1712. {
  1713. $courseId = (int) $courseId;
  1714. if (empty($courseId)) {
  1715. return false;
  1716. }
  1717. $sql = "SELECT DISTINCT
  1718. u.id as user_id,
  1719. u.lastname,
  1720. u.firstname,
  1721. u.email,
  1722. u.username,
  1723. u.status
  1724. FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)." cu
  1725. INNER JOIN ".Database::get_main_table(TABLE_MAIN_USER)." u
  1726. ON (cu.user_id = u.id)
  1727. WHERE
  1728. cu.c_id = $courseId AND
  1729. cu.status = 1 ";
  1730. $rs = Database::query($sql);
  1731. $listTeachers = [];
  1732. $teachers = [];
  1733. $url = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?a=get_user_popup&course_id='.$courseId;
  1734. while ($teacher = Database::fetch_array($rs)) {
  1735. $teachers['id'] = $teacher['user_id'];
  1736. $teachers['lastname'] = $teacher['lastname'];
  1737. $teachers['firstname'] = $teacher['firstname'];
  1738. $teachers['email'] = $teacher['email'];
  1739. $teachers['username'] = $teacher['username'];
  1740. $teachers['status'] = $teacher['status'];
  1741. $teachers['fullname'] = api_get_person_name($teacher['firstname'], $teacher['lastname']);
  1742. $teachers['avatar'] = '';
  1743. if ($loadAvatars) {
  1744. $userPicture = UserManager::getUserPicture($teacher['user_id'], USER_IMAGE_SIZE_SMALL);
  1745. $teachers['avatar'] = $userPicture;
  1746. }
  1747. $teachers['url'] = $url.'&user_id='.$teacher['user_id'];
  1748. $listTeachers[] = $teachers;
  1749. }
  1750. return $listTeachers;
  1751. }
  1752. /**
  1753. * Returns a string list of teachers assigned to the given course.
  1754. *
  1755. * @param string $course_code
  1756. * @param string $separator between teachers names
  1757. * @param bool $add_link_to_profile Whether to add a link to the teacher's profile
  1758. * @param bool $orderList
  1759. *
  1760. * @return string List of teachers teaching the course
  1761. */
  1762. public static function getTeacherListFromCourseCodeToString(
  1763. $course_code,
  1764. $separator = self::USER_SEPARATOR,
  1765. $add_link_to_profile = false,
  1766. $orderList = false
  1767. ) {
  1768. $teacher_list = self::get_teacher_list_from_course_code($course_code);
  1769. $html = '';
  1770. $list = [];
  1771. if (!empty($teacher_list)) {
  1772. foreach ($teacher_list as $teacher) {
  1773. $teacher_name = api_get_person_name(
  1774. $teacher['firstname'],
  1775. $teacher['lastname']
  1776. );
  1777. if ($add_link_to_profile) {
  1778. $url = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?a=get_user_popup&user_id='.$teacher['user_id'];
  1779. $teacher_name = Display::url(
  1780. $teacher_name,
  1781. $url,
  1782. [
  1783. 'class' => 'ajax',
  1784. 'data-title' => $teacher_name,
  1785. ]
  1786. );
  1787. }
  1788. $list[] = $teacher_name;
  1789. }
  1790. if (!empty($list)) {
  1791. if ($orderList === true) {
  1792. $html .= '<ul class="user-teacher">';
  1793. foreach ($list as $teacher) {
  1794. $html .= '<li>';
  1795. $html .= Display::return_icon('teacher.png', '', null, ICON_SIZE_TINY);
  1796. $html .= ' '.$teacher;
  1797. $html .= '</li>';
  1798. }
  1799. $html .= '</ul>';
  1800. } else {
  1801. $html .= array_to_string($list, $separator);
  1802. }
  1803. }
  1804. }
  1805. return $html;
  1806. }
  1807. /**
  1808. * This function returns information about coachs from a course in session.
  1809. *
  1810. * @param int $session_id
  1811. * @param int $courseId
  1812. *
  1813. * @return array containing user_id, lastname, firstname, username
  1814. */
  1815. public static function get_coachs_from_course($session_id = 0, $courseId = 0)
  1816. {
  1817. if (!empty($session_id)) {
  1818. $session_id = intval($session_id);
  1819. } else {
  1820. $session_id = api_get_session_id();
  1821. }
  1822. if (!empty($courseId)) {
  1823. $courseId = intval($courseId);
  1824. } else {
  1825. $courseId = api_get_course_int_id();
  1826. }
  1827. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  1828. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1829. $sql = "SELECT DISTINCT
  1830. u.user_id,
  1831. u.lastname,
  1832. u.firstname,
  1833. u.username
  1834. FROM $tbl_user u
  1835. INNER JOIN $tbl_session_course_user scu
  1836. ON (u.user_id = scu.user_id)
  1837. WHERE
  1838. scu.session_id = $session_id AND
  1839. scu.c_id = $courseId AND
  1840. scu.status = 2";
  1841. $rs = Database::query($sql);
  1842. $coaches = [];
  1843. if (Database::num_rows($rs) > 0) {
  1844. while ($row = Database::fetch_array($rs)) {
  1845. $completeName = api_get_person_name($row['firstname'], $row['lastname']);
  1846. $coaches[] = $row + ['full_name' => $completeName];
  1847. }
  1848. }
  1849. return $coaches;
  1850. }
  1851. /**
  1852. * @param int $session_id
  1853. * @param int $courseId
  1854. * @param string $separator
  1855. * @param bool $add_link_to_profile
  1856. * @param bool $orderList
  1857. *
  1858. * @return string
  1859. */
  1860. public static function get_coachs_from_course_to_string(
  1861. $session_id = 0,
  1862. $courseId = 0,
  1863. $separator = self::USER_SEPARATOR,
  1864. $add_link_to_profile = false,
  1865. $orderList = false
  1866. ) {
  1867. $coachList = self::get_coachs_from_course($session_id, $courseId);
  1868. $course_coachs = [];
  1869. if (!empty($coachList)) {
  1870. foreach ($coachList as $coach_course) {
  1871. $coach_name = $coach_course['full_name'];
  1872. if ($add_link_to_profile) {
  1873. $url = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?a=get_user_popup&user_id='.$coach_course['user_id'].'&course_id='.$courseId.'&session_id='.$session_id;
  1874. $coach_name = Display::url(
  1875. $coach_name,
  1876. $url,
  1877. [
  1878. 'class' => 'ajax',
  1879. 'data-title' => $coach_name,
  1880. ]
  1881. );
  1882. }
  1883. $course_coachs[] = $coach_name;
  1884. }
  1885. }
  1886. $html = '';
  1887. if (!empty($course_coachs)) {
  1888. if ($orderList === true) {
  1889. $html .= '<ul class="user-coachs">';
  1890. foreach ($course_coachs as $coachs) {
  1891. $html .= Display::tag(
  1892. 'li',
  1893. Display::return_icon(
  1894. 'teacher.png',
  1895. get_lang('Coach'),
  1896. null,
  1897. ICON_SIZE_TINY
  1898. ).' '.$coachs
  1899. );
  1900. }
  1901. $html .= '</ul>';
  1902. } else {
  1903. $html = array_to_string($course_coachs, $separator);
  1904. }
  1905. }
  1906. return $html;
  1907. }
  1908. /**
  1909. * Get the list of groups from the course.
  1910. *
  1911. * @param string $course_code
  1912. * @param int $session_id Session ID (optional)
  1913. * @param int $in_get_empty_group get empty groups (optional)
  1914. *
  1915. * @return array List of groups info
  1916. */
  1917. public static function get_group_list_of_course(
  1918. $course_code,
  1919. $session_id = 0,
  1920. $in_get_empty_group = 0
  1921. ) {
  1922. $course_info = api_get_course_info($course_code);
  1923. if (empty($course_info)) {
  1924. return [];
  1925. }
  1926. $course_id = $course_info['real_id'];
  1927. if (empty($course_id)) {
  1928. return [];
  1929. }
  1930. $session_id != 0 ? $session_condition = ' WHERE g.session_id IN(1,'.intval($session_id).')' : $session_condition = ' WHERE g.session_id = 0';
  1931. if ($in_get_empty_group == 0) {
  1932. // get only groups that are not empty
  1933. $sql = "SELECT DISTINCT g.id, g.iid, g.name
  1934. FROM ".Database::get_course_table(TABLE_GROUP)." AS g
  1935. INNER JOIN ".Database::get_course_table(TABLE_GROUP_USER)." gu
  1936. ON (g.id = gu.group_id AND g.c_id = $course_id AND gu.c_id = $course_id)
  1937. $session_condition
  1938. ORDER BY g.name";
  1939. } else {
  1940. // get all groups even if they are empty
  1941. $sql = "SELECT g.id, g.name, g.iid
  1942. FROM ".Database::get_course_table(TABLE_GROUP)." AS g
  1943. $session_condition
  1944. AND c_id = $course_id";
  1945. }
  1946. $result = Database::query($sql);
  1947. $groupList = [];
  1948. while ($groupData = Database::fetch_array($result)) {
  1949. $groupData['userNb'] = GroupManager::number_of_students($groupData['id'], $course_id);
  1950. $groupList[$groupData['iid']] = $groupData;
  1951. }
  1952. return $groupList;
  1953. }
  1954. /**
  1955. * Delete a course
  1956. * This function deletes a whole course-area from the platform. When the
  1957. * given course is a virtual course, the database and directory will not be
  1958. * deleted.
  1959. * When the given course is a real course, also all virtual courses refering
  1960. * to the given course will be deleted.
  1961. * Considering the fact that we remove all traces of the course in the main
  1962. * database, it makes sense to remove all tracking as well (if stats databases exist)
  1963. * so that a new course created with this code would not use the remains of an older
  1964. * course.
  1965. *
  1966. * @param string $code The code of the course to delete
  1967. *
  1968. * @todo When deleting a virtual course: unsubscribe users from that virtual
  1969. * course from the groups in the real course if they are not subscribed in
  1970. * that real course.
  1971. */
  1972. public static function delete_course($code)
  1973. {
  1974. $table_course = Database::get_main_table(TABLE_MAIN_COURSE);
  1975. $table_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  1976. $table_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  1977. $table_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1978. $table_course_survey = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY);
  1979. $table_course_survey_question = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
  1980. $table_course_survey_question_option = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
  1981. $table_course_rel_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  1982. $table_stats_hotpots = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
  1983. $table_stats_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  1984. $table_stats_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  1985. $table_stats_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
  1986. $table_stats_lastaccess = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
  1987. $table_stats_course_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  1988. $table_stats_online = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
  1989. $table_stats_default = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DEFAULT);
  1990. $table_stats_downloads = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DOWNLOADS);
  1991. $table_stats_links = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LINKS);
  1992. $table_stats_uploads = Database::get_main_table(TABLE_STATISTIC_TRACK_E_UPLOADS);
  1993. if (empty($code)) {
  1994. return false;
  1995. }
  1996. $codeFiltered = Database::escape_string($code);
  1997. $sql = "SELECT * FROM $table_course
  1998. WHERE code = '$codeFiltered'";
  1999. $res = Database::query($sql);
  2000. if (Database::num_rows($res) == 0) {
  2001. return;
  2002. }
  2003. $course = Database::fetch_array($res);
  2004. $courseId = $course['id']; // int
  2005. $count = 0;
  2006. if (api_is_multiple_url_enabled()) {
  2007. $url_id = 1;
  2008. if (api_get_current_access_url_id() != -1) {
  2009. $url_id = api_get_current_access_url_id();
  2010. }
  2011. UrlManager::delete_url_rel_course($courseId, $url_id);
  2012. $count = UrlManager::getCountUrlRelCourse($courseId);
  2013. }
  2014. if ($count == 0) {
  2015. self::create_database_dump($code);
  2016. $course_tables = AddCourse::get_course_tables();
  2017. // Cleaning group categories
  2018. $groupCategories = GroupManager::get_categories($course['code']);
  2019. if (!empty($groupCategories)) {
  2020. foreach ($groupCategories as $category) {
  2021. GroupManager::delete_category($category['id'], $course['code']);
  2022. }
  2023. }
  2024. // Cleaning groups
  2025. $groups = GroupManager::get_groups($courseId);
  2026. if (!empty($groups)) {
  2027. foreach ($groups as $group) {
  2028. GroupManager::deleteGroup($group, $course['code']);
  2029. }
  2030. }
  2031. // Cleaning c_x tables
  2032. if (!empty($courseId)) {
  2033. foreach ($course_tables as $table) {
  2034. $table = Database::get_course_table($table);
  2035. $sql = "DELETE FROM $table WHERE c_id = $courseId ";
  2036. Database::query($sql);
  2037. }
  2038. }
  2039. $course_dir = api_get_path(SYS_COURSE_PATH).$course['directory'];
  2040. $archive_dir = api_get_path(SYS_ARCHIVE_PATH).$course['directory'].'_'.time();
  2041. if (is_dir($course_dir)) {
  2042. rename($course_dir, $archive_dir);
  2043. }
  2044. Category::deleteFromCourse($course['code']);
  2045. // Unsubscribe all users from the course
  2046. $sql = "DELETE FROM $table_course_user WHERE c_id = $courseId";
  2047. Database::query($sql);
  2048. // Delete the course from the sessions tables
  2049. $sql = "DELETE FROM $table_session_course WHERE c_id = $courseId";
  2050. Database::query($sql);
  2051. $sql = "DELETE FROM $table_session_course_user WHERE c_id = $courseId";
  2052. Database::query($sql);
  2053. // Delete from Course - URL
  2054. $sql = "DELETE FROM $table_course_rel_url WHERE c_id = $courseId";
  2055. Database::query($sql);
  2056. $sql = "SELECT survey_id FROM $table_course_survey WHERE course_code = '$codeFiltered'";
  2057. $result_surveys = Database::query($sql);
  2058. while ($surveys = Database::fetch_array($result_surveys)) {
  2059. $survey_id = $surveys[0]; //int
  2060. $sql = "DELETE FROM $table_course_survey_question WHERE survey_id = $survey_id";
  2061. Database::query($sql);
  2062. $sql = "DELETE FROM $table_course_survey_question_option WHERE survey_id = $survey_id";
  2063. Database::query($sql);
  2064. $sql = "DELETE FROM $table_course_survey WHERE survey_id = $survey_id";
  2065. Database::query($sql);
  2066. }
  2067. // Delete the course from the stats tables
  2068. $sql = "DELETE FROM $table_stats_hotpots WHERE c_id = $courseId";
  2069. Database::query($sql);
  2070. $sql = "DELETE FROM $table_stats_attempt WHERE c_id = $courseId";
  2071. Database::query($sql);
  2072. $sql = "DELETE FROM $table_stats_exercises WHERE c_id = $courseId";
  2073. Database::query($sql);
  2074. $sql = "DELETE FROM $table_stats_access WHERE c_id = $courseId";
  2075. Database::query($sql);
  2076. $sql = "DELETE FROM $table_stats_lastaccess WHERE c_id = $courseId";
  2077. Database::query($sql);
  2078. $sql = "DELETE FROM $table_stats_course_access WHERE c_id = $courseId";
  2079. Database::query($sql);
  2080. $sql = "DELETE FROM $table_stats_online WHERE c_id = $courseId";
  2081. Database::query($sql);
  2082. // Do not delete rows from track_e_default as these include course
  2083. // creation and other important things that do not take much space
  2084. // but give information on the course history
  2085. //$sql = "DELETE FROM $table_stats_default WHERE c_id = $courseId";
  2086. //Database::query($sql);
  2087. $sql = "DELETE FROM $table_stats_downloads WHERE c_id = $courseId";
  2088. Database::query($sql);
  2089. $sql = "DELETE FROM $table_stats_links WHERE c_id = $courseId";
  2090. Database::query($sql);
  2091. $sql = "DELETE FROM $table_stats_uploads WHERE c_id = $courseId";
  2092. Database::query($sql);
  2093. // Update ticket
  2094. $table = Database::get_main_table(TABLE_TICKET_TICKET);
  2095. $sql = "UPDATE $table SET course_id = NULL WHERE course_id = $courseId";
  2096. Database::query($sql);
  2097. // Class
  2098. $table = Database::get_main_table(TABLE_USERGROUP_REL_COURSE);
  2099. $sql = "DELETE FROM $table
  2100. WHERE course_id = $courseId";
  2101. Database::query($sql);
  2102. // Skills
  2103. $table = Database::get_main_table(TABLE_MAIN_SKILL_REL_USER);
  2104. $argumentation = Database::escape_string(sprintf(get_lang('SkillFromCourseXDeletedSinceThen'), $course['code']));
  2105. $sql = "UPDATE $table SET course_id = NULL, session_id = NULL, argumentation = '$argumentation'
  2106. WHERE course_id = $courseId";
  2107. Database::query($sql);
  2108. if (api_get_configuration_value('allow_skill_rel_items')) {
  2109. $sql = "DELETE FROM skill_rel_course WHERE c_id = $courseId";
  2110. Database::query($sql);
  2111. }
  2112. // Deletes all groups, group-users, group-tutors information
  2113. // To prevent fK mix up on some tables
  2114. GroupManager::deleteAllGroupsFromCourse($courseId);
  2115. $app_plugin = new AppPlugin();
  2116. $app_plugin->performActionsWhenDeletingItem('course', $courseId);
  2117. // Delete the course from the database
  2118. $sql = "DELETE FROM $table_course WHERE id = $courseId";
  2119. Database::query($sql);
  2120. // delete extra course fields
  2121. $extraFieldValues = new ExtraFieldValue('course');
  2122. $extraFieldValues->deleteValuesByItem($courseId);
  2123. // Add event to system log
  2124. Event::addEvent(
  2125. LOG_COURSE_DELETE,
  2126. LOG_COURSE_CODE,
  2127. $code,
  2128. api_get_utc_datetime(),
  2129. api_get_user_id(),
  2130. $courseId
  2131. );
  2132. }
  2133. }
  2134. /**
  2135. * Creates a file called mysql_dump.sql in the course folder.
  2136. *
  2137. * @param string $course_code The code of the course
  2138. *
  2139. * @todo Implementation for single database
  2140. */
  2141. public static function create_database_dump($course_code)
  2142. {
  2143. $sql_dump = '';
  2144. $course_code = Database::escape_string($course_code);
  2145. $table_course = Database::get_main_table(TABLE_MAIN_COURSE);
  2146. $sql = "SELECT * FROM $table_course WHERE code = '$course_code'";
  2147. $res = Database::query($sql);
  2148. $course = Database::fetch_array($res);
  2149. $course_tables = AddCourse::get_course_tables();
  2150. if (!empty($course['id'])) {
  2151. //Cleaning c_x tables
  2152. foreach ($course_tables as $table) {
  2153. $table = Database::get_course_table($table);
  2154. $sql = "SELECT * FROM $table WHERE c_id = {$course['id']} ";
  2155. $res_table = Database::query($sql);
  2156. while ($row = Database::fetch_array($res_table, 'ASSOC')) {
  2157. $row_to_save = [];
  2158. foreach ($row as $key => $value) {
  2159. $row_to_save[$key] = $key."='".Database::escape_string($row[$key])."'";
  2160. }
  2161. $sql_dump .= "\nINSERT INTO $table SET ".implode(', ', $row_to_save).';';
  2162. }
  2163. }
  2164. }
  2165. if (is_dir(api_get_path(SYS_COURSE_PATH).$course['directory'])) {
  2166. $file_name = api_get_path(SYS_COURSE_PATH).$course['directory'].'/mysql_dump.sql';
  2167. $handle = fopen($file_name, 'a+');
  2168. if ($handle !== false) {
  2169. fwrite($handle, $sql_dump);
  2170. fclose($handle);
  2171. } else {
  2172. //TODO trigger exception in a try-catch
  2173. }
  2174. }
  2175. }
  2176. /**
  2177. * Sort courses for a specific user ??
  2178. *
  2179. * @param int $user_id User ID
  2180. * @param string $course_code Course code
  2181. *
  2182. * @return int Minimum course order
  2183. *
  2184. * @todo Review documentation
  2185. */
  2186. public static function userCourseSort($user_id, $course_code)
  2187. {
  2188. if ($user_id != strval(intval($user_id))) {
  2189. return false;
  2190. }
  2191. $course_code = Database::escape_string($course_code);
  2192. $TABLECOURSE = Database::get_main_table(TABLE_MAIN_COURSE);
  2193. $TABLECOURSUSER = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  2194. $course_title = Database::result(
  2195. Database::query(
  2196. "SELECT title FROM $TABLECOURSE WHERE code = '$course_code'"
  2197. ),
  2198. 0,
  2199. 0
  2200. );
  2201. if ($course_title === false) {
  2202. $course_title = '';
  2203. }
  2204. $sql = "SELECT course.code as code, course.title as title, cu.sort as sort
  2205. FROM $TABLECOURSUSER as cu, $TABLECOURSE as course
  2206. WHERE course.id = cu.c_id AND user_id = $user_id AND
  2207. cu.relation_type <> ".COURSE_RELATION_TYPE_RRHH." AND
  2208. user_course_cat = 0
  2209. ORDER BY cu.sort";
  2210. $result = Database::query($sql);
  2211. $course_title_precedent = '';
  2212. $counter = 0;
  2213. $course_found = false;
  2214. $course_sort = 1;
  2215. if (Database::num_rows($result) > 0) {
  2216. while ($courses = Database::fetch_array($result)) {
  2217. if ($course_title_precedent == '') {
  2218. $course_title_precedent = $courses['title'];
  2219. }
  2220. if (api_strcasecmp($course_title_precedent, $course_title) < 0) {
  2221. $course_found = true;
  2222. $course_sort = $courses['sort'];
  2223. if ($counter == 0) {
  2224. $sql = "UPDATE $TABLECOURSUSER
  2225. SET sort = sort+1
  2226. WHERE
  2227. user_id= $user_id AND
  2228. relation_type <> ".COURSE_RELATION_TYPE_RRHH."
  2229. AND user_course_cat = 0
  2230. AND sort > $course_sort";
  2231. $course_sort++;
  2232. } else {
  2233. $sql = "UPDATE $TABLECOURSUSER SET sort = sort+1
  2234. WHERE
  2235. user_id= $user_id AND
  2236. relation_type <> ".COURSE_RELATION_TYPE_RRHH." AND
  2237. user_course_cat = 0 AND
  2238. sort >= $course_sort";
  2239. }
  2240. Database::query($sql);
  2241. break;
  2242. } else {
  2243. $course_title_precedent = $courses['title'];
  2244. }
  2245. $counter++;
  2246. }
  2247. // We must register the course in the beginning of the list
  2248. if (!$course_found) {
  2249. $course_sort = Database::result(
  2250. Database::query(
  2251. 'SELECT min(sort) as min_sort FROM '.$TABLECOURSUSER.' WHERE user_id = "'.$user_id.'" AND user_course_cat="0"'
  2252. ),
  2253. 0,
  2254. 0
  2255. );
  2256. Database::query("UPDATE $TABLECOURSUSER SET sort = sort+1 WHERE user_id = $user_id AND user_course_cat = 0");
  2257. }
  2258. }
  2259. return $course_sort;
  2260. }
  2261. /**
  2262. * check if course exists.
  2263. *
  2264. * @param string $courseCode
  2265. *
  2266. * @return int if exists, false else
  2267. */
  2268. public static function course_exists($courseCode)
  2269. {
  2270. $courseCode = Database::escape_string($courseCode);
  2271. $sql = "SELECT 1 FROM ".Database::get_main_table(TABLE_MAIN_COURSE)."
  2272. WHERE code = '$courseCode'";
  2273. return Database::num_rows(Database::query($sql));
  2274. }
  2275. /**
  2276. * Send an email to tutor after the auth-suscription of a student in your course.
  2277. *
  2278. * @author Carlos Vargas <carlos.vargas@dokeos.com>, Dokeos Latino
  2279. *
  2280. * @param int $user_id the id of the user
  2281. * @param string $courseId the course code
  2282. * @param bool $send_to_tutor_also
  2283. *
  2284. * @return false|null we return the message that is displayed when the action is successful
  2285. */
  2286. public static function email_to_tutor($user_id, $courseId, $send_to_tutor_also = false)
  2287. {
  2288. $user_id = (int) $user_id;
  2289. $courseId = (int) $courseId;
  2290. $information = api_get_course_info_by_id($courseId);
  2291. $course_code = $information['code'];
  2292. $student = api_get_user_info($user_id);
  2293. $name_course = $information['title'];
  2294. $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  2295. WHERE c_id = $courseId";
  2296. // TODO: Ivan: This is a mistake, please, have a look at it. Intention here is diffcult to be guessed.
  2297. //if ($send_to_tutor_also = true)
  2298. // Proposed change:
  2299. if ($send_to_tutor_also) {
  2300. $sql .= ' AND is_tutor = 1';
  2301. } else {
  2302. $sql .= ' AND status = 1';
  2303. }
  2304. $result = Database::query($sql);
  2305. while ($row = Database::fetch_array($result)) {
  2306. $tutor = api_get_user_info($row['user_id']);
  2307. $emailto = $tutor['email'];
  2308. $emailsubject = get_lang('NewUserInTheCourse').': '.$name_course;
  2309. $emailbody = get_lang('Dear').': '.api_get_person_name($tutor['firstname'], $tutor['lastname'])."\n";
  2310. $emailbody .= get_lang('MessageNewUserInTheCourse').': '.$name_course."\n";
  2311. $emailbody .= get_lang('UserName').': '.$student['username']."\n";
  2312. if (api_is_western_name_order()) {
  2313. $emailbody .= get_lang('FirstName').': '.$student['firstname']."\n";
  2314. $emailbody .= get_lang('LastName').': '.$student['lastname']."\n";
  2315. } else {
  2316. $emailbody .= get_lang('LastName').': '.$student['lastname']."\n";
  2317. $emailbody .= get_lang('FirstName').': '.$student['firstname']."\n";
  2318. }
  2319. $emailbody .= get_lang('Email').': <a href="mailto:'.$student['email'].'">'.$student['email']."</a>\n\n";
  2320. $recipient_name = api_get_person_name(
  2321. $tutor['firstname'],
  2322. $tutor['lastname'],
  2323. null,
  2324. PERSON_NAME_EMAIL_ADDRESS
  2325. );
  2326. $sender_name = api_get_person_name(
  2327. api_get_setting('administratorName'),
  2328. api_get_setting('administratorSurname'),
  2329. null,
  2330. PERSON_NAME_EMAIL_ADDRESS
  2331. );
  2332. $email_admin = api_get_setting('emailAdministrator');
  2333. $additionalParameters = [
  2334. 'smsType' => SmsPlugin::NEW_USER_SUBSCRIBED_COURSE,
  2335. 'userId' => $tutor['user_id'],
  2336. 'userUsername' => $student['username'],
  2337. 'courseCode' => $course_code,
  2338. ];
  2339. api_mail_html(
  2340. $recipient_name,
  2341. $emailto,
  2342. $emailsubject,
  2343. $emailbody,
  2344. $sender_name,
  2345. $email_admin,
  2346. null,
  2347. null,
  2348. null,
  2349. $additionalParameters
  2350. );
  2351. }
  2352. }
  2353. /**
  2354. * @return array
  2355. */
  2356. public static function get_special_course_list()
  2357. {
  2358. $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
  2359. $tbl_course_field = Database::get_main_table(TABLE_EXTRA_FIELD);
  2360. $tbl_course_field_value = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  2361. //we filter the courses from the URL
  2362. $join_access_url = $where_access_url = '';
  2363. if (api_get_multiple_access_url()) {
  2364. $access_url_id = api_get_current_access_url_id();
  2365. if ($access_url_id != -1) {
  2366. $tbl_url_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  2367. $join_access_url = "LEFT JOIN $tbl_url_course url_rel_course
  2368. ON url_rel_course.c_id = tcfv.item_id ";
  2369. $where_access_url = " AND access_url_id = $access_url_id ";
  2370. }
  2371. }
  2372. $extraFieldType = EntityExtraField::COURSE_FIELD_TYPE;
  2373. // get course list auto-register
  2374. $sql = "SELECT DISTINCT(c.id)
  2375. FROM $tbl_course_field_value tcfv
  2376. INNER JOIN $tbl_course_field tcf
  2377. ON tcfv.field_id = tcf.id $join_access_url
  2378. INNER JOIN $courseTable c
  2379. ON (c.id = tcfv.item_id)
  2380. WHERE
  2381. tcf.extra_field_type = $extraFieldType AND
  2382. tcf.variable = 'special_course' AND
  2383. tcfv.value = 1 $where_access_url";
  2384. $result = Database::query($sql);
  2385. $courseList = [];
  2386. if (Database::num_rows($result) > 0) {
  2387. while ($row = Database::fetch_array($result)) {
  2388. $courseList[] = $row['id'];
  2389. }
  2390. }
  2391. return $courseList;
  2392. }
  2393. /**
  2394. * Get the course codes that have been restricted in the catalogue, and if byUserId is set
  2395. * then the courses that the user is allowed or not to see in catalogue.
  2396. *
  2397. * @param bool $allowed Either if the courses have some users that are or are not allowed to see in catalogue
  2398. * @param int $byUserId if the courses are or are not allowed to see to the user
  2399. *
  2400. * @return array Course codes allowed or not to see in catalogue by some user or the user
  2401. */
  2402. public static function getCatalogueCourseList($allowed = true, $byUserId = -1)
  2403. {
  2404. $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
  2405. $tblCourseRelUserCatalogue = Database::get_main_table(TABLE_MAIN_COURSE_CATALOGUE_USER);
  2406. $visibility = $allowed ? 1 : 0;
  2407. // Restriction by user id
  2408. $currentUserRestriction = '';
  2409. if ($byUserId > 0) {
  2410. $byUserId = (int) $byUserId;
  2411. $currentUserRestriction = " AND tcruc.user_id = $byUserId ";
  2412. }
  2413. //we filter the courses from the URL
  2414. $joinAccessUrl = '';
  2415. $whereAccessUrl = '';
  2416. if (api_get_multiple_access_url()) {
  2417. $accessUrlId = api_get_current_access_url_id();
  2418. if ($accessUrlId != -1) {
  2419. $tblUrlCourse = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  2420. $joinAccessUrl = "LEFT JOIN $tblUrlCourse url_rel_course
  2421. ON url_rel_course.c_id = c.id ";
  2422. $whereAccessUrl = " AND access_url_id = $accessUrlId ";
  2423. }
  2424. }
  2425. // get course list auto-register
  2426. $sql = "SELECT DISTINCT(c.code)
  2427. FROM $tblCourseRelUserCatalogue tcruc
  2428. INNER JOIN $courseTable c
  2429. ON (c.id = tcruc.c_id) $joinAccessUrl
  2430. WHERE tcruc.visible = $visibility $currentUserRestriction $whereAccessUrl";
  2431. $result = Database::query($sql);
  2432. $courseList = [];
  2433. if (Database::num_rows($result) > 0) {
  2434. while ($resultRow = Database::fetch_array($result)) {
  2435. $courseList[] = $resultRow['code'];
  2436. }
  2437. }
  2438. return $courseList;
  2439. }
  2440. /**
  2441. * Get list of courses for a given user.
  2442. *
  2443. * @param int $user_id
  2444. * @param bool $include_sessions Whether to include courses from session or not
  2445. * @param bool $adminGetsAllCourses If the user is platform admin,
  2446. * whether he gets all the courses or just his. Note: This does *not* include all sessions
  2447. * @param bool $loadSpecialCourses
  2448. * @param array $skipCourseList List of course ids to skip
  2449. * @param bool $useUserLanguageFilterIfAvailable
  2450. * @param bool $showCoursesSessionWithDifferentKey
  2451. *
  2452. * @return array List of codes and db name
  2453. *
  2454. * @author isaac flores paz
  2455. */
  2456. public static function get_courses_list_by_user_id(
  2457. $user_id,
  2458. $include_sessions = false,
  2459. $adminGetsAllCourses = false,
  2460. $loadSpecialCourses = true,
  2461. $skipCourseList = [],
  2462. $useUserLanguageFilterIfAvailable = true,
  2463. $showCoursesSessionWithDifferentKey = false
  2464. ) {
  2465. $user_id = intval($user_id);
  2466. $urlId = api_get_current_access_url_id();
  2467. $course_list = [];
  2468. $codes = [];
  2469. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  2470. $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  2471. $tbl_user_course_category = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
  2472. $tableCourseUrl = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  2473. $languageCondition = '';
  2474. $onlyInUserLanguage = api_get_configuration_value('my_courses_show_courses_in_user_language_only');
  2475. if ($useUserLanguageFilterIfAvailable && $onlyInUserLanguage) {
  2476. $userInfo = api_get_user_info(api_get_user_id());
  2477. if (!empty($userInfo['language'])) {
  2478. $languageCondition = " AND course.course_language = '".$userInfo['language']."' ";
  2479. }
  2480. }
  2481. if ($adminGetsAllCourses && UserManager::is_admin($user_id)) {
  2482. // get the whole courses list
  2483. $sql = "SELECT DISTINCT(course.code), course.id as real_id, course.title
  2484. FROM $tbl_course course
  2485. INNER JOIN $tableCourseUrl url
  2486. ON (course.id = url.c_id)
  2487. WHERE
  2488. url.access_url_id = $urlId
  2489. $languageCondition
  2490. ";
  2491. } else {
  2492. $withSpecialCourses = $withoutSpecialCourses = '';
  2493. if ($loadSpecialCourses) {
  2494. $specialCourseList = self::get_special_course_list();
  2495. if (!empty($specialCourseList)) {
  2496. $specialCourseToString = '"'.implode('","', $specialCourseList).'"';
  2497. $withSpecialCourses = ' AND course.id IN ('.$specialCourseToString.')';
  2498. $withoutSpecialCourses = ' AND course.id NOT IN ('.$specialCourseToString.')';
  2499. }
  2500. if (!empty($withSpecialCourses)) {
  2501. $sql = "SELECT DISTINCT (course.code),
  2502. course.id as real_id,
  2503. course.category_code AS category,
  2504. course.title
  2505. FROM $tbl_course_user course_rel_user
  2506. LEFT JOIN $tbl_course course
  2507. ON course.id = course_rel_user.c_id
  2508. LEFT JOIN $tbl_user_course_category user_course_category
  2509. ON course_rel_user.user_course_cat = user_course_category.id
  2510. INNER JOIN $tableCourseUrl url
  2511. ON (course.id = url.c_id)
  2512. WHERE url.access_url_id = $urlId
  2513. $withSpecialCourses
  2514. $languageCondition
  2515. GROUP BY course.code
  2516. ORDER BY user_course_category.sort, course.title, course_rel_user.sort ASC
  2517. ";
  2518. $result = Database::query($sql);
  2519. if (Database::num_rows($result) > 0) {
  2520. while ($result_row = Database::fetch_array($result, 'ASSOC')) {
  2521. $result_row['special_course'] = 1;
  2522. $course_list[] = $result_row;
  2523. $codes[] = $result_row['real_id'];
  2524. }
  2525. }
  2526. }
  2527. }
  2528. // get course list not auto-register. Use Distinct to avoid multiple
  2529. // entries when a course is assigned to a HRD (DRH) as watcher
  2530. $sql = "SELECT
  2531. DISTINCT(course.code),
  2532. course.id as real_id,
  2533. course.category_code AS category,
  2534. course.title
  2535. FROM $tbl_course course
  2536. INNER JOIN $tbl_course_user cru
  2537. ON (course.id = cru.c_id)
  2538. INNER JOIN $tableCourseUrl url
  2539. ON (course.id = url.c_id)
  2540. WHERE
  2541. url.access_url_id = $urlId AND
  2542. cru.user_id = $user_id
  2543. $withoutSpecialCourses
  2544. $languageCondition
  2545. ORDER BY course.title
  2546. ";
  2547. }
  2548. $result = Database::query($sql);
  2549. if (Database::num_rows($result)) {
  2550. while ($row = Database::fetch_array($result, 'ASSOC')) {
  2551. if (!empty($skipCourseList)) {
  2552. if (in_array($row['real_id'], $skipCourseList)) {
  2553. continue;
  2554. }
  2555. }
  2556. $course_list[] = $row;
  2557. $codes[] = $row['real_id'];
  2558. }
  2559. }
  2560. if ($include_sessions === true) {
  2561. $sql = "SELECT DISTINCT (c.code),
  2562. c.id as real_id,
  2563. c.category_code AS category,
  2564. s.id as session_id,
  2565. s.name as session_name
  2566. FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)." scu
  2567. INNER JOIN $tbl_course c
  2568. ON (scu.c_id = c.id)
  2569. INNER JOIN ".Database::get_main_table(TABLE_MAIN_SESSION)." s
  2570. ON (s.id = scu.session_id)
  2571. WHERE user_id = $user_id ";
  2572. $r = Database::query($sql);
  2573. while ($row = Database::fetch_array($r, 'ASSOC')) {
  2574. if (!empty($skipCourseList)) {
  2575. if (in_array($row['real_id'], $skipCourseList)) {
  2576. continue;
  2577. }
  2578. }
  2579. if ($showCoursesSessionWithDifferentKey) {
  2580. $course_list[] = $row;
  2581. } else {
  2582. if (!in_array($row['real_id'], $codes)) {
  2583. $course_list[] = $row;
  2584. }
  2585. }
  2586. }
  2587. }
  2588. return $course_list;
  2589. }
  2590. /**
  2591. * Get course ID from a given course directory name.
  2592. *
  2593. * @param string $path Course directory (without any slash)
  2594. *
  2595. * @return string Course code, or false if not found
  2596. */
  2597. public static function getCourseCodeFromDirectory($path)
  2598. {
  2599. $path = Database::escape_string(str_replace('.', '', str_replace('/', '', $path)));
  2600. $res = Database::query("SELECT code FROM ".Database::get_main_table(TABLE_MAIN_COURSE)."
  2601. WHERE directory LIKE BINARY '$path'");
  2602. if ($res === false) {
  2603. return false;
  2604. }
  2605. if (Database::num_rows($res) != 1) {
  2606. return false;
  2607. }
  2608. $row = Database::fetch_array($res);
  2609. return $row['code'];
  2610. }
  2611. /**
  2612. * Get course code(s) from visual code.
  2613. *
  2614. * @deprecated
  2615. *
  2616. * @param string Visual code
  2617. *
  2618. * @return array List of codes for the given visual code
  2619. */
  2620. public static function get_courses_info_from_visual_code($code)
  2621. {
  2622. $result = [];
  2623. $sql_result = Database::query("SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE)."
  2624. WHERE visual_code = '".Database::escape_string($code)."'");
  2625. while ($virtual_course = Database::fetch_array($sql_result)) {
  2626. $result[] = $virtual_course;
  2627. }
  2628. return $result;
  2629. }
  2630. /**
  2631. * Creates a new extra field for a given course.
  2632. *
  2633. * @param string $variable Field's internal variable name
  2634. * @param int $fieldType Field's type
  2635. * @param string $displayText Field's language var name
  2636. * @param string $default Optional. The default value
  2637. *
  2638. * @return int New extra field ID
  2639. */
  2640. public static function create_course_extra_field($variable, $fieldType, $displayText, $default = '')
  2641. {
  2642. $extraField = new ExtraField('course');
  2643. $params = [
  2644. 'variable' => $variable,
  2645. 'field_type' => $fieldType,
  2646. 'display_text' => $displayText,
  2647. 'default_value' => $default,
  2648. ];
  2649. return $extraField->save($params);
  2650. }
  2651. /**
  2652. * Update course attributes. Will only update attributes with a non-empty value.
  2653. * Note that you NEED to check that your attributes are valid before using this function.
  2654. *
  2655. * @param int Course id
  2656. * @param array Associative array with field names as keys and field values as values
  2657. *
  2658. * @return Doctrine\DBAL\Driver\Statement|null True if update was successful, false otherwise
  2659. */
  2660. public static function update_attributes($id, $attributes)
  2661. {
  2662. $id = (int) $id;
  2663. $table = Database::get_main_table(TABLE_MAIN_COURSE);
  2664. $sql = "UPDATE $table SET ";
  2665. $i = 0;
  2666. foreach ($attributes as $name => $value) {
  2667. if ($value != '') {
  2668. if ($i > 0) {
  2669. $sql .= ", ";
  2670. }
  2671. $sql .= " $name = '".Database::escape_string($value)."'";
  2672. $i++;
  2673. }
  2674. }
  2675. $sql .= " WHERE id = $id";
  2676. return Database::query($sql);
  2677. }
  2678. /**
  2679. * Update an extra field value for a given course.
  2680. *
  2681. * @param string $course_code Course code
  2682. * @param string $variable Field variable name
  2683. * @param string $value Optional. Default field value
  2684. *
  2685. * @return bool|int An integer when register a new extra field. And boolean when update the extrafield
  2686. */
  2687. public static function update_course_extra_field_value($course_code, $variable, $value = '')
  2688. {
  2689. $courseInfo = api_get_course_info($course_code);
  2690. $courseId = $courseInfo['real_id'];
  2691. $extraFieldValues = new ExtraFieldValue('course');
  2692. $params = [
  2693. 'item_id' => $courseId,
  2694. 'variable' => $variable,
  2695. 'value' => $value,
  2696. ];
  2697. return $extraFieldValues->save($params);
  2698. }
  2699. /**
  2700. * @param int $sessionId
  2701. *
  2702. * @return mixed
  2703. */
  2704. public static function get_session_category_id_by_session_id($sessionId)
  2705. {
  2706. if (empty($sessionId)) {
  2707. return [];
  2708. }
  2709. $sessionId = intval($sessionId);
  2710. $sql = 'SELECT sc.id session_category
  2711. FROM '.Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY).' sc
  2712. INNER JOIN '.Database::get_main_table(TABLE_MAIN_SESSION).' s
  2713. ON sc.id = s.session_category_id
  2714. WHERE s.id = '.$sessionId;
  2715. return Database::result(
  2716. Database::query($sql),
  2717. 0,
  2718. 'session_category'
  2719. );
  2720. }
  2721. /**
  2722. * Gets the value of a course extra field. Returns null if it was not found.
  2723. *
  2724. * @param string $variable Name of the extra field
  2725. * @param string $code Course code
  2726. *
  2727. * @return string Value
  2728. */
  2729. public static function get_course_extra_field_value($variable, $code)
  2730. {
  2731. $courseInfo = api_get_course_info($code);
  2732. $courseId = $courseInfo['real_id'];
  2733. $extraFieldValues = new ExtraFieldValue('course');
  2734. $result = $extraFieldValues->get_values_by_handler_and_field_variable($courseId, $variable);
  2735. if (!empty($result['value'])) {
  2736. return $result['value'];
  2737. }
  2738. return null;
  2739. }
  2740. /**
  2741. * Lists details of the course description.
  2742. *
  2743. * @param array The course description
  2744. * @param string The encoding
  2745. * @param bool If true is displayed if false is hidden
  2746. *
  2747. * @return string The course description in html
  2748. */
  2749. public static function get_details_course_description_html(
  2750. $descriptions,
  2751. $charset,
  2752. $action_show = true
  2753. ) {
  2754. $data = null;
  2755. if (isset($descriptions) && count($descriptions) > 0) {
  2756. foreach ($descriptions as $description) {
  2757. $data .= '<div class="sectiontitle">';
  2758. if (api_is_allowed_to_edit() && $action_show) {
  2759. //delete
  2760. $data .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=delete&description_id='.$description->id.'" onclick="javascript:if(!confirm(\''.addslashes(api_htmlentities(
  2761. get_lang('ConfirmYourChoice'),
  2762. ENT_QUOTES,
  2763. $charset
  2764. )).'\')) return false;">';
  2765. $data .= Display::return_icon(
  2766. 'delete.gif',
  2767. get_lang('Delete'),
  2768. ['style' => 'vertical-align:middle;float:right;']
  2769. );
  2770. $data .= '</a> ';
  2771. //edit
  2772. $data .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&description_id='.$description->id.'">';
  2773. $data .= Display::return_icon(
  2774. 'edit.png',
  2775. get_lang('Edit'),
  2776. ['style' => 'vertical-align:middle;float:right; padding-right:4px;'],
  2777. ICON_SIZE_SMALL
  2778. );
  2779. $data .= '</a> ';
  2780. }
  2781. $data .= $description->title;
  2782. $data .= '</div>';
  2783. $data .= '<div class="sectioncomment">';
  2784. $data .= Security::remove_XSS($description->content);
  2785. $data .= '</div>';
  2786. }
  2787. } else {
  2788. $data .= '<em>'.get_lang('ThisCourseDescriptionIsEmpty').'</em>';
  2789. }
  2790. return $data;
  2791. }
  2792. /**
  2793. * Returns the details of a course category.
  2794. *
  2795. * @param string $code Category code
  2796. *
  2797. * @return array Course category
  2798. */
  2799. public static function get_course_category($code)
  2800. {
  2801. $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
  2802. $code = Database::escape_string($code);
  2803. $sql = "SELECT * FROM $table WHERE code = '$code'";
  2804. return Database::fetch_array(Database::query($sql));
  2805. }
  2806. /**
  2807. * Subscribes courses to human resource manager (Dashboard feature).
  2808. *
  2809. * @param int $hr_manager_id Human Resource Manager id
  2810. * @param array $courses_list Courses code
  2811. *
  2812. * @return int
  2813. */
  2814. public static function subscribeCoursesToDrhManager($hr_manager_id, $courses_list)
  2815. {
  2816. $tbl_course_rel_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  2817. $tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  2818. $hr_manager_id = intval($hr_manager_id);
  2819. $affected_rows = 0;
  2820. //Deleting assigned courses to hrm_id
  2821. if (api_is_multiple_url_enabled()) {
  2822. $sql = "SELECT s.c_id FROM $tbl_course_rel_user s
  2823. INNER JOIN $tbl_course_rel_access_url a
  2824. ON (a.c_id = s.c_id)
  2825. WHERE
  2826. user_id = $hr_manager_id AND
  2827. relation_type = ".COURSE_RELATION_TYPE_RRHH." AND
  2828. access_url_id = ".api_get_current_access_url_id();
  2829. } else {
  2830. $sql = "SELECT c_id FROM $tbl_course_rel_user
  2831. WHERE user_id = $hr_manager_id AND relation_type = ".COURSE_RELATION_TYPE_RRHH;
  2832. }
  2833. $result = Database::query($sql);
  2834. if (Database::num_rows($result) > 0) {
  2835. while ($row = Database::fetch_array($result)) {
  2836. $sql = "DELETE FROM $tbl_course_rel_user
  2837. WHERE
  2838. c_id = {$row['c_id']} AND
  2839. user_id = $hr_manager_id AND
  2840. relation_type = ".COURSE_RELATION_TYPE_RRHH;
  2841. Database::query($sql);
  2842. }
  2843. }
  2844. // inserting new courses list
  2845. if (is_array($courses_list)) {
  2846. foreach ($courses_list as $course_code) {
  2847. $courseInfo = api_get_course_info($course_code);
  2848. $courseId = $courseInfo['real_id'];
  2849. $sql = "INSERT IGNORE INTO $tbl_course_rel_user(c_id, user_id, status, relation_type)
  2850. VALUES($courseId, $hr_manager_id, ".DRH.", ".COURSE_RELATION_TYPE_RRHH.")";
  2851. $result = Database::query($sql);
  2852. if (Database::affected_rows($result)) {
  2853. $affected_rows++;
  2854. }
  2855. }
  2856. }
  2857. return $affected_rows;
  2858. }
  2859. /**
  2860. * get courses followed by human resources manager.
  2861. *
  2862. * @param int $user_id
  2863. * @param int $status
  2864. * @param int $from
  2865. * @param int $limit
  2866. * @param string $column
  2867. * @param string $direction
  2868. * @param bool $getCount
  2869. *
  2870. * @return array courses
  2871. */
  2872. public static function get_courses_followed_by_drh(
  2873. $user_id,
  2874. $status = DRH,
  2875. $from = null,
  2876. $limit = null,
  2877. $column = null,
  2878. $direction = null,
  2879. $getCount = false
  2880. ) {
  2881. return self::getCoursesFollowedByUser(
  2882. $user_id,
  2883. $status,
  2884. $from,
  2885. $limit,
  2886. $column,
  2887. $direction,
  2888. $getCount
  2889. );
  2890. }
  2891. /**
  2892. * get courses followed by user.
  2893. *
  2894. * @param int $user_id
  2895. * @param int $status
  2896. * @param int $from
  2897. * @param int $limit
  2898. * @param string $column
  2899. * @param string $direction
  2900. * @param bool $getCount
  2901. * @param string $keyword
  2902. * @param int $sessionId
  2903. * @param bool $showAllAssignedCourses
  2904. *
  2905. * @return array courses
  2906. */
  2907. public static function getCoursesFollowedByUser(
  2908. $user_id,
  2909. $status = null,
  2910. $from = null,
  2911. $limit = null,
  2912. $column = null,
  2913. $direction = null,
  2914. $getCount = false,
  2915. $keyword = null,
  2916. $sessionId = 0,
  2917. $showAllAssignedCourses = false
  2918. ) {
  2919. // Database Table Definitions
  2920. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  2921. $tbl_course_rel_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  2922. $tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  2923. $sessionId = (int) $sessionId;
  2924. $user_id = (int) $user_id;
  2925. $select = "SELECT DISTINCT c.*, c.id as real_id ";
  2926. if ($getCount) {
  2927. $select = "SELECT COUNT(DISTINCT c.id) as count";
  2928. }
  2929. $whereConditions = '';
  2930. switch ($status) {
  2931. case COURSEMANAGER:
  2932. $whereConditions .= " AND cru.user_id = $user_id";
  2933. if (!$showAllAssignedCourses) {
  2934. $whereConditions .= " AND cru.status = ".COURSEMANAGER;
  2935. } else {
  2936. $whereConditions .= " AND relation_type = ".COURSE_RELATION_TYPE_COURSE_MANAGER;
  2937. }
  2938. break;
  2939. case DRH:
  2940. $whereConditions .= " AND
  2941. cru.user_id = $user_id AND
  2942. cru.status = ".DRH." AND
  2943. relation_type = '".COURSE_RELATION_TYPE_RRHH."'
  2944. ";
  2945. break;
  2946. }
  2947. $keywordCondition = null;
  2948. if (!empty($keyword)) {
  2949. $keyword = Database::escape_string($keyword);
  2950. $keywordCondition = " AND (c.code LIKE '%$keyword%' OR c.title LIKE '%$keyword%' ) ";
  2951. }
  2952. $orderBy = null;
  2953. $extraInnerJoin = null;
  2954. if (!empty($sessionId)) {
  2955. if ($status == COURSEMANAGER) {
  2956. // Teacher of course or teacher inside session
  2957. $whereConditions = " AND (cru.status = ".COURSEMANAGER." OR srcru.status = 2) ";
  2958. }
  2959. $courseList = SessionManager::get_course_list_by_session_id($sessionId);
  2960. if (!empty($courseList)) {
  2961. $courseListToString = implode("','", array_keys($courseList));
  2962. $whereConditions .= " AND c.id IN ('".$courseListToString."')";
  2963. }
  2964. $tableSessionRelCourse = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  2965. $tableSessionRelCourseRelUser = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2966. $orderBy = ' ORDER BY position';
  2967. $extraInnerJoin = " INNER JOIN $tableSessionRelCourse src
  2968. ON (c.id = src.c_id AND src.session_id = $sessionId)
  2969. INNER JOIN $tableSessionRelCourseRelUser srcru
  2970. ON (src.session_id = srcru.session_id AND srcru.c_id = src.c_id)
  2971. ";
  2972. }
  2973. $whereConditions .= $keywordCondition;
  2974. $sql = "$select
  2975. FROM $tbl_course c
  2976. INNER JOIN $tbl_course_rel_user cru
  2977. ON (cru.c_id = c.id)
  2978. INNER JOIN $tbl_course_rel_access_url a
  2979. ON (a.c_id = c.id)
  2980. $extraInnerJoin
  2981. WHERE
  2982. access_url_id = ".api_get_current_access_url_id()."
  2983. $whereConditions
  2984. $orderBy
  2985. ";
  2986. if (isset($from) && isset($limit)) {
  2987. $from = intval($from);
  2988. $limit = intval($limit);
  2989. $sql .= " LIMIT $from, $limit";
  2990. }
  2991. $result = Database::query($sql);
  2992. if ($getCount) {
  2993. $row = Database::fetch_array($result);
  2994. return $row['count'];
  2995. }
  2996. $courses = [];
  2997. if (Database::num_rows($result) > 0) {
  2998. while ($row = Database::fetch_array($result)) {
  2999. $courses[$row['code']] = $row;
  3000. }
  3001. }
  3002. return $courses;
  3003. }
  3004. /**
  3005. * check if a course is special (autoregister).
  3006. *
  3007. * @param int $courseId
  3008. *
  3009. * @return bool
  3010. */
  3011. public static function isSpecialCourse($courseId)
  3012. {
  3013. $extraFieldValue = new ExtraFieldValue('course');
  3014. $result = $extraFieldValue->get_values_by_handler_and_field_variable(
  3015. $courseId,
  3016. 'special_course'
  3017. );
  3018. if (!empty($result)) {
  3019. if ($result['value'] == 1) {
  3020. return true;
  3021. }
  3022. }
  3023. return false;
  3024. }
  3025. /**
  3026. * Update course picture.
  3027. *
  3028. * @param array $courseInfo
  3029. * @param string File name
  3030. * @param string the full system name of the image
  3031. * from which course picture will be created
  3032. * @param string $cropParameters Optional string that contents "x,y,width,height" of a cropped image format
  3033. *
  3034. * @return bool Returns the resulting. In case of internal error or negative validation returns FALSE.
  3035. */
  3036. public static function update_course_picture(
  3037. $courseInfo,
  3038. $filename,
  3039. $source_file = null,
  3040. $cropParameters = null
  3041. ) {
  3042. if (empty($courseInfo)) {
  3043. return false;
  3044. }
  3045. // course path
  3046. $store_path = api_get_path(SYS_COURSE_PATH).$courseInfo['path'];
  3047. // image name for courses
  3048. $course_image = $store_path.'/course-pic.png';
  3049. $course_medium_image = $store_path.'/course-pic85x85.png';
  3050. if (file_exists($course_image)) {
  3051. unlink($course_image);
  3052. }
  3053. if (file_exists($course_medium_image)) {
  3054. unlink($course_medium_image);
  3055. }
  3056. //Crop the image to adjust 4:3 ratio
  3057. $image = new Image($source_file);
  3058. $image->crop($cropParameters);
  3059. //Resize the images in two formats
  3060. $medium = new Image($source_file);
  3061. $medium->resize(85);
  3062. $medium->send_image($course_medium_image, -1, 'png');
  3063. $normal = new Image($source_file);
  3064. $normal->resize(400);
  3065. $normal->send_image($course_image, -1, 'png');
  3066. $result = $medium && $normal;
  3067. return $result ? $result : false;
  3068. }
  3069. /**
  3070. * Deletes the course picture.
  3071. *
  3072. * @param string $courseCode
  3073. */
  3074. public static function deleteCoursePicture($courseCode)
  3075. {
  3076. $course_info = api_get_course_info($courseCode);
  3077. // course path
  3078. $storePath = api_get_path(SYS_COURSE_PATH).$course_info['path'];
  3079. // image name for courses
  3080. $courseImage = $storePath.'/course-pic.png';
  3081. $courseMediumImage = $storePath.'/course-pic85x85.png';
  3082. $courseSmallImage = $storePath.'/course-pic32.png';
  3083. if (file_exists($courseImage)) {
  3084. unlink($courseImage);
  3085. }
  3086. if (file_exists($courseMediumImage)) {
  3087. unlink($courseMediumImage);
  3088. }
  3089. if (file_exists($courseSmallImage)) {
  3090. unlink($courseSmallImage);
  3091. }
  3092. }
  3093. /**
  3094. * Display special courses (and only these) as several HTML divs of class userportal-course-item.
  3095. *
  3096. * Special courses are courses that stick on top of the list and are "auto-registerable"
  3097. * in the sense that any user clicking them is registered as a student
  3098. *
  3099. * @param int $user_id User id
  3100. * @param bool $load_dirs Whether to show the document quick-loader or not
  3101. * @param bool $useUserLanguageFilterIfAvailable
  3102. *
  3103. * @return array
  3104. */
  3105. public static function returnSpecialCourses(
  3106. $user_id,
  3107. $load_dirs = false,
  3108. $useUserLanguageFilterIfAvailable = true
  3109. ) {
  3110. $user_id = (int) $user_id;
  3111. $table = Database::get_main_table(TABLE_MAIN_COURSE);
  3112. $specialCourseList = self::get_special_course_list();
  3113. if (empty($specialCourseList)) {
  3114. return [];
  3115. }
  3116. // Filter by language
  3117. $languageCondition = '';
  3118. $onlyInUserLanguage = api_get_configuration_value('my_courses_show_courses_in_user_language_only');
  3119. if ($useUserLanguageFilterIfAvailable && $onlyInUserLanguage) {
  3120. $userInfo = api_get_user_info(api_get_user_id());
  3121. if (!empty($userInfo['language'])) {
  3122. $languageCondition = " AND course_language = '".$userInfo['language']."' ";
  3123. }
  3124. }
  3125. $sql = "SELECT
  3126. id,
  3127. code,
  3128. subscribe subscr,
  3129. unsubscribe unsubscr
  3130. FROM $table
  3131. WHERE
  3132. id IN ('".implode("','", $specialCourseList)."')
  3133. $languageCondition
  3134. GROUP BY code";
  3135. $rs_special_course = Database::query($sql);
  3136. $number_of_courses = Database::num_rows($rs_special_course);
  3137. $showCustomIcon = api_get_setting('course_images_in_courses_list');
  3138. $courseList = [];
  3139. if ($number_of_courses > 0) {
  3140. while ($course = Database::fetch_array($rs_special_course)) {
  3141. $course_info = api_get_course_info($course['code']);
  3142. $courseId = $course_info['real_id'];
  3143. if ($course_info['visibility'] == COURSE_VISIBILITY_HIDDEN) {
  3144. continue;
  3145. }
  3146. $params = [];
  3147. //Param (course_code) needed to get the student info in page "My courses"
  3148. $params['course_code'] = $course['code'];
  3149. $params['code'] = $course['code'];
  3150. // Get notifications.
  3151. $course_info['id_session'] = null;
  3152. $courseUserInfo = self::getUserCourseInfo($user_id, $courseId);
  3153. if (empty($courseUserInfo)) {
  3154. $course_info['status'] = STUDENT;
  3155. } else {
  3156. $course_info['status'] = $courseUserInfo['status'];
  3157. }
  3158. $show_notification = !api_get_configuration_value('hide_course_notification')
  3159. ? Display::show_notification($course_info)
  3160. : '';
  3161. $params['edit_actions'] = '';
  3162. $params['document'] = '';
  3163. if (api_is_platform_admin()) {
  3164. $params['edit_actions'] .= api_get_path(WEB_CODE_PATH).'course_info/infocours.php?cidReq='.$course['code'];
  3165. if ($load_dirs) {
  3166. $params['document'] = '<a id="document_preview_'.$courseId.'_0" class="document_preview btn btn-default btn-sm" href="javascript:void(0);">'
  3167. .Display::returnFontAwesomeIcon('folder-open').'</a>';
  3168. $params['document'] .= Display::div('', ['id' => 'document_result_'.$courseId.'_0', 'class' => 'document_preview_container']);
  3169. }
  3170. } else {
  3171. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED && $load_dirs) {
  3172. $params['document'] = '<a id="document_preview_'.$courseId.'_0" class="document_preview btn btn-default btn-sm" href="javascript:void(0);">'
  3173. .Display::returnFontAwesomeIcon('folder-open').'</a>';
  3174. $params['document'] .= Display::div('', ['id' => 'document_result_'.$courseId.'_0', 'class' => 'document_preview_container']);
  3175. }
  3176. }
  3177. $params['visibility'] = $course_info['visibility'];
  3178. $params['status'] = $course_info['status'];
  3179. $params['category'] = $course_info['categoryName'];
  3180. $params['category_code'] = $course_info['categoryCode'];
  3181. $params['icon'] = Display::return_icon(
  3182. 'drawing-pin.png',
  3183. null,
  3184. null,
  3185. ICON_SIZE_LARGE,
  3186. null
  3187. );
  3188. if (api_get_setting('display_coursecode_in_courselist') == 'true') {
  3189. $params['code_course'] = '('.$course_info['visual_code'].')';
  3190. }
  3191. $params['title'] = $course_info['title'];
  3192. $params['title_cut'] = $course_info['title'];
  3193. $params['link'] = $course_info['course_public_url'].'?id_session=0&autoreg=1';
  3194. if (api_get_setting('display_teacher_in_courselist') === 'true') {
  3195. $params['teachers'] = self::getTeachersFromCourse(
  3196. $courseId,
  3197. true
  3198. );
  3199. }
  3200. if ($showCustomIcon === 'true') {
  3201. $params['thumbnails'] = $course_info['course_image'];
  3202. $params['image'] = $course_info['course_image_large'];
  3203. }
  3204. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED) {
  3205. $params['notifications'] = $show_notification;
  3206. }
  3207. $params['is_special_course'] = true;
  3208. $courseList[] = $params;
  3209. }
  3210. }
  3211. return $courseList;
  3212. }
  3213. /**
  3214. * Display courses (without special courses) as several HTML divs
  3215. * of course categories, as class userportal-catalog-item.
  3216. *
  3217. * @uses \displayCoursesInCategory() to display the courses themselves
  3218. *
  3219. * @param int $user_id
  3220. * @param bool $load_dirs Whether to show the document quick-loader or not
  3221. * @param bool $useUserLanguageFilterIfAvailable
  3222. *
  3223. * @return array
  3224. */
  3225. public static function returnCourses(
  3226. $user_id,
  3227. $load_dirs = false,
  3228. $useUserLanguageFilterIfAvailable = true
  3229. ) {
  3230. $user_id = (int) $user_id;
  3231. if (empty($user_id)) {
  3232. $user_id = api_get_user_id();
  3233. }
  3234. // Step 1: We get all the categories of the user
  3235. $table = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
  3236. $sql = "SELECT * FROM $table
  3237. WHERE user_id = $user_id
  3238. ORDER BY sort ASC";
  3239. $result = Database::query($sql);
  3240. $listItems = [
  3241. 'in_category' => [],
  3242. 'not_category' => [],
  3243. ];
  3244. $collapsable = api_get_configuration_value('allow_user_course_category_collapsable');
  3245. $stok = Security::get_token();
  3246. while ($row = Database::fetch_array($result)) {
  3247. // We simply display the title of the category.
  3248. $courseInCategory = self::returnCoursesCategories(
  3249. $row['id'],
  3250. $load_dirs,
  3251. $user_id,
  3252. $useUserLanguageFilterIfAvailable
  3253. );
  3254. $collapsed = 0;
  3255. $collapsableLink = '';
  3256. if ($collapsable) {
  3257. $url = api_get_path(WEB_CODE_PATH).
  3258. 'auth/courses.php?categoryid='.$row['id'].'&sec_token='.$stok.'&redirect=home';
  3259. $collapsed = isset($row['collapsed']) && $row['collapsed'] ? 1 : 0;
  3260. if ($collapsed === 0) {
  3261. $collapsableLink = Display::url(
  3262. '<i class="fa fa-folder-open"></i>',
  3263. $url.'&action=set_collapsable&option=1'
  3264. );
  3265. } else {
  3266. $collapsableLink = Display::url(
  3267. '<i class="fa fa-folder"></i>',
  3268. $url.'&action=set_collapsable&option=0'
  3269. );
  3270. }
  3271. }
  3272. $params = [
  3273. 'id_category' => $row['id'],
  3274. 'title_category' => $row['title'],
  3275. 'collapsed' => $collapsed,
  3276. 'collapsable_link' => $collapsableLink,
  3277. 'courses' => $courseInCategory,
  3278. ];
  3279. $listItems['in_category'][] = $params;
  3280. }
  3281. // Step 2: We display the course without a user category.
  3282. $coursesNotCategory = self::returnCoursesCategories(
  3283. 0,
  3284. $load_dirs,
  3285. $user_id,
  3286. $useUserLanguageFilterIfAvailable
  3287. );
  3288. if ($coursesNotCategory) {
  3289. $listItems['not_category'] = $coursesNotCategory;
  3290. }
  3291. return $listItems;
  3292. }
  3293. /**
  3294. * Display courses inside a category (without special courses) as HTML dics of
  3295. * class userportal-course-item.
  3296. *
  3297. * @param int $user_category_id User category id
  3298. * @param bool $load_dirs Whether to show the document quick-loader or not
  3299. * @param int $user_id
  3300. * @param bool $useUserLanguageFilterIfAvailable
  3301. *
  3302. * @return array
  3303. */
  3304. public static function returnCoursesCategories(
  3305. $user_category_id,
  3306. $load_dirs = false,
  3307. $user_id = 0,
  3308. $useUserLanguageFilterIfAvailable = true
  3309. ) {
  3310. $user_id = $user_id ? (int) $user_id : api_get_user_id();
  3311. $user_category_id = (int) $user_category_id;
  3312. // Table definitions
  3313. $TABLECOURS = Database::get_main_table(TABLE_MAIN_COURSE);
  3314. $TABLECOURSUSER = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  3315. $TABLE_ACCESS_URL_REL_COURSE = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  3316. $current_url_id = api_get_current_access_url_id();
  3317. // Get course list auto-register
  3318. $special_course_list = self::get_special_course_list();
  3319. $without_special_courses = '';
  3320. if (!empty($special_course_list)) {
  3321. $without_special_courses = ' AND course.id NOT IN ("'.implode('","', $special_course_list).'")';
  3322. }
  3323. $userCategoryCondition = " (course_rel_user.user_course_cat = $user_category_id) ";
  3324. if (empty($user_category_id)) {
  3325. $userCategoryCondition = ' (course_rel_user.user_course_cat = 0 OR course_rel_user.user_course_cat IS NULL) ';
  3326. }
  3327. $languageCondition = '';
  3328. $onlyInUserLanguage = api_get_configuration_value('my_courses_show_courses_in_user_language_only');
  3329. if ($useUserLanguageFilterIfAvailable && $onlyInUserLanguage) {
  3330. $userInfo = api_get_user_info(api_get_user_id());
  3331. if (!empty($userInfo['language'])) {
  3332. $languageCondition = " AND course.course_language = '".$userInfo['language']."' ";
  3333. }
  3334. }
  3335. $sql = "SELECT DISTINCT
  3336. course.id,
  3337. course_rel_user.status status,
  3338. course.code as course_code,
  3339. user_course_cat,
  3340. course_rel_user.sort
  3341. FROM $TABLECOURS course
  3342. INNER JOIN $TABLECOURSUSER course_rel_user
  3343. ON (course.id = course_rel_user.c_id)
  3344. INNER JOIN $TABLE_ACCESS_URL_REL_COURSE url
  3345. ON (url.c_id = course.id)
  3346. WHERE
  3347. course_rel_user.user_id = $user_id AND
  3348. $userCategoryCondition
  3349. $without_special_courses
  3350. $languageCondition
  3351. ";
  3352. // If multiple URL access mode is enabled, only fetch courses
  3353. // corresponding to the current URL.
  3354. if (api_get_multiple_access_url() && $current_url_id != -1) {
  3355. $sql .= " AND access_url_id = $current_url_id";
  3356. }
  3357. // Use user's classification for courses (if any).
  3358. $sql .= ' ORDER BY course_rel_user.user_course_cat, course_rel_user.sort ASC';
  3359. $result = Database::query($sql);
  3360. $showCustomIcon = api_get_setting('course_images_in_courses_list');
  3361. // Browse through all courses.
  3362. $courseAdded = [];
  3363. $courseList = [];
  3364. while ($row = Database::fetch_array($result)) {
  3365. $course_info = api_get_course_info_by_id($row['id']);
  3366. if (empty($course_info)) {
  3367. continue;
  3368. }
  3369. if (isset($course_info['visibility']) &&
  3370. $course_info['visibility'] == COURSE_VISIBILITY_HIDDEN
  3371. ) {
  3372. continue;
  3373. }
  3374. // Skip if already in list
  3375. if (in_array($course_info['real_id'], $courseAdded)) {
  3376. continue;
  3377. }
  3378. $course_info['id_session'] = null;
  3379. $course_info['status'] = $row['status'];
  3380. // For each course, get if there is any notification icon to show
  3381. // (something that would have changed since the user's last visit).
  3382. $showNotification = !api_get_configuration_value('hide_course_notification')
  3383. ? Display::show_notification($course_info)
  3384. : '';
  3385. $iconName = basename($course_info['course_image']);
  3386. $params = [];
  3387. //Param (course_code) needed to get the student process
  3388. $params['course_code'] = $row['course_code'];
  3389. $params['code'] = $row['course_code'];
  3390. if ($showCustomIcon === 'true' && $iconName != 'course.png') {
  3391. $params['thumbnails'] = $course_info['course_image'];
  3392. $params['image'] = $course_info['course_image_large'];
  3393. }
  3394. $thumbnails = null;
  3395. $image = null;
  3396. if ($showCustomIcon === 'true' && $iconName != 'course.png') {
  3397. $thumbnails = $course_info['course_image'];
  3398. $image = $course_info['course_image_large'];
  3399. } else {
  3400. $image = Display::return_icon(
  3401. 'session_default.png',
  3402. null,
  3403. null,
  3404. null,
  3405. null,
  3406. true
  3407. );
  3408. }
  3409. $params['course_id'] = $course_info['real_id'];
  3410. $params['edit_actions'] = '';
  3411. $params['document'] = '';
  3412. if (api_is_platform_admin()) {
  3413. $params['edit_actions'] .= api_get_path(WEB_CODE_PATH).'course_info/infocours.php?cidReq='.$course_info['code'];
  3414. if ($load_dirs) {
  3415. $params['document'] = '<a id="document_preview_'.$course_info['real_id'].'_0" class="document_preview btn btn-default btn-sm" href="javascript:void(0);">'
  3416. .Display::returnFontAwesomeIcon('folder-open').'</a>';
  3417. $params['document'] .= Display::div(
  3418. '',
  3419. [
  3420. 'id' => 'document_result_'.$course_info['real_id'].'_0',
  3421. 'class' => 'document_preview_container',
  3422. ]
  3423. );
  3424. }
  3425. }
  3426. if ($load_dirs) {
  3427. $params['document'] = '<a id="document_preview_'.$course_info['real_id'].'_0" class="document_preview btn btn-default btn-sm" href="javascript:void(0);">'
  3428. .Display::returnFontAwesomeIcon('folder-open').'</a>';
  3429. $params['document'] .= Display::div(
  3430. '',
  3431. [
  3432. 'id' => 'document_result_'.$course_info['real_id'].'_0',
  3433. 'class' => 'document_preview_container',
  3434. ]
  3435. );
  3436. }
  3437. $courseUrl = api_get_path(WEB_COURSE_PATH).$course_info['path'].'/index.php?id_session=0';
  3438. $teachers = [];
  3439. if (api_get_setting('display_teacher_in_courselist') === 'true') {
  3440. $teachers = self::getTeachersFromCourse(
  3441. $course_info['real_id'],
  3442. true
  3443. );
  3444. }
  3445. $params['status'] = $row['status'];
  3446. if (api_get_setting('display_coursecode_in_courselist') === 'true') {
  3447. $params['code_course'] = '('.$course_info['visual_code'].') ';
  3448. }
  3449. $params['current_user_is_teacher'] = false;
  3450. /** @var array $teacher */
  3451. foreach ($teachers as $teacher) {
  3452. if ($teacher['id'] != $user_id) {
  3453. continue;
  3454. }
  3455. $params['current_user_is_teacher'] = true;
  3456. }
  3457. $params['visibility'] = $course_info['visibility'];
  3458. $params['link'] = $courseUrl;
  3459. $params['thumbnails'] = $thumbnails;
  3460. $params['image'] = $image;
  3461. $params['title'] = $course_info['title'];
  3462. $params['title_cut'] = $params['title'];
  3463. $params['category'] = $course_info['categoryName'];
  3464. $params['category_code'] = $course_info['categoryCode'];
  3465. $params['teachers'] = $teachers;
  3466. $params['real_id'] = $course_info['real_id'];
  3467. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED) {
  3468. $params['notifications'] = $showNotification;
  3469. }
  3470. $courseAdded[] = $course_info['real_id'];
  3471. $courseList[] = $params;
  3472. }
  3473. return $courseList;
  3474. }
  3475. /**
  3476. * Retrieves the user defined course categories.
  3477. *
  3478. * @param int $userId
  3479. *
  3480. * @return array
  3481. */
  3482. public static function get_user_course_categories($userId = 0)
  3483. {
  3484. $userId = empty($userId) ? api_get_user_id() : (int) $userId;
  3485. $table = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
  3486. $sql = "SELECT * FROM $table
  3487. WHERE user_id = $userId
  3488. ORDER BY sort ASC
  3489. ";
  3490. $result = Database::query($sql);
  3491. $output = [];
  3492. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3493. $output[$row['id']] = $row;
  3494. }
  3495. return $output;
  3496. }
  3497. /**
  3498. * Return an array the user_category id and title for the course $courseId for user $userId.
  3499. *
  3500. * @param $userId
  3501. * @param $courseId
  3502. *
  3503. * @return array
  3504. */
  3505. public static function getUserCourseCategoryForCourse($userId, $courseId)
  3506. {
  3507. $tblCourseRelUser = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  3508. $tblUserCategory = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
  3509. $courseId = intval($courseId);
  3510. $userId = intval($userId);
  3511. $sql = "SELECT user_course_cat, title
  3512. FROM $tblCourseRelUser cru
  3513. LEFT JOIN $tblUserCategory ucc
  3514. ON cru.user_course_cat = ucc.id
  3515. WHERE
  3516. cru.user_id = $userId AND c_id = $courseId ";
  3517. $res = Database::query($sql);
  3518. $data = [];
  3519. if (Database::num_rows($res) > 0) {
  3520. $data = Database::fetch_assoc($res);
  3521. }
  3522. return $data;
  3523. }
  3524. /**
  3525. * Get the course id based on the original id and field name in the extra fields.
  3526. * Returns 0 if course was not found.
  3527. *
  3528. * @param string $value Original course code
  3529. * @param string $variable Original field name
  3530. *
  3531. * @return array
  3532. */
  3533. public static function getCourseInfoFromOriginalId($value, $variable)
  3534. {
  3535. $extraFieldValue = new ExtraFieldValue('course');
  3536. $result = $extraFieldValue->get_item_id_from_field_variable_and_field_value(
  3537. $variable,
  3538. $value
  3539. );
  3540. if (!empty($result)) {
  3541. $courseInfo = api_get_course_info_by_id($result['item_id']);
  3542. return $courseInfo;
  3543. }
  3544. return [];
  3545. }
  3546. /**
  3547. * Display code for one specific course a logged in user is subscribed to.
  3548. * Shows a link to the course, what's new icons...
  3549. *
  3550. * $my_course['d'] - course directory
  3551. * $my_course['i'] - course title
  3552. * $my_course['c'] - visual course code
  3553. * $my_course['k'] - system course code
  3554. *
  3555. * @param array Course details
  3556. * @param int Session ID
  3557. * @param string CSS class to apply to course entry
  3558. * @param bool Whether the session is supposedly accessible now
  3559. * (not in the case it has passed and is in invisible/unaccessible mode)
  3560. * @param bool Whether to show the document quick-loader or not
  3561. *
  3562. * @return string The HTML to be printed for the course entry
  3563. *
  3564. * @version 1.0.3
  3565. *
  3566. * @todo refactor into different functions for database calls | logic | display
  3567. * @todo replace single-character $my_course['d'] indices
  3568. * @todo move code for what's new icons to a separate function to clear things up
  3569. * @todo add a parameter user_id so that it is possible to show the
  3570. * courselist of other users (=generalisation).
  3571. * This will prevent having to write a new function for this.
  3572. */
  3573. public static function get_logged_user_course_html(
  3574. $course,
  3575. $session_id = 0,
  3576. $class = 'courses',
  3577. $session_accessible = true,
  3578. $load_dirs = false
  3579. ) {
  3580. $now = date('Y-m-d h:i:s');
  3581. $user_id = api_get_user_id();
  3582. $course_info = api_get_course_info_by_id($course['real_id']);
  3583. $course_visibility = (int) $course_info['visibility'];
  3584. if ($course_visibility === COURSE_VISIBILITY_HIDDEN) {
  3585. return '';
  3586. }
  3587. $userInCourseStatus = self::getUserInCourseStatus(
  3588. $user_id,
  3589. $course_info['real_id']
  3590. );
  3591. $course_info['status'] = empty($session_id) ? $userInCourseStatus : STUDENT;
  3592. $course_info['id_session'] = $session_id;
  3593. $is_coach = api_is_coach($session_id, $course_info['real_id']);
  3594. // Display course entry.
  3595. // Show a hyperlink to the course, unless the course is closed and user is not course admin.
  3596. $session_url = '';
  3597. $params = [];
  3598. $params['icon'] = Display::return_icon(
  3599. 'blackboard_blue.png',
  3600. null,
  3601. [],
  3602. ICON_SIZE_LARGE,
  3603. null,
  3604. true
  3605. );
  3606. $params['real_id'] = $course_info['real_id'];
  3607. // Display the "what's new" icons
  3608. $notifications = '';
  3609. if (
  3610. ($course_visibility != COURSE_VISIBILITY_CLOSED && $course_visibility != COURSE_VISIBILITY_HIDDEN) ||
  3611. !api_get_configuration_value('hide_course_notification')
  3612. ) {
  3613. $notifications .= Display::show_notification($course_info);
  3614. }
  3615. if ($session_accessible) {
  3616. if ($course_visibility != COURSE_VISIBILITY_CLOSED ||
  3617. $userInCourseStatus == COURSEMANAGER
  3618. ) {
  3619. if (empty($course_info['id_session'])) {
  3620. $course_info['id_session'] = 0;
  3621. }
  3622. $sessionCourseAvailable = false;
  3623. $sessionCourseStatus = api_get_session_visibility($session_id, $course_info['real_id']);
  3624. if (in_array(
  3625. $sessionCourseStatus,
  3626. [SESSION_VISIBLE_READ_ONLY, SESSION_VISIBLE, SESSION_AVAILABLE]
  3627. )) {
  3628. $sessionCourseAvailable = true;
  3629. }
  3630. if ($userInCourseStatus === COURSEMANAGER || $sessionCourseAvailable) {
  3631. $session_url = $course_info['course_public_url'].'?id_session='.$course_info['id_session'];
  3632. $session_title = '<a title="'.$course_info['name'].'" href="'.$session_url.'">'.
  3633. $course_info['name'].'</a>'.$notifications;
  3634. } else {
  3635. $session_title = $course_info['name'];
  3636. }
  3637. } else {
  3638. $session_title =
  3639. $course_info['name'].' '.
  3640. Display::tag('span', get_lang('CourseClosed'), ['class' => 'item_closed']);
  3641. }
  3642. } else {
  3643. $session_title = $course_info['name'];
  3644. }
  3645. $thumbnails = null;
  3646. $image = null;
  3647. $showCustomIcon = api_get_setting('course_images_in_courses_list');
  3648. $iconName = basename($course_info['course_image']);
  3649. if ($showCustomIcon === 'true' && $iconName != 'course.png') {
  3650. $thumbnails = $course_info['course_image'];
  3651. $image = $course_info['course_image_large'];
  3652. } else {
  3653. $image = Display::return_icon(
  3654. 'session_default.png',
  3655. null,
  3656. null,
  3657. null,
  3658. null,
  3659. true
  3660. );
  3661. }
  3662. $params['thumbnails'] = $thumbnails;
  3663. $params['image'] = $image;
  3664. $params['link'] = $session_url;
  3665. $params['title'] = $session_title;
  3666. $params['name'] = $course_info['name'];
  3667. $params['edit_actions'] = '';
  3668. $params['document'] = '';
  3669. $params['category'] = $course_info['categoryName'];
  3670. if ($course_visibility != COURSE_VISIBILITY_CLOSED &&
  3671. $course_visibility != COURSE_VISIBILITY_HIDDEN
  3672. ) {
  3673. if (api_is_platform_admin()) {
  3674. $params['edit_actions'] .= api_get_path(WEB_CODE_PATH).'course_info/infocours.php?cidReq='.$course_info['code'];
  3675. if ($load_dirs) {
  3676. $params['document'] .= '<a
  3677. id="document_preview_'.$course_info['real_id'].'_'.$course_info['id_session'].'"
  3678. class="document_preview btn btn-default btn-sm"
  3679. href="javascript:void(0);">'.
  3680. Display::returnFontAwesomeIcon('folder-open').'</a>';
  3681. $params['document'] .= Display::div('', [
  3682. 'id' => 'document_result_'.$course_info['real_id'].'_'.$course_info['id_session'],
  3683. 'class' => 'document_preview_container',
  3684. ]);
  3685. }
  3686. }
  3687. }
  3688. if (api_get_setting('display_teacher_in_courselist') === 'true') {
  3689. $teacher_list = self::getTeachersFromCourse(
  3690. $course_info['real_id'],
  3691. true
  3692. );
  3693. $course_coachs = self::get_coachs_from_course(
  3694. $course_info['id_session'],
  3695. $course_info['real_id']
  3696. );
  3697. $params['teachers'] = $teacher_list;
  3698. if (($course_info['status'] == STUDENT && !empty($course_info['id_session'])) ||
  3699. ($is_coach && $course_info['status'] != COURSEMANAGER)
  3700. ) {
  3701. $params['coaches'] = $course_coachs;
  3702. }
  3703. }
  3704. $special = isset($course['special_course']) ? true : false;
  3705. $params['title'] = $session_title;
  3706. $params['special'] = $special;
  3707. if (api_get_setting('display_coursecode_in_courselist') === 'true') {
  3708. $params['visual_code'] = '('.$course_info['visual_code'].')';
  3709. }
  3710. $params['extra'] = '';
  3711. $html = $params;
  3712. $session_category_id = null;
  3713. if (1) {
  3714. $session = '';
  3715. $active = false;
  3716. if (!empty($course_info['id_session'])) {
  3717. $session = api_get_session_info($course_info['id_session']);
  3718. $sessionCoachName = '';
  3719. if (!empty($session['id_coach'])) {
  3720. $coachInfo = api_get_user_info($session['id_coach']);
  3721. $sessionCoachName = $coachInfo['complete_name'];
  3722. }
  3723. $session_category_id = self::get_session_category_id_by_session_id($course_info['id_session']);
  3724. if (
  3725. $session['access_start_date'] === '0000-00-00 00:00:00' || empty($session['access_start_date']) ||
  3726. $session['access_start_date'] === '0000-00-00'
  3727. ) {
  3728. $session['dates'] = '';
  3729. if (api_get_setting('show_session_coach') === 'true') {
  3730. $session['coach'] = get_lang('GeneralCoach').': '.$sessionCoachName;
  3731. }
  3732. $active = true;
  3733. } else {
  3734. $session['dates'] = ' - '.
  3735. get_lang('From').' '.$session['access_start_date'].' '.
  3736. get_lang('To').' '.$session['access_end_date'];
  3737. if (api_get_setting('show_session_coach') === 'true') {
  3738. $session['coach'] = get_lang('GeneralCoach').': '.$sessionCoachName;
  3739. }
  3740. $date_start = $session['access_start_date'];
  3741. $date_end = $session['access_end_date'];
  3742. $active = !$date_end ? ($date_start <= $now) : ($date_start <= $now && $date_end >= $now);
  3743. }
  3744. }
  3745. $user_course_category = '';
  3746. if (isset($course_info['user_course_cat'])) {
  3747. $user_course_category = $course_info['user_course_cat'];
  3748. }
  3749. $output = [
  3750. $user_course_category,
  3751. $html,
  3752. $course_info['id_session'],
  3753. $session,
  3754. 'active' => $active,
  3755. 'session_category_id' => $session_category_id,
  3756. ];
  3757. if (Skill::isAllowed($user_id, false)) {
  3758. $em = Database::getManager();
  3759. $objUser = api_get_user_entity($user_id);
  3760. /** @var Course $objCourse */
  3761. $objCourse = $em->find('ChamiloCoreBundle:Course', $course['real_id']);
  3762. $objSession = $em->find('ChamiloCoreBundle:Session', $session_id);
  3763. $skill = $em->getRepository('ChamiloCoreBundle:Skill')->getLastByUser($objUser, $objCourse, $objSession);
  3764. $output['skill'] = null;
  3765. if ($skill) {
  3766. $output['skill']['name'] = $skill->getName();
  3767. $output['skill']['icon'] = $skill->getIcon();
  3768. }
  3769. }
  3770. } else {
  3771. $output = [$course_info['user_course_cat'], $html];
  3772. }
  3773. return $output;
  3774. }
  3775. /**
  3776. * @param string $source_course_code
  3777. * @param int $source_session_id
  3778. * @param string $destination_course_code
  3779. * @param int $destination_session_id
  3780. * @param array $params
  3781. *
  3782. * @return bool
  3783. */
  3784. public static function copy_course(
  3785. $source_course_code,
  3786. $source_session_id,
  3787. $destination_course_code,
  3788. $destination_session_id,
  3789. $params = []
  3790. ) {
  3791. $course_info = api_get_course_info($source_course_code);
  3792. if (!empty($course_info)) {
  3793. $cb = new CourseBuilder('', $course_info);
  3794. $course = $cb->build($source_session_id, $source_course_code, true);
  3795. $course_restorer = new CourseRestorer($course);
  3796. $course_restorer->skip_content = $params;
  3797. $course_restorer->restore(
  3798. $destination_course_code,
  3799. $destination_session_id,
  3800. true,
  3801. true
  3802. );
  3803. return true;
  3804. }
  3805. return false;
  3806. }
  3807. /**
  3808. * A simpler version of the copy_course, the function creates an empty course with an autogenerated course code.
  3809. *
  3810. * @param string $new_title new course title
  3811. * @param string source course code
  3812. * @param int source session id
  3813. * @param int destination session id
  3814. * @param array $params
  3815. *
  3816. * @return array
  3817. */
  3818. public static function copy_course_simple(
  3819. $new_title,
  3820. $source_course_code,
  3821. $source_session_id = 0,
  3822. $destination_session_id = 0,
  3823. $params = []
  3824. ) {
  3825. $source_course_info = api_get_course_info($source_course_code);
  3826. if (!empty($source_course_info)) {
  3827. $new_course_code = self::generate_nice_next_course_code($source_course_code);
  3828. if ($new_course_code) {
  3829. $new_course_info = self::create_course(
  3830. $new_title,
  3831. $new_course_code,
  3832. false
  3833. );
  3834. if (!empty($new_course_info['code'])) {
  3835. $result = self::copy_course(
  3836. $source_course_code,
  3837. $source_session_id,
  3838. $new_course_info['code'],
  3839. $destination_session_id,
  3840. $params
  3841. );
  3842. if ($result) {
  3843. return $new_course_info;
  3844. }
  3845. }
  3846. }
  3847. }
  3848. return false;
  3849. }
  3850. /**
  3851. * Creates a new course code based in a given code.
  3852. *
  3853. * @param string wanted code
  3854. * <code> $wanted_code = 'curse' if there are in the DB codes like curse1 curse2 the function will return: course3</code>
  3855. * if the course code doest not exist in the DB the same course code will be returned
  3856. *
  3857. * @return string wanted unused code
  3858. */
  3859. public static function generate_nice_next_course_code($wanted_code)
  3860. {
  3861. $course_code_ok = !self::course_code_exists($wanted_code);
  3862. if (!$course_code_ok) {
  3863. $wanted_code = self::generate_course_code($wanted_code);
  3864. $table = Database::get_main_table(TABLE_MAIN_COURSE);
  3865. $wanted_code = Database::escape_string($wanted_code);
  3866. $sql = "SELECT count(id) as count
  3867. FROM $table
  3868. WHERE code LIKE '$wanted_code%'";
  3869. $result = Database::query($sql);
  3870. if (Database::num_rows($result) > 0) {
  3871. $row = Database::fetch_array($result);
  3872. $count = $row['count'] + 1;
  3873. $wanted_code = $wanted_code.'_'.$count;
  3874. $result = api_get_course_info($wanted_code);
  3875. if (empty($result)) {
  3876. return $wanted_code;
  3877. }
  3878. }
  3879. return false;
  3880. }
  3881. return $wanted_code;
  3882. }
  3883. /**
  3884. * Gets the status of the users agreement in a course course-session.
  3885. *
  3886. * @param int $user_id
  3887. * @param string $course_code
  3888. * @param int $session_id
  3889. *
  3890. * @return bool
  3891. */
  3892. public static function is_user_accepted_legal($user_id, $course_code, $session_id = 0)
  3893. {
  3894. $user_id = intval($user_id);
  3895. $course_code = Database::escape_string($course_code);
  3896. $session_id = intval($session_id);
  3897. $courseInfo = api_get_course_info($course_code);
  3898. $courseId = $courseInfo['real_id'];
  3899. // Course legal
  3900. $enabled = api_get_plugin_setting('courselegal', 'tool_enable');
  3901. if ($enabled == 'true') {
  3902. require_once api_get_path(SYS_PLUGIN_PATH).'courselegal/config.php';
  3903. $plugin = CourseLegalPlugin::create();
  3904. return $plugin->isUserAcceptedLegal($user_id, $course_code, $session_id);
  3905. }
  3906. if (empty($session_id)) {
  3907. $table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  3908. $sql = "SELECT legal_agreement FROM $table
  3909. WHERE user_id = $user_id AND c_id = $courseId ";
  3910. $result = Database::query($sql);
  3911. if (Database::num_rows($result) > 0) {
  3912. $result = Database::fetch_array($result);
  3913. if ($result['legal_agreement'] == 1) {
  3914. return true;
  3915. }
  3916. }
  3917. return false;
  3918. } else {
  3919. $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3920. $sql = "SELECT legal_agreement FROM $table
  3921. WHERE user_id = $user_id AND c_id = $courseId AND session_id = $session_id";
  3922. $result = Database::query($sql);
  3923. if (Database::num_rows($result) > 0) {
  3924. $result = Database::fetch_array($result);
  3925. if ($result['legal_agreement'] == 1) {
  3926. return true;
  3927. }
  3928. }
  3929. return false;
  3930. }
  3931. }
  3932. /**
  3933. * Saves the user-course legal agreement.
  3934. *
  3935. * @param int user id
  3936. * @param string course code
  3937. * @param int session id
  3938. *
  3939. * @return mixed
  3940. */
  3941. public static function save_user_legal($user_id, $course_code, $session_id = null)
  3942. {
  3943. // Course plugin legal
  3944. $enabled = api_get_plugin_setting('courselegal', 'tool_enable');
  3945. if ($enabled == 'true') {
  3946. require_once api_get_path(SYS_PLUGIN_PATH).'courselegal/config.php';
  3947. $plugin = CourseLegalPlugin::create();
  3948. return $plugin->saveUserLegal($user_id, $course_code, $session_id);
  3949. }
  3950. $user_id = intval($user_id);
  3951. $course_code = Database::escape_string($course_code);
  3952. $session_id = intval($session_id);
  3953. $courseInfo = api_get_course_info($course_code);
  3954. $courseId = $courseInfo['real_id'];
  3955. if (empty($session_id)) {
  3956. $table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  3957. $sql = "UPDATE $table SET legal_agreement = '1'
  3958. WHERE user_id = $user_id AND c_id = $courseId ";
  3959. Database::query($sql);
  3960. } else {
  3961. $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3962. $sql = "UPDATE $table SET legal_agreement = '1'
  3963. WHERE user_id = $user_id AND c_id = $courseId AND session_id = $session_id";
  3964. Database::query($sql);
  3965. }
  3966. }
  3967. /**
  3968. * @param int $user_id
  3969. * @param int $course_id
  3970. * @param int $session_id
  3971. * @param int $url_id
  3972. *
  3973. * @return bool
  3974. */
  3975. public static function get_user_course_vote($user_id, $course_id, $session_id = 0, $url_id = 0)
  3976. {
  3977. $table_user_course_vote = Database::get_main_table(TABLE_MAIN_USER_REL_COURSE_VOTE);
  3978. $session_id = !isset($session_id) ? api_get_session_id() : intval($session_id);
  3979. $url_id = empty($url_id) ? api_get_current_access_url_id() : intval($url_id);
  3980. $user_id = intval($user_id);
  3981. if (empty($user_id)) {
  3982. return false;
  3983. }
  3984. $params = [
  3985. 'user_id' => $user_id,
  3986. 'c_id' => $course_id,
  3987. 'session_id' => $session_id,
  3988. 'url_id' => $url_id,
  3989. ];
  3990. $result = Database::select(
  3991. 'vote',
  3992. $table_user_course_vote,
  3993. [
  3994. 'where' => [
  3995. 'user_id = ? AND c_id = ? AND session_id = ? AND url_id = ?' => $params,
  3996. ],
  3997. ],
  3998. 'first'
  3999. );
  4000. if (!empty($result)) {
  4001. return $result['vote'];
  4002. }
  4003. return false;
  4004. }
  4005. /**
  4006. * @param int $course_id
  4007. * @param int $session_id
  4008. * @param int $url_id
  4009. *
  4010. * @return array
  4011. */
  4012. public static function get_course_ranking(
  4013. $course_id,
  4014. $session_id = 0,
  4015. $url_id = 0
  4016. ) {
  4017. $table_course_ranking = Database::get_main_table(TABLE_STATISTIC_TRACK_COURSE_RANKING);
  4018. $session_id = empty($session_id) ? api_get_session_id() : intval($session_id);
  4019. $url_id = empty($url_id) ? api_get_current_access_url_id() : intval($url_id);
  4020. $now = api_get_utc_datetime();
  4021. $params = [
  4022. 'c_id' => $course_id,
  4023. 'session_id' => $session_id,
  4024. 'url_id' => $url_id,
  4025. 'creation_date' => $now,
  4026. ];
  4027. $result = Database::select(
  4028. 'c_id, accesses, total_score, users',
  4029. $table_course_ranking,
  4030. ['where' => ['c_id = ? AND session_id = ? AND url_id = ?' => $params]],
  4031. 'first'
  4032. );
  4033. $point_average_in_percentage = 0;
  4034. $point_average_in_star = 0;
  4035. $users_who_voted = 0;
  4036. if (!empty($result['users'])) {
  4037. $users_who_voted = $result['users'];
  4038. $point_average_in_percentage = round($result['total_score'] / $result['users'] * 100 / 5, 2);
  4039. $point_average_in_star = round($result['total_score'] / $result['users'], 1);
  4040. }
  4041. $result['user_vote'] = false;
  4042. if (!api_is_anonymous()) {
  4043. $result['user_vote'] = self::get_user_course_vote(api_get_user_id(), $course_id, $session_id, $url_id);
  4044. }
  4045. $result['point_average'] = $point_average_in_percentage;
  4046. $result['point_average_star'] = $point_average_in_star;
  4047. $result['users_who_voted'] = $users_who_voted;
  4048. return $result;
  4049. }
  4050. /**
  4051. * Updates the course ranking.
  4052. *
  4053. * @param int course id
  4054. * @param int $session_id
  4055. * @param int url id
  4056. * @param $points_to_add
  4057. * @param bool $add_access
  4058. * @param bool $add_user
  4059. *
  4060. * @return array
  4061. */
  4062. public static function update_course_ranking(
  4063. $course_id = 0,
  4064. $session_id = 0,
  4065. $url_id = 0,
  4066. $points_to_add = null,
  4067. $add_access = true,
  4068. $add_user = true
  4069. ) {
  4070. // Course catalog stats modifications see #4191
  4071. $table_course_ranking = Database::get_main_table(TABLE_STATISTIC_TRACK_COURSE_RANKING);
  4072. $now = api_get_utc_datetime();
  4073. $course_id = empty($course_id) ? api_get_course_int_id() : intval($course_id);
  4074. $session_id = empty($session_id) ? api_get_session_id() : intval($session_id);
  4075. $url_id = empty($url_id) ? api_get_current_access_url_id() : intval($url_id);
  4076. $params = [
  4077. 'c_id' => $course_id,
  4078. 'session_id' => $session_id,
  4079. 'url_id' => $url_id,
  4080. 'creation_date' => $now,
  4081. 'total_score' => 0,
  4082. 'users' => 0,
  4083. ];
  4084. $result = Database::select(
  4085. 'id, accesses, total_score, users',
  4086. $table_course_ranking,
  4087. ['where' => ['c_id = ? AND session_id = ? AND url_id = ?' => $params]],
  4088. 'first'
  4089. );
  4090. // Problem here every time we load the courses/XXXX/index.php course home page we update the access
  4091. if (empty($result)) {
  4092. if ($add_access) {
  4093. $params['accesses'] = 1;
  4094. }
  4095. //The votes and users are empty
  4096. if (isset($points_to_add) && !empty($points_to_add)) {
  4097. $params['total_score'] = intval($points_to_add);
  4098. }
  4099. if ($add_user) {
  4100. $params['users'] = 1;
  4101. }
  4102. $result = Database::insert($table_course_ranking, $params);
  4103. } else {
  4104. $my_params = [];
  4105. if ($add_access) {
  4106. $my_params['accesses'] = intval($result['accesses']) + 1;
  4107. }
  4108. if (isset($points_to_add) && !empty($points_to_add)) {
  4109. $my_params['total_score'] = $result['total_score'] + $points_to_add;
  4110. }
  4111. if ($add_user) {
  4112. $my_params['users'] = $result['users'] + 1;
  4113. }
  4114. if (!empty($my_params)) {
  4115. $result = Database::update(
  4116. $table_course_ranking,
  4117. $my_params,
  4118. ['c_id = ? AND session_id = ? AND url_id = ?' => $params]
  4119. );
  4120. }
  4121. }
  4122. return $result;
  4123. }
  4124. /**
  4125. * Add user vote to a course.
  4126. *
  4127. * @param int user id
  4128. * @param int vote [1..5]
  4129. * @param int course id
  4130. * @param int session id
  4131. * @param int url id (access_url_id)
  4132. *
  4133. * @return false|string 'added', 'updated' or 'nothing'
  4134. */
  4135. public static function add_course_vote(
  4136. $user_id,
  4137. $vote,
  4138. $course_id,
  4139. $session_id = 0,
  4140. $url_id = 0
  4141. ) {
  4142. $table_user_course_vote = Database::get_main_table(TABLE_MAIN_USER_REL_COURSE_VOTE);
  4143. $course_id = empty($course_id) ? api_get_course_int_id() : intval($course_id);
  4144. if (empty($course_id) || empty($user_id)) {
  4145. return false;
  4146. }
  4147. if (!in_array($vote, [1, 2, 3, 4, 5])) {
  4148. return false;
  4149. }
  4150. $session_id = empty($session_id) ? api_get_session_id() : intval($session_id);
  4151. $url_id = empty($url_id) ? api_get_current_access_url_id() : intval($url_id);
  4152. $vote = intval($vote);
  4153. $params = [
  4154. 'user_id' => intval($user_id),
  4155. 'c_id' => $course_id,
  4156. 'session_id' => $session_id,
  4157. 'url_id' => $url_id,
  4158. 'vote' => $vote,
  4159. ];
  4160. $action_done = 'nothing';
  4161. $result = Database::select(
  4162. 'id, vote',
  4163. $table_user_course_vote,
  4164. ['where' => ['user_id = ? AND c_id = ? AND session_id = ? AND url_id = ?' => $params]],
  4165. 'first'
  4166. );
  4167. if (empty($result)) {
  4168. Database::insert($table_user_course_vote, $params);
  4169. $points_to_add = $vote;
  4170. $add_user = true;
  4171. $action_done = 'added';
  4172. } else {
  4173. $my_params = ['vote' => $vote];
  4174. $points_to_add = $vote - $result['vote'];
  4175. $add_user = false;
  4176. Database::update(
  4177. $table_user_course_vote,
  4178. $my_params,
  4179. ['user_id = ? AND c_id = ? AND session_id = ? AND url_id = ?' => $params]
  4180. );
  4181. $action_done = 'updated';
  4182. }
  4183. // Current points
  4184. if (!empty($points_to_add)) {
  4185. self::update_course_ranking(
  4186. $course_id,
  4187. $session_id,
  4188. $url_id,
  4189. $points_to_add,
  4190. false,
  4191. $add_user
  4192. );
  4193. }
  4194. return $action_done;
  4195. }
  4196. /**
  4197. * Remove course ranking + user votes.
  4198. *
  4199. * @param int $course_id
  4200. * @param int $session_id
  4201. * @param int $url_id
  4202. */
  4203. public static function remove_course_ranking($course_id, $session_id, $url_id = null)
  4204. {
  4205. $table_course_ranking = Database::get_main_table(TABLE_STATISTIC_TRACK_COURSE_RANKING);
  4206. $table_user_course_vote = Database::get_main_table(TABLE_MAIN_USER_REL_COURSE_VOTE);
  4207. if (!empty($course_id) && isset($session_id)) {
  4208. $url_id = empty($url_id) ? api_get_current_access_url_id() : intval($url_id);
  4209. $params = [
  4210. 'c_id' => $course_id,
  4211. 'session_id' => $session_id,
  4212. 'url_id' => $url_id,
  4213. ];
  4214. Database::delete($table_course_ranking, ['c_id = ? AND session_id = ? AND url_id = ?' => $params]);
  4215. Database::delete($table_user_course_vote, ['c_id = ? AND session_id = ? AND url_id = ?' => $params]);
  4216. }
  4217. }
  4218. /**
  4219. * Returns an array with the hottest courses.
  4220. *
  4221. * @param int $days number of days
  4222. * @param int $limit number of hottest courses
  4223. *
  4224. * @return array
  4225. */
  4226. public static function return_hot_courses($days = 30, $limit = 6)
  4227. {
  4228. if (api_is_invitee()) {
  4229. return [];
  4230. }
  4231. $limit = (int) $limit;
  4232. $userId = api_get_user_id();
  4233. // Getting my courses
  4234. $my_course_list = self::get_courses_list_by_user_id($userId);
  4235. $codeList = [];
  4236. foreach ($my_course_list as $course) {
  4237. $codeList[$course['real_id']] = $course['real_id'];
  4238. }
  4239. if (api_is_drh()) {
  4240. $courses = self::get_courses_followed_by_drh($userId);
  4241. foreach ($courses as $course) {
  4242. $codeList[$course['real_id']] = $course['real_id'];
  4243. }
  4244. }
  4245. $table_course_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  4246. $table_course = Database::get_main_table(TABLE_MAIN_COURSE);
  4247. $table_course_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  4248. $urlId = api_get_current_access_url_id();
  4249. //$table_course_access table uses the now() and interval ...
  4250. $now = api_get_utc_datetime();
  4251. $sql = "SELECT COUNT(course_access_id) course_count, a.c_id, visibility
  4252. FROM $table_course c
  4253. INNER JOIN $table_course_access a
  4254. ON (c.id = a.c_id)
  4255. INNER JOIN $table_course_url u
  4256. ON u.c_id = c.id
  4257. WHERE
  4258. u.access_url_id = $urlId AND
  4259. login_course_date <= '$now' AND
  4260. login_course_date > DATE_SUB('$now', INTERVAL $days DAY) AND
  4261. visibility <> ".COURSE_VISIBILITY_CLOSED." AND
  4262. visibility <> ".COURSE_VISIBILITY_HIDDEN."
  4263. GROUP BY a.c_id
  4264. ORDER BY course_count DESC
  4265. LIMIT $limit
  4266. ";
  4267. $result = Database::query($sql);
  4268. $courses = [];
  4269. if (Database::num_rows($result)) {
  4270. $courses = Database::store_result($result, 'ASSOC');
  4271. $courses = self::processHotCourseItem($courses, $codeList);
  4272. }
  4273. return $courses;
  4274. }
  4275. /**
  4276. * @param array $courses
  4277. * @param array $codeList
  4278. *
  4279. * @return mixed
  4280. */
  4281. public static function processHotCourseItem($courses, $codeList = [])
  4282. {
  4283. $hotCourses = [];
  4284. $ajax_url = api_get_path(WEB_AJAX_PATH).'course.ajax.php?a=add_course_vote';
  4285. $stok = Security::get_existing_token();
  4286. $user_id = api_get_user_id();
  4287. foreach ($courses as $courseId) {
  4288. $course_info = api_get_course_info_by_id($courseId['c_id']);
  4289. $courseCode = $course_info['code'];
  4290. $categoryCode = !empty($course_info['categoryCode']) ? $course_info['categoryCode'] : "";
  4291. $my_course = $course_info;
  4292. $my_course['go_to_course_button'] = '';
  4293. $my_course['register_button'] = '';
  4294. $access_link = self::get_access_link_by_user(
  4295. api_get_user_id(),
  4296. $course_info,
  4297. $codeList
  4298. );
  4299. $userRegisteredInCourse = self::is_user_subscribed_in_course($user_id, $course_info['code']);
  4300. $userRegisteredInCourseAsTeacher = self::is_course_teacher($user_id, $course_info['code']);
  4301. $userRegistered = $userRegisteredInCourse && $userRegisteredInCourseAsTeacher;
  4302. $my_course['is_course_student'] = $userRegisteredInCourse;
  4303. $my_course['is_course_teacher'] = $userRegisteredInCourseAsTeacher;
  4304. $my_course['is_registered'] = $userRegistered;
  4305. $my_course['title_cut'] = cut($course_info['title'], 45);
  4306. // Course visibility
  4307. if ($access_link && in_array('register', $access_link)) {
  4308. $my_course['register_button'] = Display::url(
  4309. get_lang('Subscribe').' '.
  4310. Display::returnFontAwesomeIcon('sign-in'),
  4311. api_get_path(WEB_COURSE_PATH).$course_info['path'].
  4312. '/index.php?action=subscribe&sec_token='.$stok,
  4313. [
  4314. 'class' => 'btn btn-success btn-sm',
  4315. 'title' => get_lang('Subscribe'),
  4316. 'aria-label' => get_lang('Subscribe'),
  4317. ]
  4318. );
  4319. }
  4320. if ($access_link && in_array('enter', $access_link) ||
  4321. $course_info['visibility'] == COURSE_VISIBILITY_OPEN_WORLD
  4322. ) {
  4323. $my_course['go_to_course_button'] = Display::url(
  4324. get_lang('GoToCourse').' '.
  4325. Display::returnFontAwesomeIcon('share'),
  4326. api_get_path(WEB_COURSE_PATH).$course_info['path'].'/index.php',
  4327. [
  4328. 'class' => 'btn btn-default btn-sm',
  4329. 'title' => get_lang('GoToCourse'),
  4330. 'aria-label' => get_lang('GoToCourse'),
  4331. ]
  4332. );
  4333. }
  4334. if ($access_link && in_array('unsubscribe', $access_link)) {
  4335. $my_course['unsubscribe_button'] = Display::url(
  4336. get_lang('Unreg').' '.
  4337. Display::returnFontAwesomeIcon('sign-out'),
  4338. api_get_path(WEB_CODE_PATH).'auth/courses.php?action=unsubscribe&unsubscribe='.$courseCode
  4339. .'&sec_token='.$stok.'&category_code='.$categoryCode,
  4340. [
  4341. 'class' => 'btn btn-danger btn-sm',
  4342. 'title' => get_lang('Unreg'),
  4343. 'aria-label' => get_lang('Unreg'),
  4344. ]
  4345. );
  4346. }
  4347. // start buycourse validation
  4348. // display the course price and buy button if the buycourses plugin is enabled and this course is configured
  4349. $plugin = BuyCoursesPlugin::create();
  4350. $isThisCourseInSale = $plugin->buyCoursesForGridCatalogValidator(
  4351. $course_info['real_id'],
  4352. BuyCoursesPlugin::PRODUCT_TYPE_COURSE
  4353. );
  4354. if ($isThisCourseInSale) {
  4355. // set the price label
  4356. $my_course['price'] = $isThisCourseInSale['html'];
  4357. // set the Buy button instead register.
  4358. if ($isThisCourseInSale['verificator'] && !empty($my_course['register_button'])) {
  4359. $my_course['register_button'] = $plugin->returnBuyCourseButton(
  4360. $course_info['real_id'],
  4361. BuyCoursesPlugin::PRODUCT_TYPE_COURSE
  4362. );
  4363. }
  4364. }
  4365. // end buycourse validation
  4366. // Description
  4367. $my_course['description_button'] = self::returnDescriptionButton($course_info);
  4368. $my_course['teachers'] = self::getTeachersFromCourse($course_info['real_id'], true);
  4369. $point_info = self::get_course_ranking($course_info['real_id'], 0);
  4370. $my_course['rating_html'] = '';
  4371. if (api_get_configuration_value('hide_course_rating') === false) {
  4372. $my_course['rating_html'] = Display::return_rating_system(
  4373. 'star_'.$course_info['real_id'],
  4374. $ajax_url.'&course_id='.$course_info['real_id'],
  4375. $point_info
  4376. );
  4377. }
  4378. $hotCourses[] = $my_course;
  4379. }
  4380. return $hotCourses;
  4381. }
  4382. /**
  4383. * Get courses count.
  4384. *
  4385. * @param int $access_url_id Access URL ID (optional)
  4386. * @param int $visibility
  4387. *
  4388. * @return int Number of courses
  4389. */
  4390. public static function count_courses($access_url_id = null, $visibility = null)
  4391. {
  4392. $table_course = Database::get_main_table(TABLE_MAIN_COURSE);
  4393. $table_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  4394. $sql = "SELECT count(c.id) FROM $table_course c";
  4395. if (!empty($access_url_id) && $access_url_id == intval($access_url_id)) {
  4396. $sql .= ", $table_course_rel_access_url u
  4397. WHERE c.id = u.c_id AND u.access_url_id = $access_url_id";
  4398. if (!empty($visibility)) {
  4399. $visibility = intval($visibility);
  4400. $sql .= " AND visibility = $visibility ";
  4401. }
  4402. } else {
  4403. if (!empty($visibility)) {
  4404. $visibility = intval($visibility);
  4405. $sql .= " WHERE visibility = $visibility ";
  4406. }
  4407. }
  4408. $res = Database::query($sql);
  4409. $row = Database::fetch_row($res);
  4410. return $row[0];
  4411. }
  4412. /**
  4413. * Get active courses count.
  4414. * Active = all courses except the ones with hidden visibility.
  4415. *
  4416. * @param int $urlId Access URL ID (optional)
  4417. *
  4418. * @return int Number of courses
  4419. */
  4420. public static function countActiveCourses($urlId = null)
  4421. {
  4422. $table_course = Database::get_main_table(TABLE_MAIN_COURSE);
  4423. $table_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  4424. $sql = "SELECT count(id) FROM $table_course c";
  4425. if (!empty($urlId) && $urlId == intval($urlId)) {
  4426. $sql .= ", $table_course_rel_access_url u
  4427. WHERE
  4428. c.id = u.c_id AND
  4429. u.access_url_id = $urlId AND
  4430. visibility <> ".COURSE_VISIBILITY_HIDDEN;
  4431. } else {
  4432. $sql .= " WHERE visibility <> ".COURSE_VISIBILITY_HIDDEN;
  4433. }
  4434. $res = Database::query($sql);
  4435. $row = Database::fetch_row($res);
  4436. return $row[0];
  4437. }
  4438. /**
  4439. * Returns the SQL conditions to filter course only visible by the user in the catalogue.
  4440. *
  4441. * @param string $courseTableAlias Alias of the course table
  4442. * @param bool $hideClosed Whether to hide closed and hidden courses
  4443. *
  4444. * @return string SQL conditions
  4445. */
  4446. public static function getCourseVisibilitySQLCondition(
  4447. $courseTableAlias,
  4448. $hideClosed = false
  4449. ) {
  4450. $visibilityCondition = '';
  4451. $hidePrivate = api_get_setting('course_catalog_hide_private');
  4452. if ($hidePrivate === 'true') {
  4453. $visibilityCondition .= " AND $courseTableAlias.visibility <> ".COURSE_VISIBILITY_REGISTERED;
  4454. }
  4455. if ($hideClosed) {
  4456. $visibilityCondition .= " AND $courseTableAlias.visibility NOT IN (".COURSE_VISIBILITY_CLOSED.','.COURSE_VISIBILITY_HIDDEN.')';
  4457. }
  4458. // Check if course have users allowed to see it in the catalogue, then show only if current user is allowed to see it
  4459. $currentUserId = api_get_user_id();
  4460. $restrictedCourses = self::getCatalogueCourseList(true);
  4461. $allowedCoursesToCurrentUser = self::getCatalogueCourseList(true, $currentUserId);
  4462. if (!empty($restrictedCourses)) {
  4463. $visibilityCondition .= ' AND ('.$courseTableAlias.'.code NOT IN ("'.implode('","', $restrictedCourses).'")';
  4464. $visibilityCondition .= ' OR '.$courseTableAlias.'.code IN ("'.implode('","', $allowedCoursesToCurrentUser).'"))';
  4465. }
  4466. // Check if course have users denied to see it in the catalogue, then show only if current user is not denied to see it
  4467. $restrictedCourses = self::getCatalogueCourseList(false);
  4468. $notAllowedCoursesToCurrentUser = self::getCatalogueCourseList(false, $currentUserId);
  4469. if (!empty($restrictedCourses)) {
  4470. $visibilityCondition .= ' AND ('.$courseTableAlias.'.code NOT IN ("'.implode('","', $restrictedCourses).'")';
  4471. $visibilityCondition .= ' OR '.$courseTableAlias.'.code NOT IN ("'.implode('","', $notAllowedCoursesToCurrentUser).'"))';
  4472. }
  4473. return $visibilityCondition;
  4474. }
  4475. /**
  4476. * Return a link to go to the course, validating the visibility of the
  4477. * course and the user status.
  4478. *
  4479. * @param int $uid User ID
  4480. * @param array Course details array
  4481. * @param array List of courses to which the user is subscribed (if not provided, will be generated)
  4482. *
  4483. * @return mixed 'enter' for a link to go to the course or 'register' for a link to subscribe, or false if no access
  4484. */
  4485. public static function get_access_link_by_user($uid, $course, $user_courses = [])
  4486. {
  4487. if (empty($uid) || empty($course)) {
  4488. return false;
  4489. }
  4490. if (empty($user_courses)) {
  4491. // get the array of courses to which the user is subscribed
  4492. $user_courses = self::get_courses_list_by_user_id($uid);
  4493. foreach ($user_courses as $k => $v) {
  4494. $user_courses[$k] = $v['real_id'];
  4495. }
  4496. }
  4497. if (!isset($course['real_id']) && empty($course['real_id'])) {
  4498. $course = api_get_course_info($course['code']);
  4499. }
  4500. if ($course['visibility'] == COURSE_VISIBILITY_HIDDEN) {
  4501. return [];
  4502. }
  4503. $is_admin = api_is_platform_admin_by_id($uid);
  4504. $options = [];
  4505. // Register button
  4506. if (!api_is_anonymous($uid) &&
  4507. (
  4508. ($course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD || $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM)
  4509. //$course['visibility'] == COURSE_VISIBILITY_REGISTERED && $course['subscribe'] == SUBSCRIBE_ALLOWED
  4510. ) &&
  4511. $course['subscribe'] == SUBSCRIBE_ALLOWED &&
  4512. (!in_array($course['real_id'], $user_courses) || empty($user_courses))
  4513. ) {
  4514. $options[] = 'register';
  4515. }
  4516. // Go To Course button (only if admin, if course public or if student already subscribed)
  4517. if ($is_admin ||
  4518. $course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD && empty($course['registration_code']) ||
  4519. (api_user_is_login($uid) && $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM && empty($course['registration_code'])) ||
  4520. (in_array($course['real_id'], $user_courses) && $course['visibility'] != COURSE_VISIBILITY_CLOSED)
  4521. ) {
  4522. $options[] = 'enter';
  4523. }
  4524. if ($is_admin ||
  4525. $course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD && empty($course['registration_code']) ||
  4526. (api_user_is_login($uid) && $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM && empty($course['registration_code'])) ||
  4527. (in_array($course['real_id'], $user_courses) && $course['visibility'] != COURSE_VISIBILITY_CLOSED)
  4528. ) {
  4529. $options[] = 'enter';
  4530. }
  4531. if ($course['visibility'] != COURSE_VISIBILITY_HIDDEN &&
  4532. empty($course['registration_code']) &&
  4533. $course['unsubscribe'] == UNSUBSCRIBE_ALLOWED &&
  4534. api_user_is_login($uid) &&
  4535. in_array($course['real_id'], $user_courses)
  4536. ) {
  4537. $options[] = 'unsubscribe';
  4538. }
  4539. return $options;
  4540. }
  4541. /**
  4542. * @param array $courseInfo
  4543. * @param array $teachers
  4544. * @param bool $deleteTeachersNotInList
  4545. * @param bool $editTeacherInSessions
  4546. * @param bool $deleteSessionTeacherNotInList
  4547. * @param array $teacherBackup
  4548. * @param Monolog\Logger $logger
  4549. *
  4550. * @return false|null
  4551. */
  4552. public static function updateTeachers(
  4553. $courseInfo,
  4554. $teachers,
  4555. $deleteTeachersNotInList = true,
  4556. $editTeacherInSessions = false,
  4557. $deleteSessionTeacherNotInList = false,
  4558. $teacherBackup = [],
  4559. $logger = null
  4560. ) {
  4561. if (!is_array($teachers)) {
  4562. $teachers = [$teachers];
  4563. }
  4564. if (empty($courseInfo) || !isset($courseInfo['real_id'])) {
  4565. return false;
  4566. }
  4567. $teachers = array_filter($teachers);
  4568. $courseId = $courseInfo['real_id'];
  4569. $course_code = $courseInfo['code'];
  4570. $course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  4571. $alreadyAddedTeachers = self::get_teacher_list_from_course_code($course_code);
  4572. if ($deleteTeachersNotInList) {
  4573. // Delete only teacher relations that doesn't match the selected teachers
  4574. $cond = null;
  4575. if (count($teachers) > 0) {
  4576. foreach ($teachers as $key) {
  4577. $key = Database::escape_string($key);
  4578. $cond .= " AND user_id <> '".$key."'";
  4579. }
  4580. }
  4581. // Recover user categories
  4582. $sql = "SELECT * FROM $course_user_table
  4583. WHERE c_id = $courseId AND status = 1 AND relation_type = 0 ".$cond;
  4584. $result = Database::query($sql);
  4585. if (Database::num_rows($result)) {
  4586. $teachersToDelete = Database::store_result($result, 'ASSOC');
  4587. foreach ($teachersToDelete as $data) {
  4588. $userId = $data['user_id'];
  4589. $teacherBackup[$userId][$course_code] = $data;
  4590. }
  4591. }
  4592. $sql = "DELETE FROM $course_user_table
  4593. WHERE c_id = $courseId AND status = 1 AND relation_type = 0 ".$cond;
  4594. Database::query($sql);
  4595. }
  4596. if (count($teachers) > 0) {
  4597. foreach ($teachers as $userId) {
  4598. $userId = intval($userId);
  4599. // We check if the teacher is already subscribed in this course
  4600. $sql = "SELECT 1 FROM $course_user_table
  4601. WHERE user_id = $userId AND c_id = $courseId";
  4602. $result = Database::query($sql);
  4603. if (Database::num_rows($result)) {
  4604. $sql = "UPDATE $course_user_table
  4605. SET status = 1
  4606. WHERE c_id = $courseId AND user_id = $userId ";
  4607. } else {
  4608. $userCourseCategory = '0';
  4609. if (isset($teacherBackup[$userId]) &&
  4610. isset($teacherBackup[$userId][$course_code])
  4611. ) {
  4612. $courseUserData = $teacherBackup[$userId][$course_code];
  4613. $userCourseCategory = $courseUserData['user_course_cat'];
  4614. if ($logger) {
  4615. $logger->addInfo("Recovering user_course_cat: $userCourseCategory");
  4616. }
  4617. }
  4618. $sql = "INSERT INTO $course_user_table SET
  4619. c_id = $courseId,
  4620. user_id = $userId,
  4621. status = 1,
  4622. is_tutor = 0,
  4623. sort = 0,
  4624. relation_type = 0,
  4625. user_course_cat = $userCourseCategory
  4626. ";
  4627. }
  4628. Database::query($sql);
  4629. }
  4630. }
  4631. if ($editTeacherInSessions) {
  4632. $sessions = SessionManager::get_session_by_course($courseId);
  4633. if (!empty($sessions)) {
  4634. if ($logger) {
  4635. $logger->addInfo("Edit teachers in sessions");
  4636. }
  4637. foreach ($sessions as $session) {
  4638. $sessionId = $session['id'];
  4639. // Remove old and add new
  4640. if ($deleteSessionTeacherNotInList) {
  4641. foreach ($teachers as $userId) {
  4642. if ($logger) {
  4643. $logger->addInfo("Set coach #$userId in session #$sessionId of course #$courseId ");
  4644. }
  4645. SessionManager::set_coach_to_course_session(
  4646. $userId,
  4647. $sessionId,
  4648. $courseId
  4649. );
  4650. }
  4651. $teachersToDelete = [];
  4652. if (!empty($alreadyAddedTeachers)) {
  4653. $teachersToDelete = array_diff(array_keys($alreadyAddedTeachers), $teachers);
  4654. }
  4655. if (!empty($teachersToDelete)) {
  4656. foreach ($teachersToDelete as $userId) {
  4657. if ($logger) {
  4658. $logger->addInfo("Delete coach #$userId in session #$sessionId of course #$courseId ");
  4659. }
  4660. SessionManager::set_coach_to_course_session(
  4661. $userId,
  4662. $sessionId,
  4663. $courseId,
  4664. true
  4665. );
  4666. }
  4667. }
  4668. } else {
  4669. // Add new teachers only
  4670. foreach ($teachers as $userId) {
  4671. if ($logger) {
  4672. $logger->addInfo("Add coach #$userId in session #$sessionId of course #$courseId ");
  4673. }
  4674. SessionManager::set_coach_to_course_session(
  4675. $userId,
  4676. $sessionId,
  4677. $courseId
  4678. );
  4679. }
  4680. }
  4681. }
  4682. }
  4683. }
  4684. }
  4685. /**
  4686. * Course available settings variables see c_course_setting table.
  4687. *
  4688. * @param AppPlugin $appPlugin
  4689. *
  4690. * @return array
  4691. */
  4692. public static function getCourseSettingVariables(AppPlugin $appPlugin)
  4693. {
  4694. $pluginCourseSettings = $appPlugin->getAllPluginCourseSettings();
  4695. $courseSettings = [
  4696. // Get allow_learning_path_theme from table
  4697. 'allow_learning_path_theme',
  4698. // Get allow_open_chat_window from table
  4699. 'allow_open_chat_window',
  4700. 'allow_public_certificates',
  4701. // Get allow_user_edit_agenda from table
  4702. 'allow_user_edit_agenda',
  4703. // Get allow_user_edit_announcement from table
  4704. 'allow_user_edit_announcement',
  4705. // Get allow_user_image_forum from table
  4706. 'allow_user_image_forum',
  4707. //Get allow show user list
  4708. 'allow_user_view_user_list',
  4709. // Get course_theme from table
  4710. 'course_theme',
  4711. //Get allow show user list
  4712. 'display_info_advance_inside_homecourse',
  4713. 'documents_default_visibility',
  4714. // Get send_mail_setting (work)from table
  4715. 'email_alert_manager_on_new_doc',
  4716. // Get send_mail_setting (work)from table
  4717. 'email_alert_manager_on_new_quiz',
  4718. // Get send_mail_setting (dropbox) from table
  4719. 'email_alert_on_new_doc_dropbox',
  4720. 'email_alert_students_on_new_homework',
  4721. // Get send_mail_setting (auth)from table
  4722. 'email_alert_to_teacher_on_new_user_in_course',
  4723. 'enable_lp_auto_launch',
  4724. 'enable_exercise_auto_launch',
  4725. 'enable_document_auto_launch',
  4726. 'pdf_export_watermark_text',
  4727. 'show_system_folders',
  4728. 'exercise_invisible_in_session',
  4729. 'enable_forum_auto_launch',
  4730. 'show_course_in_user_language',
  4731. 'email_to_teachers_on_new_work_feedback',
  4732. 'student_delete_own_publication',
  4733. 'hide_forum_notifications',
  4734. 'quiz_question_limit_per_day',
  4735. 'subscribe_users_to_forum_notifications',
  4736. ];
  4737. $courseModels = ExerciseLib::getScoreModels();
  4738. if (!empty($courseModels)) {
  4739. $courseSettings[] = 'score_model_id';
  4740. }
  4741. $allowLPReturnLink = api_get_setting('allow_lp_return_link');
  4742. if ($allowLPReturnLink === 'true') {
  4743. $courseSettings[] = 'lp_return_link';
  4744. }
  4745. if (!empty($pluginCourseSettings)) {
  4746. $courseSettings = array_merge(
  4747. $courseSettings,
  4748. $pluginCourseSettings
  4749. );
  4750. }
  4751. return $courseSettings;
  4752. }
  4753. /**
  4754. * @param AppPlugin $appPlugin
  4755. * @param string $variable
  4756. * @param string|array $value
  4757. * @param int $courseId
  4758. *
  4759. * @return bool
  4760. */
  4761. public static function saveCourseConfigurationSetting(AppPlugin $appPlugin, $variable, $value, $courseId)
  4762. {
  4763. $settingList = self::getCourseSettingVariables($appPlugin);
  4764. if (!in_array($variable, $settingList)) {
  4765. return false;
  4766. }
  4767. $courseSettingTable = Database::get_course_table(TABLE_COURSE_SETTING);
  4768. if (is_array($value)) {
  4769. $value = implode(',', $value);
  4770. }
  4771. if (self::hasCourseSetting($variable, $courseId)) {
  4772. // Update
  4773. Database::update(
  4774. $courseSettingTable,
  4775. ['value' => $value],
  4776. ['variable = ? AND c_id = ?' => [$variable, $courseId]]
  4777. );
  4778. } else {
  4779. // Create
  4780. Database::insert(
  4781. $courseSettingTable,
  4782. [
  4783. 'title' => $variable,
  4784. 'value' => $value,
  4785. 'c_id' => $courseId,
  4786. 'variable' => $variable,
  4787. ]
  4788. );
  4789. }
  4790. return true;
  4791. }
  4792. /**
  4793. * Check if course setting exists.
  4794. *
  4795. * @param string $variable
  4796. * @param int $courseId
  4797. *
  4798. * @return bool
  4799. */
  4800. public static function hasCourseSetting($variable, $courseId)
  4801. {
  4802. $courseSetting = Database::get_course_table(TABLE_COURSE_SETTING);
  4803. $courseId = (int) $courseId;
  4804. $variable = Database::escape_string($variable);
  4805. $sql = "SELECT variable FROM $courseSetting
  4806. WHERE c_id = $courseId AND variable = '$variable'";
  4807. $result = Database::query($sql);
  4808. return Database::num_rows($result) > 0;
  4809. }
  4810. /**
  4811. * Get information from the track_e_course_access table.
  4812. *
  4813. * @param int $courseId
  4814. * @param int $sessionId
  4815. * @param string $startDate
  4816. * @param string $endDate
  4817. *
  4818. * @return array
  4819. */
  4820. public static function getCourseAccessPerCourseAndSession(
  4821. $courseId,
  4822. $sessionId,
  4823. $startDate,
  4824. $endDate
  4825. ) {
  4826. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  4827. $courseId = (int) $courseId;
  4828. $sessionId = (int) $sessionId;
  4829. $startDate = Database::escape_string($startDate);
  4830. $endDate = Database::escape_string($endDate);
  4831. $sql = "SELECT * FROM $table
  4832. WHERE
  4833. c_id = $courseId AND
  4834. session_id = $sessionId AND
  4835. login_course_date BETWEEN '$startDate' AND '$endDate'
  4836. ";
  4837. $result = Database::query($sql);
  4838. return Database::store_result($result);
  4839. }
  4840. /**
  4841. * Get login information from the track_e_course_access table, for any
  4842. * course in the given session.
  4843. *
  4844. * @param int $sessionId
  4845. * @param int $userId
  4846. *
  4847. * @return array
  4848. */
  4849. public static function getFirstCourseAccessPerSessionAndUser($sessionId, $userId)
  4850. {
  4851. $sessionId = (int) $sessionId;
  4852. $userId = (int) $userId;
  4853. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  4854. $sql = "SELECT * FROM $table
  4855. WHERE session_id = $sessionId AND user_id = $userId
  4856. ORDER BY login_course_date ASC
  4857. LIMIT 1";
  4858. $result = Database::query($sql);
  4859. $courseAccess = [];
  4860. if (Database::num_rows($result)) {
  4861. $courseAccess = Database::fetch_array($result, 'ASSOC');
  4862. }
  4863. return $courseAccess;
  4864. }
  4865. /**
  4866. * @param int $courseId
  4867. * @param int $sessionId
  4868. * @param bool $getAllSessions
  4869. *
  4870. * @return mixed
  4871. */
  4872. public static function getCountForum(
  4873. $courseId,
  4874. $sessionId = 0,
  4875. $getAllSessions = false
  4876. ) {
  4877. $forum = Database::get_course_table(TABLE_FORUM);
  4878. if ($getAllSessions) {
  4879. $sql = "SELECT count(*) as count
  4880. FROM $forum f
  4881. WHERE f.c_id = %s";
  4882. } else {
  4883. $sql = "SELECT count(*) as count
  4884. FROM $forum f
  4885. WHERE f.c_id = %s and f.session_id = %s";
  4886. }
  4887. $sql = sprintf($sql, intval($courseId), intval($sessionId));
  4888. $result = Database::query($sql);
  4889. $row = Database::fetch_array($result);
  4890. return $row['count'];
  4891. }
  4892. /**
  4893. * @param int $userId
  4894. * @param int $courseId
  4895. * @param int $sessionId
  4896. *
  4897. * @return mixed
  4898. */
  4899. public static function getCountPostInForumPerUser(
  4900. $userId,
  4901. $courseId,
  4902. $sessionId = 0
  4903. ) {
  4904. $forum = Database::get_course_table(TABLE_FORUM);
  4905. $forum_post = Database::get_course_table(TABLE_FORUM_POST);
  4906. $sql = "SELECT count(distinct post_id) as count
  4907. FROM $forum_post p
  4908. INNER JOIN $forum f
  4909. ON f.forum_id = p.forum_id AND f.c_id = p.c_id
  4910. WHERE p.poster_id = %s and f.session_id = %s and p.c_id = %s";
  4911. $sql = sprintf(
  4912. $sql,
  4913. intval($userId),
  4914. intval($sessionId),
  4915. intval($courseId)
  4916. );
  4917. $result = Database::query($sql);
  4918. $row = Database::fetch_array($result);
  4919. return $row['count'];
  4920. }
  4921. /**
  4922. * @param int $userId
  4923. * @param int $courseId
  4924. * @param int $sessionId
  4925. *
  4926. * @return mixed
  4927. */
  4928. public static function getCountForumPerUser(
  4929. $userId,
  4930. $courseId,
  4931. $sessionId = 0
  4932. ) {
  4933. $forum = Database::get_course_table(TABLE_FORUM);
  4934. $forum_post = Database::get_course_table(TABLE_FORUM_POST);
  4935. $sql = "SELECT count(distinct f.forum_id) as count
  4936. FROM $forum_post p
  4937. INNER JOIN $forum f
  4938. ON f.forum_id = p.forum_id AND f.c_id = p.c_id
  4939. WHERE p.poster_id = %s and f.session_id = %s and p.c_id = %s";
  4940. $sql = sprintf(
  4941. $sql,
  4942. intval($userId),
  4943. intval($sessionId),
  4944. intval($courseId)
  4945. );
  4946. $result = Database::query($sql);
  4947. $row = Database::fetch_array($result);
  4948. return $row['count'];
  4949. }
  4950. /**
  4951. * Returns the course name from a given code.
  4952. *
  4953. * @param string $code
  4954. *
  4955. * @return string
  4956. */
  4957. public static function getCourseNameFromCode($code)
  4958. {
  4959. $tbl_main_categories = Database::get_main_table(TABLE_MAIN_COURSE);
  4960. $code = Database::escape_string($code);
  4961. $sql = "SELECT title
  4962. FROM $tbl_main_categories
  4963. WHERE code = '$code'";
  4964. $result = Database::query($sql);
  4965. if ($col = Database::fetch_array($result)) {
  4966. return $col['title'];
  4967. }
  4968. }
  4969. /**
  4970. * Generates a course code from a course title.
  4971. *
  4972. * @todo Such a function might be useful in other places too. It might be moved in the CourseManager class.
  4973. * @todo the function might be upgraded for avoiding code duplications (currently,
  4974. * it might suggest a code that is already in use)
  4975. *
  4976. * @param string $title A course title
  4977. *
  4978. * @return string A proposed course code
  4979. * +
  4980. * @assert (null,null) === false
  4981. * @assert ('ABC_DEF', null) === 'ABCDEF'
  4982. * @assert ('ABC09*^[%A', null) === 'ABC09A'
  4983. */
  4984. public static function generate_course_code($title)
  4985. {
  4986. return substr(
  4987. preg_replace('/[^A-Z0-9]/', '', strtoupper(api_replace_dangerous_char($title))),
  4988. 0,
  4989. self::MAX_COURSE_LENGTH_CODE
  4990. );
  4991. }
  4992. /**
  4993. * this function gets all the users of the course,
  4994. * including users from linked courses.
  4995. *
  4996. * @param $filterByActive
  4997. *
  4998. * @return array
  4999. */
  5000. public static function getCourseUsers($filterByActive = null)
  5001. {
  5002. // This would return only the users from real courses:
  5003. $userList = self::get_user_list_from_course_code(
  5004. api_get_course_id(),
  5005. api_get_session_id(),
  5006. null,
  5007. null,
  5008. null,
  5009. null,
  5010. false,
  5011. false,
  5012. [],
  5013. [],
  5014. [],
  5015. $filterByActive
  5016. );
  5017. return $userList;
  5018. }
  5019. /**
  5020. * this function gets all the groups of the course,
  5021. * not including linked courses.
  5022. */
  5023. public static function getCourseGroups()
  5024. {
  5025. $sessionId = api_get_session_id();
  5026. if ($sessionId != 0) {
  5027. $groupList = self::get_group_list_of_course(
  5028. api_get_course_id(),
  5029. $sessionId,
  5030. 1
  5031. );
  5032. } else {
  5033. $groupList = self::get_group_list_of_course(
  5034. api_get_course_id(),
  5035. 0,
  5036. 1
  5037. );
  5038. }
  5039. return $groupList;
  5040. }
  5041. /**
  5042. * @param FormValidator $form
  5043. * @param array $alreadySelected
  5044. *
  5045. * @return HTML_QuickForm_element
  5046. */
  5047. public static function addUserGroupMultiSelect(&$form, $alreadySelected)
  5048. {
  5049. $userList = self::getCourseUsers(true);
  5050. $groupList = self::getCourseGroups();
  5051. $array = self::buildSelectOptions(
  5052. $groupList,
  5053. $userList,
  5054. $alreadySelected
  5055. );
  5056. $result = [];
  5057. foreach ($array as $content) {
  5058. $result[$content['value']] = $content['content'];
  5059. }
  5060. return $form->addElement(
  5061. 'advmultiselect',
  5062. 'users',
  5063. get_lang('Users'),
  5064. $result,
  5065. ['select_all_checkbox' => true]
  5066. );
  5067. }
  5068. /**
  5069. * This function separates the users from the groups
  5070. * users have a value USER:XXX (with XXX the groups id have a value
  5071. * GROUP:YYY (with YYY the group id).
  5072. *
  5073. * @param array $to Array of strings that define the type and id of each destination
  5074. *
  5075. * @return array Array of groups and users (each an array of IDs)
  5076. */
  5077. public static function separateUsersGroups($to)
  5078. {
  5079. $groupList = [];
  5080. $userList = [];
  5081. foreach ($to as $to_item) {
  5082. if (!empty($to_item)) {
  5083. $parts = explode(':', $to_item);
  5084. $type = isset($parts[0]) ? $parts[0] : '';
  5085. $id = isset($parts[1]) ? $parts[1] : '';
  5086. switch ($type) {
  5087. case 'GROUP':
  5088. $groupList[] = (int) $id;
  5089. break;
  5090. case 'USER':
  5091. $userList[] = (int) $id;
  5092. break;
  5093. }
  5094. }
  5095. }
  5096. $send_to['groups'] = $groupList;
  5097. $send_to['users'] = $userList;
  5098. return $send_to;
  5099. }
  5100. /**
  5101. * Shows the form for sending a message to a specific group or user.
  5102. *
  5103. * @param FormValidator $form
  5104. * @param array $groupInfo
  5105. * @param array $to
  5106. *
  5107. * @return HTML_QuickForm_element
  5108. */
  5109. public static function addGroupMultiSelect($form, $groupInfo, $to = [])
  5110. {
  5111. $groupUsers = GroupManager::get_subscribed_users($groupInfo);
  5112. $array = self::buildSelectOptions([$groupInfo], $groupUsers, $to);
  5113. $result = [];
  5114. foreach ($array as $content) {
  5115. $result[$content['value']] = $content['content'];
  5116. }
  5117. return $form->addElement('advmultiselect', 'users', get_lang('Users'), $result);
  5118. }
  5119. /**
  5120. * this function shows the form for sending a message to a specific group or user.
  5121. *
  5122. * @param array $groupList
  5123. * @param array $userList
  5124. * @param array $alreadySelected
  5125. *
  5126. * @return array
  5127. */
  5128. public static function buildSelectOptions(
  5129. $groupList = [],
  5130. $userList = [],
  5131. $alreadySelected = []
  5132. ) {
  5133. if (empty($alreadySelected)) {
  5134. $alreadySelected = [];
  5135. }
  5136. $result = [];
  5137. // adding the groups to the select form
  5138. if ($groupList) {
  5139. foreach ($groupList as $thisGroup) {
  5140. $groupId = $thisGroup['iid'];
  5141. if (is_array($alreadySelected)) {
  5142. if (!in_array(
  5143. "GROUP:".$groupId,
  5144. $alreadySelected
  5145. )
  5146. ) {
  5147. $userCount = isset($thisGroup['userNb']) ? $thisGroup['userNb'] : 0;
  5148. if (empty($userCount)) {
  5149. $userCount = isset($thisGroup['count_users']) ? $thisGroup['count_users'] : 0;
  5150. }
  5151. // $alreadySelected is the array containing the groups (and users) that are already selected
  5152. $user_label = ($userCount > 0) ? get_lang('Users') : get_lang('LowerCaseUser');
  5153. $user_disabled = ($userCount > 0) ? "" : "disabled=disabled";
  5154. $result[] = [
  5155. 'disabled' => $user_disabled,
  5156. 'value' => "GROUP:".$groupId,
  5157. // The space before "G" is needed in order to advmultiselect.php js puts groups first
  5158. 'content' => " G: ".$thisGroup['name']." - ".$userCount." ".$user_label,
  5159. ];
  5160. }
  5161. }
  5162. }
  5163. }
  5164. // adding the individual users to the select form
  5165. if ($userList) {
  5166. foreach ($userList as $user) {
  5167. if (is_array($alreadySelected)) {
  5168. if (!in_array(
  5169. "USER:".$user['user_id'],
  5170. $alreadySelected
  5171. )
  5172. ) {
  5173. // $alreadySelected is the array containing the users (and groups) that are already selected
  5174. $result[] = [
  5175. 'value' => "USER:".$user['user_id'],
  5176. 'content' => api_get_person_name($user['firstname'], $user['lastname']),
  5177. ];
  5178. }
  5179. }
  5180. }
  5181. }
  5182. return $result;
  5183. }
  5184. /**
  5185. * @return array a list (array) of all courses
  5186. */
  5187. public static function get_course_list()
  5188. {
  5189. $table = Database::get_main_table(TABLE_MAIN_COURSE);
  5190. return Database::store_result(Database::query("SELECT *, id as real_id FROM $table"));
  5191. }
  5192. /**
  5193. * Returns course code from a given gradebook category's id.
  5194. *
  5195. * @param int Category ID
  5196. *
  5197. * @return string Course code
  5198. */
  5199. public static function get_course_by_category($category_id)
  5200. {
  5201. $category_id = (int) $category_id;
  5202. $info = Database::fetch_array(
  5203. Database::query(
  5204. 'SELECT course_code
  5205. FROM '.Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY).'
  5206. WHERE id = '.$category_id
  5207. ),
  5208. 'ASSOC'
  5209. );
  5210. return $info ? $info['course_code'] : false;
  5211. }
  5212. /**
  5213. * This function gets all the courses that are not in a session.
  5214. *
  5215. * @param date Start date
  5216. * @param date End date
  5217. * @param bool $includeClosed Whether to include closed and hidden courses
  5218. *
  5219. * @return array Not-in-session courses
  5220. */
  5221. public static function getCoursesWithoutSession(
  5222. $startDate = null,
  5223. $endDate = null,
  5224. $includeClosed = false
  5225. ) {
  5226. $dateConditional = ($startDate && $endDate) ?
  5227. " WHERE session_id IN (SELECT id FROM ".Database::get_main_table(TABLE_MAIN_SESSION).
  5228. " WHERE access_start_date = '$startDate' AND access_end_date = '$endDate')" : null;
  5229. $visibility = ($includeClosed ? '' : 'visibility NOT IN (0, 4) AND ');
  5230. $sql = "SELECT id, code, title
  5231. FROM ".Database::get_main_table(TABLE_MAIN_COURSE)."
  5232. WHERE $visibility code NOT IN (
  5233. SELECT DISTINCT course_code
  5234. FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE).$dateConditional."
  5235. )
  5236. ORDER BY id";
  5237. $result = Database::query($sql);
  5238. $courses = [];
  5239. while ($row = Database::fetch_array($result)) {
  5240. $courses[] = $row;
  5241. }
  5242. return $courses;
  5243. }
  5244. /**
  5245. * Get list of courses based on users of a group for a group admin.
  5246. *
  5247. * @param int $userId The user id
  5248. *
  5249. * @return array
  5250. */
  5251. public static function getCoursesFollowedByGroupAdmin($userId)
  5252. {
  5253. $coursesList = [];
  5254. $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
  5255. $courseUserTable = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  5256. $userGroup = new UserGroup();
  5257. $userIdList = $userGroup->getGroupUsersByUser($userId);
  5258. if (empty($userIdList)) {
  5259. return [];
  5260. }
  5261. $sql = "SELECT DISTINCT(c.id), c.title
  5262. FROM $courseTable c
  5263. INNER JOIN $courseUserTable cru ON c.id = cru.c_id
  5264. WHERE (
  5265. cru.user_id IN (".implode(', ', $userIdList).")
  5266. AND cru.relation_type = 0
  5267. )";
  5268. if (api_is_multiple_url_enabled()) {
  5269. $courseAccessUrlTable = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  5270. $accessUrlId = api_get_current_access_url_id();
  5271. if ($accessUrlId != -1) {
  5272. $sql = "SELECT DISTINCT(c.id), c.title
  5273. FROM $courseTable c
  5274. INNER JOIN $courseUserTable cru ON c.id = cru.c_id
  5275. INNER JOIN $courseAccessUrlTable crau ON c.id = crau.c_id
  5276. WHERE crau.access_url_id = $accessUrlId
  5277. AND (
  5278. cru.id_user IN (".implode(', ', $userIdList).") AND
  5279. cru.relation_type = 0
  5280. )";
  5281. }
  5282. }
  5283. $result = Database::query($sql);
  5284. while ($row = Database::fetch_assoc($result)) {
  5285. $coursesList[] = $row;
  5286. }
  5287. return $coursesList;
  5288. }
  5289. /**
  5290. * Direct course link see #5299.
  5291. *
  5292. * You can send to your students an URL like this
  5293. * http://chamilodev.beeznest.com/main/auth/inscription.php?c=ABC&e=3
  5294. * Where "c" is the course code and "e" is the exercise Id, after a successful
  5295. * registration the user will be sent to the course or exercise
  5296. *
  5297. * @param array $form_data
  5298. *
  5299. * @return array
  5300. */
  5301. public static function redirectToCourse($form_data)
  5302. {
  5303. $course_code_redirect = Session::read('course_redirect');
  5304. $_user = api_get_user_info();
  5305. $userId = api_get_user_id();
  5306. if (!empty($course_code_redirect)) {
  5307. $course_info = api_get_course_info($course_code_redirect);
  5308. if (!empty($course_info)) {
  5309. if (in_array(
  5310. $course_info['visibility'],
  5311. [COURSE_VISIBILITY_OPEN_PLATFORM, COURSE_VISIBILITY_OPEN_WORLD]
  5312. )
  5313. ) {
  5314. if (self::is_user_subscribed_in_course($userId, $course_info['code'])) {
  5315. $form_data['action'] = $course_info['course_public_url'];
  5316. $form_data['message'] = sprintf(get_lang('YouHaveBeenRegisteredToCourseX'), $course_info['title']);
  5317. $form_data['button'] = Display::button(
  5318. 'next',
  5319. get_lang('GoToCourse', null, $_user['language']),
  5320. ['class' => 'btn btn-primary btn-large']
  5321. );
  5322. $exercise_redirect = intval(Session::read('exercise_redirect'));
  5323. // Specify the course id as the current context does not
  5324. // hold a global $_course array
  5325. $objExercise = new Exercise($course_info['real_id']);
  5326. $result = $objExercise->read($exercise_redirect);
  5327. if (!empty($exercise_redirect) && !empty($result)) {
  5328. $form_data['action'] = api_get_path(WEB_CODE_PATH).
  5329. 'exercise/overview.php?exerciseId='.$exercise_redirect.'&cidReq='.$course_info['code'];
  5330. $form_data['message'] .= '<br />'.get_lang('YouCanAccessTheExercise');
  5331. $form_data['button'] = Display::button(
  5332. 'next',
  5333. get_lang('Go', null, $_user['language']),
  5334. ['class' => 'btn btn-primary btn-large']
  5335. );
  5336. }
  5337. if (!empty($form_data['action'])) {
  5338. header('Location: '.$form_data['action']);
  5339. exit;
  5340. }
  5341. }
  5342. }
  5343. }
  5344. }
  5345. return $form_data;
  5346. }
  5347. /**
  5348. * Return tab of params to display a course title in the My Courses tab
  5349. * Check visibility, right, and notification icons, and load_dirs option
  5350. * get html course params.
  5351. *
  5352. * @param $courseId
  5353. * @param bool $loadDirs
  5354. *
  5355. * @return array with keys ['right_actions'] ['teachers'] ['notifications']
  5356. */
  5357. public static function getCourseParamsForDisplay($courseId, $loadDirs = false)
  5358. {
  5359. $userId = api_get_user_id();
  5360. $courseId = intval($courseId);
  5361. // Table definitions
  5362. $TABLECOURS = Database::get_main_table(TABLE_MAIN_COURSE);
  5363. $TABLECOURSUSER = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  5364. $TABLE_ACCESS_URL_REL_COURSE = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  5365. $current_url_id = api_get_current_access_url_id();
  5366. // Get course list auto-register
  5367. $special_course_list = self::get_special_course_list();
  5368. $without_special_courses = '';
  5369. if (!empty($special_course_list)) {
  5370. $without_special_courses = ' AND course.id NOT IN ("'.implode('","', $special_course_list).'")';
  5371. }
  5372. //AND course_rel_user.relation_type<>".COURSE_RELATION_TYPE_RRHH."
  5373. $sql = "SELECT
  5374. course.id,
  5375. course.title,
  5376. course.code,
  5377. course.subscribe subscr,
  5378. course.unsubscribe unsubscr,
  5379. course_rel_user.status status,
  5380. course_rel_user.sort sort,
  5381. course_rel_user.user_course_cat user_course_cat
  5382. FROM
  5383. $TABLECOURS course
  5384. INNER JOIN $TABLECOURSUSER course_rel_user
  5385. ON (course.id = course_rel_user.c_id)
  5386. INNER JOIN $TABLE_ACCESS_URL_REL_COURSE url
  5387. ON (url.c_id = course.id)
  5388. WHERE
  5389. course.id = $courseId AND
  5390. course_rel_user.user_id = $userId
  5391. $without_special_courses
  5392. ";
  5393. // If multiple URL access mode is enabled, only fetch courses
  5394. // corresponding to the current URL.
  5395. if (api_get_multiple_access_url() && $current_url_id != -1) {
  5396. $sql .= " AND url.c_id = course.id AND access_url_id = $current_url_id";
  5397. }
  5398. // Use user's classification for courses (if any).
  5399. $sql .= " ORDER BY course_rel_user.user_course_cat, course_rel_user.sort ASC";
  5400. $result = Database::query($sql);
  5401. // Browse through all courses. We can only have one course because
  5402. // of the course.id=".intval($courseId) in sql query
  5403. $course = Database::fetch_array($result);
  5404. $course_info = api_get_course_info_by_id($courseId);
  5405. if (empty($course_info)) {
  5406. return '';
  5407. }
  5408. //$course['id_session'] = null;
  5409. $course_info['id_session'] = null;
  5410. $course_info['status'] = $course['status'];
  5411. // For each course, get if there is any notification icon to show
  5412. // (something that would have changed since the user's last visit).
  5413. $show_notification = !api_get_configuration_value('hide_course_notification')
  5414. ? Display::show_notification($course_info)
  5415. : '';
  5416. // New code displaying the user's status in respect to this course.
  5417. $status_icon = Display::return_icon(
  5418. 'blackboard.png',
  5419. $course_info['title'],
  5420. [],
  5421. ICON_SIZE_LARGE
  5422. );
  5423. $params = [];
  5424. $params['right_actions'] = '';
  5425. if (api_is_platform_admin()) {
  5426. if ($loadDirs) {
  5427. $params['right_actions'] .= '<a id="document_preview_'.$course_info['real_id'].'_0" class="document_preview" href="javascript:void(0);">'.Display::return_icon('folder.png', get_lang('Documents'), ['align' => 'absmiddle'], ICON_SIZE_SMALL).'</a>';
  5428. $params['right_actions'] .= '<a href="'.api_get_path(WEB_CODE_PATH).'course_info/infocours.php?cidReq='.$course['code'].'">'.
  5429. Display::return_icon('edit.png', get_lang('Edit'), ['align' => 'absmiddle'], ICON_SIZE_SMALL).
  5430. '</a>';
  5431. $params['right_actions'] .= Display::div(
  5432. '',
  5433. [
  5434. 'id' => 'document_result_'.$course_info['real_id'].'_0',
  5435. 'class' => 'document_preview_container',
  5436. ]
  5437. );
  5438. } else {
  5439. $params['right_actions'] .= '<a class="btn btn-default btn-sm" title="'.get_lang('Edit').'" href="'.api_get_path(WEB_CODE_PATH).'course_info/infocours.php?cidReq='.$course['code'].'">'.
  5440. Display::returnFontAwesomeIcon('pencil').'</a>';
  5441. }
  5442. } else {
  5443. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED) {
  5444. if ($loadDirs) {
  5445. $params['right_actions'] .= '<a id="document_preview_'.$course_info['real_id'].'_0" class="document_preview" href="javascript:void(0);">'.
  5446. Display::return_icon('folder.png', get_lang('Documents'), ['align' => 'absmiddle'], ICON_SIZE_SMALL).'</a>';
  5447. $params['right_actions'] .= Display::div(
  5448. '',
  5449. [
  5450. 'id' => 'document_result_'.$course_info['real_id'].'_0',
  5451. 'class' => 'document_preview_container',
  5452. ]
  5453. );
  5454. } else {
  5455. if ($course_info['status'] == COURSEMANAGER) {
  5456. $params['right_actions'] .= '<a class="btn btn-default btn-sm" title="'.get_lang('Edit').'" href="'.api_get_path(WEB_CODE_PATH).'course_info/infocours.php?cidReq='.$course['code'].'">'.
  5457. Display::returnFontAwesomeIcon('pencil').'</a>';
  5458. }
  5459. }
  5460. }
  5461. }
  5462. $course_title_url = '';
  5463. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED || $course['status'] == COURSEMANAGER) {
  5464. $course_title_url = api_get_path(WEB_COURSE_PATH).$course_info['path'].'/?id_session=0';
  5465. $course_title = Display::url($course_info['title'], $course_title_url);
  5466. } else {
  5467. $course_title = $course_info['title'].' '.Display::tag(
  5468. 'span',
  5469. get_lang('CourseClosed'),
  5470. ['class' => 'item_closed']
  5471. );
  5472. }
  5473. // Start displaying the course block itself
  5474. if (api_get_setting('display_coursecode_in_courselist') === 'true') {
  5475. $course_title .= ' ('.$course_info['visual_code'].') ';
  5476. }
  5477. $teachers = '';
  5478. if (api_get_setting('display_teacher_in_courselist') === 'true') {
  5479. $teachers = self::getTeacherListFromCourseCodeToString(
  5480. $course['code'],
  5481. self::USER_SEPARATOR,
  5482. true
  5483. );
  5484. }
  5485. $params['link'] = $course_title_url;
  5486. $params['icon'] = $status_icon;
  5487. $params['title'] = $course_title;
  5488. $params['teachers'] = $teachers;
  5489. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED) {
  5490. $params['notifications'] = $show_notification;
  5491. }
  5492. return $params;
  5493. }
  5494. /**
  5495. * Get the course id based on the original id and field name in the extra fields.
  5496. * Returns 0 if course was not found.
  5497. *
  5498. * @param string $original_course_id_value Original course id
  5499. * @param string $original_course_id_name Original field name
  5500. *
  5501. * @return int Course id
  5502. */
  5503. public static function get_course_id_from_original_id($original_course_id_value, $original_course_id_name)
  5504. {
  5505. $extraFieldValue = new ExtraFieldValue('course');
  5506. $value = $extraFieldValue->get_item_id_from_field_variable_and_field_value(
  5507. $original_course_id_name,
  5508. $original_course_id_value
  5509. );
  5510. if ($value) {
  5511. return $value['item_id'];
  5512. }
  5513. return 0;
  5514. }
  5515. /**
  5516. * Helper function to create a default gradebook (if necessary) upon course creation.
  5517. *
  5518. * @param int $modelId The gradebook model ID
  5519. * @param string $courseCode Course code
  5520. */
  5521. public static function createDefaultGradebook($modelId, $courseCode)
  5522. {
  5523. if (api_get_setting('gradebook_enable_grade_model') === 'true') {
  5524. //Create gradebook_category for the new course and add
  5525. // a gradebook model for the course
  5526. if (isset($modelId) &&
  5527. !empty($modelId) &&
  5528. $modelId != '-1'
  5529. ) {
  5530. GradebookUtils::create_default_course_gradebook(
  5531. $courseCode,
  5532. $modelId
  5533. );
  5534. }
  5535. }
  5536. }
  5537. /**
  5538. * Helper function to check if there is a course template and, if so, to
  5539. * copy the template as basis for the new course.
  5540. *
  5541. * @param string $courseCode Course code
  5542. * @param int $courseTemplate 0 if no course template is defined
  5543. */
  5544. public static function useTemplateAsBasisIfRequired($courseCode, $courseTemplate)
  5545. {
  5546. $template = api_get_setting('course_creation_use_template');
  5547. $teacherCanSelectCourseTemplate = api_get_setting('teacher_can_select_course_template') === 'true';
  5548. $courseTemplate = isset($courseTemplate) ? intval($courseTemplate) : 0;
  5549. $useTemplate = false;
  5550. if ($teacherCanSelectCourseTemplate && $courseTemplate) {
  5551. $useTemplate = true;
  5552. $originCourse = api_get_course_info_by_id($courseTemplate);
  5553. } elseif (!empty($template)) {
  5554. $useTemplate = true;
  5555. $originCourse = api_get_course_info_by_id($template);
  5556. }
  5557. if ($useTemplate) {
  5558. // Include the necessary libraries to generate a course copy
  5559. // Call the course copy object
  5560. $originCourse['official_code'] = $originCourse['code'];
  5561. $cb = new CourseBuilder(null, $originCourse);
  5562. $course = $cb->build(null, $originCourse['code']);
  5563. $cr = new CourseRestorer($course);
  5564. $cr->set_file_option();
  5565. $cr->restore($courseCode);
  5566. }
  5567. }
  5568. /**
  5569. * Helper method to get the number of users defined with a specific course extra field.
  5570. *
  5571. * @param string $name Field title
  5572. * @param string $tableExtraFields The extra fields table name
  5573. * @param string $tableUserFieldValues The user extra field value table name
  5574. *
  5575. * @return int The number of users with this extra field with a specific value
  5576. */
  5577. public static function getCountRegisteredUsersWithCourseExtraField(
  5578. $name,
  5579. $tableExtraFields = '',
  5580. $tableUserFieldValues = ''
  5581. ) {
  5582. if (empty($tableExtraFields)) {
  5583. $tableExtraFields = Database::get_main_table(TABLE_EXTRA_FIELD);
  5584. }
  5585. if (empty($tableUserFieldValues)) {
  5586. $tableUserFieldValues = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  5587. }
  5588. $registered_users_with_extra_field = 0;
  5589. if (!empty($name) && $name != '-') {
  5590. $extraFieldType = EntityExtraField::COURSE_FIELD_TYPE;
  5591. $name = Database::escape_string($name);
  5592. $sql = "SELECT count(v.item_id) as count
  5593. FROM $tableUserFieldValues v
  5594. INNER JOIN $tableExtraFields f
  5595. ON (f.id = v.field_id)
  5596. WHERE value = '$name' AND extra_field_type = $extraFieldType";
  5597. $result_count = Database::query($sql);
  5598. if (Database::num_rows($result_count)) {
  5599. $row_count = Database::fetch_array($result_count);
  5600. $registered_users_with_extra_field = $row_count['count'];
  5601. }
  5602. }
  5603. return $registered_users_with_extra_field;
  5604. }
  5605. /**
  5606. * Get the course categories form a course list.
  5607. *
  5608. * @param array $courseList
  5609. *
  5610. * @return array
  5611. */
  5612. public static function getCourseCategoriesFromCourseList(array $courseList)
  5613. {
  5614. $allCategories = array_column($courseList, 'category');
  5615. $categories = array_unique($allCategories);
  5616. sort($categories);
  5617. return $categories;
  5618. }
  5619. /**
  5620. * Display the description button of a course in the course catalog.
  5621. *
  5622. * @param array $course
  5623. *
  5624. * @return string HTML string
  5625. */
  5626. public static function returnDescriptionButton($course)
  5627. {
  5628. if (empty($course)) {
  5629. return '';
  5630. }
  5631. if (api_get_setting('show_courses_descriptions_in_catalog') == 'true') {
  5632. $title = $course['title'];
  5633. $url = api_get_path(WEB_CODE_PATH).'inc/ajax/course_home.ajax.php?a=show_course_information&code='.$course['code'];
  5634. $html = Display::url(
  5635. Display::returnFontAwesomeIcon('info-circle', 'lg'),
  5636. $url,
  5637. [
  5638. 'class' => 'ajax btn btn-default btn-sm',
  5639. 'data-title' => $title,
  5640. 'title' => get_lang('Description'),
  5641. 'aria-label' => get_lang('Description'),
  5642. 'data-size' => 'lg',
  5643. ]
  5644. );
  5645. return $html;
  5646. }
  5647. return '';
  5648. }
  5649. /**
  5650. * @param Course $course
  5651. *
  5652. * @return bool
  5653. */
  5654. public static function hasPicture(Course $course)
  5655. {
  5656. return file_exists(api_get_path(SYS_COURSE_PATH).$course->getDirectory().'/course-pic85x85.png');
  5657. }
  5658. /**
  5659. * Get the course picture path.
  5660. *
  5661. * @param Course $course
  5662. * @param bool $fullSize
  5663. *
  5664. * @return string|null
  5665. */
  5666. public static function getPicturePath(Course $course, $fullSize = false)
  5667. {
  5668. if (!self::hasPicture($course)) {
  5669. return null;
  5670. }
  5671. if ($fullSize) {
  5672. return api_get_path(WEB_COURSE_PATH).$course->getDirectory().'/course-pic.png';
  5673. }
  5674. return api_get_path(WEB_COURSE_PATH).$course->getDirectory().'/course-pic85x85.png';
  5675. }
  5676. /**
  5677. * @return int
  5678. */
  5679. public static function getCountOpenCourses()
  5680. {
  5681. $visibility = [
  5682. COURSE_VISIBILITY_REGISTERED,
  5683. COURSE_VISIBILITY_OPEN_PLATFORM,
  5684. COURSE_VISIBILITY_OPEN_WORLD,
  5685. ];
  5686. $table = Database::get_main_table(TABLE_MAIN_COURSE);
  5687. $sql = "SELECT count(id) count
  5688. FROM $table
  5689. WHERE visibility IN (".implode(',', $visibility).")";
  5690. $result = Database::query($sql);
  5691. $row = Database::fetch_array($result);
  5692. return (int) $row['count'];
  5693. }
  5694. /**
  5695. * @return int
  5696. */
  5697. public static function getCountExercisesFromOpenCourse()
  5698. {
  5699. $visibility = [
  5700. COURSE_VISIBILITY_REGISTERED,
  5701. COURSE_VISIBILITY_OPEN_PLATFORM,
  5702. COURSE_VISIBILITY_OPEN_WORLD,
  5703. ];
  5704. $table = Database::get_main_table(TABLE_MAIN_COURSE);
  5705. $tableExercise = Database::get_course_table(TABLE_QUIZ_TEST);
  5706. $sql = "SELECT count(e.iid) count
  5707. FROM $table c INNER JOIN $tableExercise e
  5708. ON (c.id = e.c_id)
  5709. WHERE e.active <> -1 AND visibility IN (".implode(',', $visibility).")";
  5710. $result = Database::query($sql);
  5711. $row = Database::fetch_array($result);
  5712. return (int) $row['count'];
  5713. }
  5714. /**
  5715. * Check if a specific access-url-related setting is a problem or not.
  5716. *
  5717. * @param array $_configuration The $_configuration array
  5718. * @param int $accessUrlId The access URL ID
  5719. * @param string $param
  5720. * @param string $msgLabel
  5721. *
  5722. * @return bool|string
  5723. */
  5724. private static function checkCreateCourseAccessUrlParam($_configuration, $accessUrlId, $param, $msgLabel)
  5725. {
  5726. if (isset($_configuration[$accessUrlId][$param]) && $_configuration[$accessUrlId][$param] > 0) {
  5727. $num = self::count_courses($accessUrlId);
  5728. if ($num >= $_configuration[$accessUrlId][$param]) {
  5729. api_warn_hosting_contact($param);
  5730. Display::addFlash(
  5731. Display::return_message($msgLabel)
  5732. );
  5733. }
  5734. }
  5735. return false;
  5736. }
  5737. /**
  5738. * Fill course with all necessary items.
  5739. *
  5740. * @param array $courseInfo Course info array
  5741. * @param array $params Parameters from the course creation form
  5742. * @param int $authorId
  5743. */
  5744. private static function fillCourse($courseInfo, $params, $authorId = 0)
  5745. {
  5746. $authorId = empty($authorId) ? api_get_user_id() : (int) $authorId;
  5747. AddCourse::prepare_course_repository($courseInfo['directory']);
  5748. AddCourse::fill_db_course(
  5749. $courseInfo['real_id'],
  5750. $courseInfo['directory'],
  5751. $courseInfo['course_language'],
  5752. $params['exemplary_content'],
  5753. $authorId
  5754. );
  5755. if (isset($params['gradebook_model_id'])) {
  5756. self::createDefaultGradebook(
  5757. $params['gradebook_model_id'],
  5758. $courseInfo['code']
  5759. );
  5760. }
  5761. // If parameter defined, copy the contents from a specific
  5762. // template course into this new course
  5763. if (isset($params['course_template'])) {
  5764. self::useTemplateAsBasisIfRequired(
  5765. $courseInfo['id'],
  5766. $params['course_template']
  5767. );
  5768. }
  5769. $params['course_code'] = $courseInfo['code'];
  5770. $params['item_id'] = $courseInfo['real_id'];
  5771. $courseFieldValue = new ExtraFieldValue('course');
  5772. $courseFieldValue->saveFieldValues($params);
  5773. }
  5774. }