123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456 |
- <?php
- /* For licensing terms, see /license.txt*/
- use Chamilo\CoreBundle\Entity\Course;
- use Chamilo\CoreBundle\Entity\ExtraField as EntityExtraField;
- use Chamilo\CourseBundle\Component\CourseCopy\CourseBuilder;
- use Chamilo\CourseBundle\Component\CourseCopy\CourseRestorer;
- use ChamiloSession as Session;
- /**
- * Class CourseManager.
- *
- * This is the course library for Chamilo.
- *
- * All main course functions should be placed here.
- *
- * Many functions of this library deal with providing support for
- * virtual/linked/combined courses (this was already used in several universities
- * but not available in standard Chamilo).
- *
- * There are probably some places left with the wrong code.
- *
- * @package chamilo.library
- */
- class CourseManager
- {
- const MAX_COURSE_LENGTH_CODE = 40;
- /** This constant is used to show separate user names in the course
- * list (userportal), footer, etc */
- const USER_SEPARATOR = ' |';
- const COURSE_FIELD_TYPE_CHECKBOX = 10;
- public $columns = [];
- /**
- * Creates a course.
- *
- * @param array $params Columns in the main.course table.
- * @param int $authorId Optional.
- * @param int $accessUrlId Optional.
- *
- * @return mixed false if the course was not created, array with the course info
- */
- public static function create_course($params, $authorId = 0, $accessUrlId = 0)
- {
- global $_configuration;
- $hook = HookCreateCourse::create();
- // Check portal limits
- $accessUrlId = empty($accessUrlId)
- ? (api_get_multiple_access_url() ? api_get_current_access_url_id() : 1)
- : $accessUrlId;
- $authorId = empty($authorId) ? api_get_user_id() : (int) $authorId;
- if (isset($_configuration[$accessUrlId]) && is_array($_configuration[$accessUrlId])) {
- $return = self::checkCreateCourseAccessUrlParam(
- $_configuration,
- $accessUrlId,
- 'hosting_limit_courses',
- 'PortalCoursesLimitReached'
- );
- if ($return != false) {
- return $return;
- }
- $return = self::checkCreateCourseAccessUrlParam(
- $_configuration,
- $accessUrlId,
- 'hosting_limit_active_courses',
- 'PortalActiveCoursesLimitReached'
- );
- if ($return != false) {
- return $return;
- }
- }
- if (empty($params['title'])) {
- return false;
- }
- if (empty($params['wanted_code'])) {
- $params['wanted_code'] = $params['title'];
- // Check whether the requested course code has already been occupied.
- $substring = api_substr($params['title'], 0, self::MAX_COURSE_LENGTH_CODE);
- if ($substring === false || empty($substring)) {
- return false;
- } else {
- $params['wanted_code'] = self::generate_course_code($substring);
- }
- }
- // Create the course keys
- $keys = AddCourse::define_course_keys($params['wanted_code']);
- $params['exemplary_content'] = isset($params['exemplary_content']) ? $params['exemplary_content'] : false;
- if (count($keys)) {
- $params['code'] = $keys['currentCourseCode'];
- $params['visual_code'] = $keys['currentCourseId'];
- $params['directory'] = $keys['currentCourseRepository'];
- $course_info = api_get_course_info($params['code']);
- if (empty($course_info)) {
- $course_id = AddCourse::register_course($params, $accessUrlId);
- $course_info = api_get_course_info_by_id($course_id);
- if ($hook) {
- $hook->setEventData(['course_info' => $course_info]);
- $hook->notifyCreateCourse(HOOK_EVENT_TYPE_POST);
- }
- if (!empty($course_info)) {
- self::fillCourse($course_info, $params, $authorId);
- return $course_info;
- }
- }
- }
- return false;
- }
- /**
- * Returns all the information of a given course code.
- *
- * @param string $course_code , the course code
- *
- * @return array with all the fields of the course table
- *
- * @deprecated Use api_get_course_info() instead
- *
- * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
- * @assert ('') === false
- */
- public static function get_course_information($course_code)
- {
- return Database::fetch_array(
- Database::query(
- "SELECT *, id as real_id FROM ".Database::get_main_table(TABLE_MAIN_COURSE)."
- WHERE code = '".Database::escape_string($course_code)."'"
- ),
- 'ASSOC'
- );
- }
- /**
- * Returns a list of courses. Should work with quickform syntax.
- *
- * @param int $from Offset (from the 7th = '6'). Optional.
- * @param int $howmany Number of results we want. Optional.
- * @param int $orderby The column we want to order it by. Optional, defaults to first column.
- * @param string $orderdirection The direction of the order (ASC or DESC). Optional, defaults to ASC.
- * @param int $visibility the visibility of the course, or all by default
- * @param string $startwith If defined, only return results for which the course *title* begins with this string
- * @param string $urlId The Access URL ID, if using multiple URLs
- * @param bool $alsoSearchCode An extension option to indicate that we also want to search for course codes (not *only* titles)
- * @param array $conditionsLike
- * @param array $onlyThisCourseList
- *
- * @return array
- */
- public static function get_courses_list(
- $from = 0,
- $howmany = 0,
- $orderby = 1,
- $orderdirection = 'ASC',
- $visibility = -1,
- $startwith = '',
- $urlId = null,
- $alsoSearchCode = false,
- $conditionsLike = [],
- $onlyThisCourseList = []
- ) {
- $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
- $sql = "SELECT course.*, course.id as real_id
- FROM $courseTable course ";
- if (!empty($urlId)) {
- $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
- $sql .= " INNER JOIN $table url ON (url.c_id = course.id) ";
- }
- $visibility = (int) $visibility;
- if (!empty($startwith)) {
- $sql .= "WHERE (title LIKE '".Database::escape_string($startwith)."%' ";
- if ($alsoSearchCode) {
- $sql .= "OR code LIKE '".Database::escape_string($startwith)."%' ";
- }
- $sql .= ') ';
- if ($visibility !== -1) {
- $sql .= " AND visibility = $visibility ";
- }
- } else {
- $sql .= 'WHERE 1 ';
- if ($visibility !== -1) {
- $sql .= " AND visibility = $visibility ";
- }
- }
- if (!empty($urlId)) {
- $urlId = (int) $urlId;
- $sql .= " AND access_url_id = $urlId";
- }
- if (!empty($onlyThisCourseList)) {
- $onlyThisCourseList = array_map('intval', $onlyThisCourseList);
- $onlyThisCourseList = implode("','", $onlyThisCourseList);
- $sql .= " AND course.id IN ('$onlyThisCourseList') ";
- }
- $allowedFields = [
- 'title',
- 'code',
- ];
- if (count($conditionsLike) > 0) {
- $sql .= ' AND ';
- $temp_conditions = [];
- foreach ($conditionsLike as $field => $value) {
- if (!in_array($field, $allowedFields)) {
- continue;
- }
- $field = Database::escape_string($field);
- $value = Database::escape_string($value);
- $simple_like = false;
- if ($simple_like) {
- $temp_conditions[] = $field." LIKE '$value%'";
- } else {
- $temp_conditions[] = $field.' LIKE \'%'.$value.'%\'';
- }
- }
- $condition = ' AND ';
- if (!empty($temp_conditions)) {
- $sql .= implode(' '.$condition.' ', $temp_conditions);
- }
- }
- if (!empty($orderby)) {
- $sql .= " ORDER BY ".Database::escape_string($orderby)." ";
- } else {
- $sql .= ' ORDER BY 1 ';
- }
- if (!in_array($orderdirection, ['ASC', 'DESC'])) {
- $sql .= 'ASC';
- } else {
- $sql .= ($orderdirection == 'ASC' ? 'ASC' : 'DESC');
- }
- if (!empty($howmany) && is_int($howmany) and $howmany > 0) {
- $sql .= ' LIMIT '.Database::escape_string($howmany);
- } else {
- $sql .= ' LIMIT 1000000'; //virtually no limit
- }
- if (!empty($from)) {
- $from = intval($from);
- $sql .= ' OFFSET '.intval($from);
- } else {
- $sql .= ' OFFSET 0';
- }
- $data = [];
- $res = Database::query($sql);
- if (Database::num_rows($res) > 0) {
- while ($row = Database::fetch_array($res, 'ASSOC')) {
- $data[] = $row;
- }
- }
- return $data;
- }
- /**
- * Returns the status of a user in a course, which is COURSEMANAGER or STUDENT.
- *
- * @param int $userId
- * @param int $courseId
- *
- * @return int|bool the status of the user in that course (or false if the user is not in that course)
- */
- public static function getUserInCourseStatus($userId, $courseId)
- {
- $courseId = (int) $courseId;
- $userId = (int) $userId;
- if (empty($courseId)) {
- return false;
- }
- $result = Database::fetch_array(
- Database::query(
- "SELECT status FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
- WHERE
- c_id = $courseId AND
- user_id = $userId"
- )
- );
- return $result['status'];
- }
- /**
- * @param int $userId
- * @param int $courseId
- *
- * @return mixed
- */
- public static function getUserCourseInfo($userId, $courseId)
- {
- $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
- WHERE
- c_id = ".intval($courseId)." AND
- user_id = ".intval($userId);
- $result = Database::fetch_array(Database::query($sql));
- return $result;
- }
- /**
- * @param int $userId
- * @param int $courseId
- * @param bool $isTutor
- *
- * @return bool
- */
- public static function updateUserCourseTutor($userId, $courseId, $isTutor)
- {
- $table = Database::escape_string(TABLE_MAIN_COURSE_USER);
- $courseId = intval($courseId);
- $isTutor = intval($isTutor);
- $sql = "UPDATE $table SET is_tutor = '".$isTutor."'
- WHERE
- user_id = ".$userId." AND
- c_id = ".$courseId;
- $result = Database::query($sql);
- if (Database::affected_rows($result) > 0) {
- return true;
- } else {
- return false;
- }
- }
- /**
- * @param int $userId
- * @param int $courseId
- *
- * @return mixed
- */
- public static function get_tutor_in_course_status($userId, $courseId)
- {
- $userId = intval($userId);
- $courseId = intval($courseId);
- $result = Database::fetch_array(
- Database::query(
- "SELECT is_tutor
- FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
- WHERE
- c_id = $courseId AND
- user_id = $userId"
- )
- );
- return $result['is_tutor'];
- }
- /**
- * Unsubscribe one or more users from a course.
- *
- * @param mixed user_id or an array with user ids
- * @param string course code
- * @param int session id
- *
- * @return bool
- *
- * @assert ('', '') === false
- */
- public static function unsubscribe_user($user_id, $course_code, $session_id = 0)
- {
- if (empty($user_id)) {
- return false;
- }
- if (!is_array($user_id)) {
- $user_id = [$user_id];
- }
- if (count($user_id) == 0) {
- return false;
- }
- if (!empty($session_id)) {
- $session_id = (int) $session_id;
- } else {
- $session_id = api_get_session_id();
- }
- if (empty($course_code)) {
- return false;
- }
- $userList = [];
- // Cleaning the $user_id variable
- if (is_array($user_id)) {
- $new_user_id_list = [];
- foreach ($user_id as $my_user_id) {
- $new_user_id_list[] = (int) $my_user_id;
- }
- $new_user_id_list = array_filter($new_user_id_list);
- $userList = $new_user_id_list;
- $user_ids = implode(',', $new_user_id_list);
- } else {
- $user_ids = (int) $user_id;
- $userList[] = $user_id;
- }
- $course_info = api_get_course_info($course_code);
- $course_id = $course_info['real_id'];
- // Unsubscribe user from all groups in the course.
- $sql = "DELETE FROM ".Database::get_course_table(TABLE_GROUP_USER)."
- WHERE c_id = $course_id AND user_id IN (".$user_ids.")";
- Database::query($sql);
- $sql = "DELETE FROM ".Database::get_course_table(TABLE_GROUP_TUTOR)."
- WHERE c_id = $course_id AND user_id IN (".$user_ids.")";
- Database::query($sql);
- // Erase user student publications (works) in the course - by André Boivin
- if (!empty($userList)) {
- require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
- foreach ($userList as $userId) {
- // Getting all work from user
- $workList = getWorkPerUser($userId);
- if (!empty($workList)) {
- foreach ($workList as $work) {
- $work = $work['work'];
- // Getting user results
- if (!empty($work->user_results)) {
- foreach ($work->user_results as $workSent) {
- deleteWorkItem($workSent['id'], $course_info);
- }
- }
- }
- }
- }
- }
- // Unsubscribe user from all blogs in the course.
- $sql = "DELETE FROM ".Database::get_course_table(TABLE_BLOGS_REL_USER)."
- WHERE c_id = $course_id AND user_id IN ($user_ids)";
- Database::query($sql);
- $sql = "DELETE FROM ".Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER)."
- WHERE c_id = $course_id AND user_id IN ($user_ids)";
- Database::query($sql);
- // Deleting users in forum_notification and mailqueue course tables
- $sql = "DELETE FROM ".Database::get_course_table(TABLE_FORUM_NOTIFICATION)."
- WHERE c_id = $course_id AND user_id IN ($user_ids)";
- Database::query($sql);
- $sql = "DELETE FROM ".Database::get_course_table(TABLE_FORUM_MAIL_QUEUE)."
- WHERE c_id = $course_id AND user_id IN ($user_ids)";
- Database::query($sql);
- // Unsubscribe user from the course.
- if (!empty($session_id)) {
- foreach ($userList as $uid) {
- SessionManager::unSubscribeUserFromCourseSession($uid, $course_id, $session_id);
- // check if a user is register in the session with other course
- $sql = "SELECT user_id FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)."
- WHERE session_id = $session_id AND user_id = $uid";
- $rs = Database::query($sql);
- if (Database::num_rows($rs) == 0) {
- SessionManager::unsubscribe_user_from_session($uid, $session_id);
- }
- }
- Event::addEvent(
- LOG_UNSUBSCRIBE_USER_FROM_COURSE,
- LOG_COURSE_CODE,
- $course_code,
- api_get_utc_datetime(),
- $user_id,
- $course_id,
- $session_id
- );
- } else {
- $sql = "DELETE FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
- WHERE
- user_id IN ($user_ids) AND
- relation_type <> ".COURSE_RELATION_TYPE_RRHH." AND
- c_id = $course_id";
- Database::query($sql);
- // add event to system log
- $user_id = api_get_user_id();
- Event::addEvent(
- LOG_UNSUBSCRIBE_USER_FROM_COURSE,
- LOG_COURSE_CODE,
- $course_code,
- api_get_utc_datetime(),
- $user_id,
- $course_id
- );
- foreach ($userList as $userId) {
- $userInfo = api_get_user_info($userId);
- Event::addEvent(
- LOG_UNSUBSCRIBE_USER_FROM_COURSE,
- LOG_USER_OBJECT,
- $userInfo,
- api_get_utc_datetime(),
- $user_id,
- $course_id
- );
- }
- }
- }
- /**
- * @param string $courseCode
- * @param int $status
- *
- * @return bool
- */
- public static function autoSubscribeToCourse($courseCode, $status = STUDENT)
- {
- $courseInfo = api_get_course_info($courseCode);
- if (empty($courseInfo)) {
- return false;
- }
- if (api_is_anonymous()) {
- return false;
- }
- if (in_array(
- $courseInfo['visibility'],
- [
- COURSE_VISIBILITY_CLOSED,
- COURSE_VISIBILITY_REGISTERED,
- COURSE_VISIBILITY_HIDDEN,
- ]
- )
- ) {
- Display::addFlash(
- Display::return_message(
- get_lang('SubscribingNotAllowed'),
- 'warning'
- )
- );
- return false;
- }
- return self::subscribeUser(api_get_user_id(), $courseInfo['code'], $status);
- }
- /**
- * Subscribe a user to a course. No checks are performed here to see if
- * course subscription is allowed.
- *
- * @param int $userId
- * @param string $courseCode
- * @param int $status (STUDENT, COURSEMANAGER, COURSE_ADMIN, NORMAL_COURSE_MEMBER)
- * @param int $sessionId
- * @param int $userCourseCategoryId
- * @param bool $checkTeacherPermission
- *
- * @return bool True on success, false on failure
- *
- * @assert ('', '') === false
- */
- public static function subscribeUser(
- $userId,
- $courseCode,
- $status = STUDENT,
- $sessionId = 0,
- $userCourseCategoryId = 0,
- $checkTeacherPermission = true
- ) {
- $userId = (int) $userId;
- $status = (int) $status;
- if (empty($userId) || empty($courseCode)) {
- return false;
- }
- $courseInfo = api_get_course_info($courseCode);
- if (empty($courseInfo)) {
- Display::addFlash(Display::return_message(get_lang('CourseDoesNotExist'), 'warning'));
- return false;
- }
- $userInfo = api_get_user_info($userId);
- if (empty($userInfo)) {
- Display::addFlash(Display::return_message(get_lang('UserDoesNotExist'), 'warning'));
- return false;
- }
- $courseId = $courseInfo['real_id'];
- $courseCode = $courseInfo['code'];
- $userCourseCategoryId = (int) $userCourseCategoryId;
- $sessionId = empty($sessionId) ? api_get_session_id() : (int) $sessionId;
- $status = $status === STUDENT || $status === COURSEMANAGER ? $status : STUDENT;
- $courseUserTable = Database::get_main_table(TABLE_MAIN_COURSE_USER);
- if (!empty($sessionId)) {
- SessionManager::subscribe_users_to_session_course(
- [$userId],
- $sessionId,
- $courseCode
- );
- // Add event to the system log
- Event::addEvent(
- LOG_SUBSCRIBE_USER_TO_COURSE,
- LOG_COURSE_CODE,
- $courseCode,
- api_get_utc_datetime(),
- api_get_user_id(),
- $courseId,
- $sessionId
- );
- Event::addEvent(
- LOG_SUBSCRIBE_USER_TO_COURSE,
- LOG_USER_OBJECT,
- $userInfo,
- api_get_utc_datetime(),
- api_get_user_id(),
- $courseId,
- $sessionId
- );
- return true;
- } else {
- // Check whether the user has not been already subscribed to the course.
- $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
- WHERE
- user_id = $userId AND
- relation_type <> ".COURSE_RELATION_TYPE_RRHH." AND
- c_id = $courseId
- ";
- if (Database::num_rows(Database::query($sql)) > 0) {
- Display::addFlash(Display::return_message(get_lang('AlreadyRegisteredToCourse'), 'warning'));
- return false;
- }
- if ($checkTeacherPermission && !api_is_course_admin()) {
- // Check in advance whether subscription is allowed or not for this course.
- if ((int) $courseInfo['subscribe'] === SUBSCRIBE_NOT_ALLOWED) {
- Display::addFlash(Display::return_message(get_lang('SubscriptionNotAllowed'), 'warning'));
- return false;
- }
- }
- if ($status === STUDENT) {
- // Check if max students per course extra field is set
- $extraFieldValue = new ExtraFieldValue('course');
- $value = $extraFieldValue->get_values_by_handler_and_field_variable($courseId, 'max_subscribed_students');
- if (!empty($value) && isset($value['value'])) {
- $maxStudents = $value['value'];
- if ($maxStudents !== '') {
- $maxStudents = (int) $maxStudents;
- $count = self::get_user_list_from_course_code(
- $courseCode,
- 0,
- null,
- null,
- STUDENT,
- true,
- false
- );
- if ($count >= $maxStudents) {
- Display::addFlash(Display::return_message(get_lang('MaxNumberSubscribedStudentsReached'), 'warning'));
- return false;
- }
- }
- }
- }
- $maxSort = api_max_sort_value('0', $userId);
- $params = [
- 'c_id' => $courseId,
- 'user_id' => $userId,
- 'status' => $status,
- 'sort' => $maxSort + 1,
- 'relation_type' => 0,
- 'user_course_cat' => (int) $userCourseCategoryId,
- ];
- $insertId = Database::insert($courseUserTable, $params);
- if ($insertId) {
- Display::addFlash(
- Display::return_message(
- sprintf(
- get_lang('UserXAddedToCourseX'),
- $userInfo['complete_name_with_username'],
- $courseInfo['title']
- )
- )
- );
- $send = api_get_course_setting('email_alert_to_teacher_on_new_user_in_course', $courseCode);
- if ($send == 1) {
- self::email_to_tutor(
- $userId,
- $courseInfo['real_id'],
- false
- );
- } elseif ($send == 2) {
- self::email_to_tutor(
- $userId,
- $courseInfo['real_id'],
- true
- );
- }
- $subscribe = (int) api_get_course_setting('subscribe_users_to_forum_notifications', $courseCode);
- if ($subscribe === 1) {
- require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
- $forums = get_forums(0, $courseCode, true, $sessionId);
- foreach ($forums as $forum) {
- $forumId = $forum['iid'];
- set_notification('forum', $forumId, false, $userInfo, $courseInfo);
- }
- }
- // Add event to the system log
- Event::addEvent(
- LOG_SUBSCRIBE_USER_TO_COURSE,
- LOG_COURSE_CODE,
- $courseCode,
- api_get_utc_datetime(),
- api_get_user_id(),
- $courseId
- );
- Event::addEvent(
- LOG_SUBSCRIBE_USER_TO_COURSE,
- LOG_USER_OBJECT,
- $userInfo,
- api_get_utc_datetime(),
- api_get_user_id(),
- $courseId
- );
- return true;
- }
- return false;
- }
- }
- /**
- * Get the course id based on the original id and field name in the
- * extra fields. Returns 0 if course was not found.
- *
- * @param string $original_course_id_value
- * @param string $original_course_id_name
- *
- * @return int Course id
- *
- * @assert ('', '') === false
- */
- public static function get_course_code_from_original_id(
- $original_course_id_value,
- $original_course_id_name
- ) {
- $t_cfv = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
- $table_field = Database::get_main_table(TABLE_EXTRA_FIELD);
- $extraFieldType = EntityExtraField::COURSE_FIELD_TYPE;
- $original_course_id_value = Database::escape_string($original_course_id_value);
- $original_course_id_name = Database::escape_string($original_course_id_name);
- $sql = "SELECT item_id
- FROM $table_field cf
- INNER JOIN $t_cfv cfv
- ON cfv.field_id=cf.id
- WHERE
- variable = '$original_course_id_name' AND
- value = '$original_course_id_value' AND
- cf.extra_field_type = $extraFieldType
- ";
- $res = Database::query($sql);
- $row = Database::fetch_object($res);
- if ($row) {
- return $row->item_id;
- } else {
- return 0;
- }
- }
- /**
- * Gets the course code from the course id. Returns null if course id was not found.
- *
- * @param int $id Course id
- *
- * @return string Course code
- * @assert ('') === false
- */
- public static function get_course_code_from_course_id($id)
- {
- $table = Database::get_main_table(TABLE_MAIN_COURSE);
- $id = intval($id);
- $sql = "SELECT code FROM $table WHERE id = $id ";
- $res = Database::query($sql);
- $row = Database::fetch_object($res);
- if ($row) {
- return $row->code;
- } else {
- return null;
- }
- }
- /**
- * Add the user $userId visibility to the course $courseCode in the catalogue.
- *
- * @author David Nos (https://github.com/dnos)
- *
- * @param int $userId the id of the user
- * @param string $courseCode the course code
- * @param int $visible (optional) The course visibility in the catalogue to the user (1=visible, 0=invisible)
- *
- * @return bool true if added succesfully, false otherwise
- */
- public static function addUserVisibilityToCourseInCatalogue(
- $userId,
- $courseCode,
- $visible = 1
- ) {
- $debug = false;
- $userTable = Database::get_main_table(TABLE_MAIN_USER);
- $courseUserTable = Database::get_main_table(TABLE_MAIN_COURSE_CATALOGUE_USER);
- $visible = (int) $visible;
- if (empty($userId) || empty($courseCode) || ($userId != strval(intval($userId)))) {
- return false;
- }
- $courseCode = Database::escape_string($courseCode);
- $courseInfo = api_get_course_info($courseCode);
- $courseId = $courseInfo['real_id'];
- // Check in advance whether the user has already been registered on the platform.
- $sql = "SELECT status FROM ".$userTable." WHERE user_id = $userId ";
- if (Database::num_rows(Database::query($sql)) == 0) {
- if ($debug) {
- error_log('The user has not been registered to the platform');
- }
- return false; // The user has not been registered to the platform.
- }
- // Check whether the user has already been registered to the course visibility in the catalogue.
- $sql = "SELECT * FROM $courseUserTable
- WHERE
- user_id = $userId AND
- visible = $visible AND
- c_id = $courseId";
- if (Database::num_rows(Database::query($sql)) > 0) {
- if ($debug) {
- error_log('The user has been already registered to the course visibility in the catalogue');
- }
- return true; // The visibility of the user to the course in the catalogue does already exist.
- }
- // Register the user visibility to course in catalogue.
- $params = [
- 'user_id' => $userId,
- 'c_id' => $courseId,
- 'visible' => $visible,
- ];
- $insertId = Database::insert($courseUserTable, $params);
- return $insertId;
- }
- /**
- * Remove the user $userId visibility to the course $courseCode in the catalogue.
- *
- * @author David Nos (https://github.com/dnos)
- *
- * @param int $userId the id of the user
- * @param string $courseCode the course code
- * @param int $visible (optional) The course visibility in the catalogue to the user (1=visible, 0=invisible)
- *
- * @return bool true if removed succesfully or register not found, false otherwise
- */
- public static function removeUserVisibilityToCourseInCatalogue(
- $userId,
- $courseCode,
- $visible = 1
- ) {
- $courseUserTable = Database::get_main_table(TABLE_MAIN_COURSE_CATALOGUE_USER);
- if (empty($userId) || empty($courseCode) || ($userId != strval(intval($userId)))) {
- return false;
- }
- $courseCode = Database::escape_string($courseCode);
- $courseInfo = api_get_course_info($courseCode);
- $courseId = $courseInfo['real_id'];
- // Check whether the user has already been registered to the course visibility in the catalogue.
- $sql = "SELECT * FROM $courseUserTable
- WHERE
- user_id = $userId AND
- visible = $visible AND
- c_id = $courseId";
- if (Database::num_rows(Database::query($sql)) > 0) {
- $cond = [
- 'user_id = ? AND c_id = ? AND visible = ? ' => [
- $userId,
- $courseId,
- $visible,
- ],
- ];
- return Database::delete($courseUserTable, $cond);
- } else {
- return true; // Register does not exist
- }
- }
- /**
- * @param string $code
- *
- * @return bool if there already are one or more courses
- * with the same code OR visual_code (visualcode), false otherwise
- */
- public static function course_code_exists($code)
- {
- $code = Database::escape_string($code);
- $sql = "SELECT COUNT(*) as number
- FROM ".Database::get_main_table(TABLE_MAIN_COURSE)."
- WHERE code = '$code' OR visual_code = '$code'";
- $result = Database::fetch_array(Database::query($sql));
- return $result['number'] > 0;
- }
- /**
- * @param int $user_id
- * @param string $startsWith Optional
- *
- * @return array an array with the course info of all the courses (real and virtual)
- * of which the current user is course admin
- */
- public static function get_course_list_of_user_as_course_admin($user_id, $startsWith = '')
- {
- if ($user_id != strval(intval($user_id))) {
- return [];
- }
- // Definitions database tables and variables
- $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
- $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
- $user_id = intval($user_id);
- $data = [];
- $sql = "SELECT
- course.code,
- course.title,
- course.id,
- course.id as real_id,
- course.category_code
- FROM $tbl_course_user as course_rel_user
- INNER JOIN $tbl_course as course
- ON course.id = course_rel_user.c_id
- WHERE
- course_rel_user.user_id = $user_id AND
- course_rel_user.status = 1
- ";
- if (api_get_multiple_access_url()) {
- $tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
- $access_url_id = api_get_current_access_url_id();
- if ($access_url_id != -1) {
- $sql = "
- SELECT
- course.code,
- course.title,
- course.id,
- course.id as real_id
- FROM $tbl_course_user as course_rel_user
- INNER JOIN $tbl_course as course
- ON course.id = course_rel_user.c_id
- INNER JOIN $tbl_course_rel_access_url course_rel_url
- ON (course_rel_url.c_id = course.id)
- WHERE
- access_url_id = $access_url_id AND
- course_rel_user.user_id = $user_id AND
- course_rel_user.status = 1
- ";
- }
- }
- if (!empty($startsWith)) {
- $startsWith = Database::escape_string($startsWith);
- $sql .= " AND (course.title LIKE '$startsWith%' OR course.code LIKE '$startsWith%')";
- }
- $sql .= ' ORDER BY course.title';
- $result_nb_cours = Database::query($sql);
- if (Database::num_rows($result_nb_cours) > 0) {
- while ($row = Database::fetch_array($result_nb_cours, 'ASSOC')) {
- $data[$row['id']] = $row;
- }
- }
- return $data;
- }
- /**
- * @param int $userId
- * @param array $courseInfo
- *
- * @return bool|null
- */
- public static function isUserSubscribedInCourseAsDrh($userId, $courseInfo)
- {
- $userId = intval($userId);
- if (!api_is_drh()) {
- return false;
- }
- if (empty($courseInfo) || empty($userId)) {
- return false;
- }
- $courseId = intval($courseInfo['real_id']);
- $table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
- $sql = "SELECT * FROM $table
- WHERE
- user_id = $userId AND
- relation_type = ".COURSE_RELATION_TYPE_RRHH." AND
- c_id = $courseId";
- $result = Database::fetch_array(Database::query($sql));
- if (!empty($result)) {
- // The user has been registered in this course.
- return true;
- }
- }
- /**
- * Check if user is subscribed inside a course.
- *
- * @param int $user_id
- * @param string $course_code , if this parameter is null, it'll check for all courses
- * @param bool $in_a_session True for checking inside sessions too, by default is not checked
- * @param int $session_id
- *
- * @return bool $session_id true if the user is registered in the course, false otherwise
- */
- public static function is_user_subscribed_in_course(
- $user_id,
- $course_code = null,
- $in_a_session = false,
- $session_id = 0
- ) {
- $user_id = (int) $user_id;
- $session_id = (int) $session_id;
- if (empty($session_id)) {
- $session_id = api_get_session_id();
- }
- $condition_course = '';
- if (isset($course_code)) {
- $courseInfo = api_get_course_info($course_code);
- if (empty($courseInfo)) {
- return false;
- }
- $courseId = $courseInfo['real_id'];
- $condition_course = " AND c_id = $courseId";
- }
- $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
- WHERE
- user_id = $user_id AND
- relation_type<>".COURSE_RELATION_TYPE_RRHH."
- $condition_course ";
- $result = Database::fetch_array(Database::query($sql));
- if (!empty($result)) {
- // The user has been registered in this course.
- return true;
- }
- if (!$in_a_session) {
- // The user has not been registered in this course.
- return false;
- }
- $tableSessionCourseUser = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
- $sql = "SELECT 1 FROM $tableSessionCourseUser
- WHERE user_id = $user_id AND session_id = $session_id $condition_course";
- if (Database::num_rows(Database::query($sql)) > 0) {
- return true;
- }
- $sql = "SELECT 1 FROM $tableSessionCourseUser
- WHERE user_id = $user_id AND session_id = $session_id AND status = 2 $condition_course";
- if (Database::num_rows(Database::query($sql)) > 0) {
- return true;
- }
- $sql = 'SELECT 1 FROM '.Database::get_main_table(TABLE_MAIN_SESSION).
- " WHERE id = $session_id AND id_coach = $user_id";
- if (Database::num_rows(Database::query($sql)) > 0) {
- return true;
- }
- return false;
- }
- /**
- * Is the user a teacher in the given course?
- *
- * @param int $user_id , the id (int) of the user
- * @param string $course_code , the course code
- *
- * @return bool if the user is a teacher in the course, false otherwise
- */
- public static function is_course_teacher($user_id, $course_code)
- {
- if ($user_id != strval(intval($user_id))) {
- return false;
- }
- $courseInfo = api_get_course_info($course_code);
- if (empty($courseInfo)) {
- return false;
- }
- $courseId = $courseInfo['real_id'];
- $sql = "SELECT status FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
- WHERE c_id = $courseId AND user_id = $user_id ";
- $result = Database::query($sql);
- if (Database::num_rows($result) > 0) {
- return Database::result($result, 0, 'status') == 1;
- }
- return false;
- }
- /**
- * Is the user subscribed in the real course or linked courses?
- *
- * @param int the id of the user
- * @param int $courseId
- *
- * @deprecated linked_courses definition doesn't exists
- *
- * @return bool if the user is registered in the real course or linked courses, false otherwise
- */
- public static function is_user_subscribed_in_real_or_linked_course($user_id, $courseId, $session_id = 0)
- {
- if ($user_id != strval(intval($user_id))) {
- return false;
- }
- $courseId = intval($courseId);
- $session_id = intval($session_id);
- if (empty($session_id)) {
- $result = Database::fetch_array(
- Database::query(
- "SELECT *
- FROM ".Database::get_main_table(TABLE_MAIN_COURSE)." course
- LEFT JOIN ".Database::get_main_table(TABLE_MAIN_COURSE_USER)." course_user
- ON course.id = course_user.c_id
- WHERE
- course_user.user_id = $user_id AND
- course_user.relation_type<>".COURSE_RELATION_TYPE_RRHH." AND
- ( course.id = $courseId)"
- )
- );
- return !empty($result);
- }
- // From here we trust session id.
- // Is he/she subscribed to the session's course?
- // A user?
- if (Database::num_rows(Database::query("SELECT user_id
- FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)."
- WHERE session_id = $session_id
- AND user_id = $user_id"))
- ) {
- return true;
- }
- // A course coach?
- if (Database::num_rows(Database::query("SELECT user_id
- FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)."
- WHERE session_id = $session_id
- AND user_id = $user_id AND status = 2
- AND c_id = $courseId"))
- ) {
- return true;
- }
- // A session coach?
- if (Database::num_rows(Database::query("SELECT id_coach
- FROM ".Database::get_main_table(TABLE_MAIN_SESSION)." AS session
- WHERE session.id = $session_id
- AND id_coach = $user_id"))
- ) {
- return true;
- }
- return false;
- }
- /**
- * Return user info array of all users registered in a course
- * This only returns the users that are registered in this actual course, not linked courses.
- *
- * @param string $course_code
- * @param int $session_id
- * @param string $limit
- * @param string $order_by the field to order the users by.
- * Valid values are 'lastname', 'firstname', 'username', 'email', 'official_code' OR a part of a SQL statement
- * that starts with ORDER BY ...
- * @param int|null $filter_by_status if using the session_id: 0 or 2 (student, coach),
- * if using session_id = 0 STUDENT or COURSEMANAGER
- * @param bool|null $return_count
- * @param bool $add_reports
- * @param bool $resumed_report
- * @param array $extra_field
- * @param array $courseCodeList
- * @param array $userIdList
- * @param string $filterByActive
- * @param array $sessionIdList
- * @param string $searchByKeyword
- *
- * @return array|int
- */
- public static function get_user_list_from_course_code(
- $course_code = null,
- $session_id = 0,
- $limit = null,
- $order_by = null,
- $filter_by_status = null,
- $return_count = null,
- $add_reports = false,
- $resumed_report = false,
- $extra_field = [],
- $courseCodeList = [],
- $userIdList = [],
- $filterByActive = null,
- $sessionIdList = [],
- $searchByKeyword = ''
- ) {
- $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
- $sessionTable = Database::get_main_table(TABLE_MAIN_SESSION);
- $session_id = (int) $session_id;
- $course_code = Database::escape_string($course_code);
- $courseInfo = api_get_course_info($course_code);
- $courseId = 0;
- if (!empty($courseInfo)) {
- $courseId = $courseInfo['real_id'];
- }
- $where = [];
- if (empty($order_by)) {
- $order_by = 'user.lastname, user.firstname';
- if (api_is_western_name_order()) {
- $order_by = 'user.firstname, user.lastname';
- }
- }
- // if the $order_by does not contain 'ORDER BY'
- // we have to check if it is a valid field that can be sorted on
- if (!strstr($order_by, 'ORDER BY')) {
- if (!empty($order_by)) {
- $order_by = "ORDER BY $order_by";
- } else {
- $order_by = '';
- }
- }
- $filter_by_status_condition = null;
- if (!empty($session_id) || !empty($sessionIdList)) {
- $sql = 'SELECT DISTINCT
- user.user_id,
- user.email,
- session_course_user.status as status_session,
- session_id,
- user.*,
- course.*,
- course.id AS c_id,
- session.name as session_name
- ';
- if ($return_count) {
- $sql = " SELECT COUNT(user.user_id) as count";
- }
- $sessionCondition = " session_course_user.session_id = $session_id";
- if (!empty($sessionIdList)) {
- $sessionIdListTostring = implode("','", array_map('intval', $sessionIdList));
- $sessionCondition = " session_course_user.session_id IN ('$sessionIdListTostring') ";
- }
- $courseCondition = " course.id = $courseId";
- if (!empty($courseCodeList)) {
- $courseCodeListForSession = array_map(['Database', 'escape_string'], $courseCodeList);
- $courseCodeListForSession = implode('","', $courseCodeListForSession);
- $courseCondition = " course.code IN ('$courseCodeListForSession') ";
- }
- $sql .= ' FROM '.Database::get_main_table(TABLE_MAIN_USER).' as user ';
- $sql .= " LEFT JOIN ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)." as session_course_user
- ON
- user.id = session_course_user.user_id AND
- $sessionCondition
- INNER JOIN $course_table course
- ON session_course_user.c_id = course.id AND
- $courseCondition
- INNER JOIN $sessionTable session
- ON session_course_user.session_id = session.id
- ";
- $where[] = ' session_course_user.c_id IS NOT NULL ';
- // 2 = coach
- // 0 = student
- if (isset($filter_by_status)) {
- $filter_by_status = intval($filter_by_status);
- $filter_by_status_condition = " session_course_user.status = $filter_by_status AND ";
- }
- } else {
- if ($return_count) {
- $sql = " SELECT COUNT(*) as count";
- } else {
- if (empty($course_code)) {
- $sql = 'SELECT DISTINCT
- course.title,
- course.code,
- course.id AS c_id,
- course_rel_user.status as status_rel,
- user.id as user_id,
- user.email,
- course_rel_user.is_tutor,
- user.* ';
- } else {
- $sql = 'SELECT DISTINCT
- course_rel_user.status as status_rel,
- user.id as user_id,
- user.email,
- course_rel_user.is_tutor,
- user.* ';
- }
- }
- $sql .= " FROM ".Database::get_main_table(TABLE_MAIN_USER)." as user
- LEFT JOIN ".Database::get_main_table(TABLE_MAIN_COURSE_USER)." as course_rel_user
- ON
- user.id = course_rel_user.user_id AND
- course_rel_user.relation_type <> ".COURSE_RELATION_TYPE_RRHH."
- INNER JOIN $course_table course
- ON course_rel_user.c_id = course.id ";
- if (!empty($course_code)) {
- $sql .= " AND course_rel_user.c_id = $courseId";
- }
- $where[] = ' course_rel_user.c_id IS NOT NULL ';
- if (isset($filter_by_status) && is_numeric($filter_by_status)) {
- $filter_by_status = (int) $filter_by_status;
- $filter_by_status_condition = " course_rel_user.status = $filter_by_status AND ";
- }
- }
- $multiple_access_url = api_get_multiple_access_url();
- if ($multiple_access_url) {
- $sql .= ' LEFT JOIN '.Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER).' au
- ON (au.user_id = user.id) ';
- }
- $extraFieldWasAdded = false;
- if ($return_count && $resumed_report) {
- foreach ($extra_field as $extraField) {
- $extraFieldInfo = UserManager::get_extra_field_information_by_name($extraField);
- if (!empty($extraFieldInfo)) {
- $fieldValuesTable = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
- $sql .= " LEFT JOIN $fieldValuesTable as ufv
- ON (
- user.id = ufv.item_id AND
- (field_id = ".$extraFieldInfo['id']." OR field_id IS NULL)
- )";
- $extraFieldWasAdded = true;
- }
- }
- }
- $sql .= " WHERE $filter_by_status_condition ".implode(' OR ', $where);
- if ($multiple_access_url) {
- $current_access_url_id = api_get_current_access_url_id();
- $sql .= " AND (access_url_id = $current_access_url_id ) ";
- }
- if ($return_count && $resumed_report && $extraFieldWasAdded) {
- $sql .= ' AND field_id IS NOT NULL GROUP BY value ';
- }
- if (!empty($courseCodeList)) {
- $courseCodeList = array_map(['Database', 'escape_string'], $courseCodeList);
- $courseCodeList = implode('","', $courseCodeList);
- if (empty($sessionIdList)) {
- $sql .= ' AND course.code IN ("'.$courseCodeList.'")';
- }
- }
- if (!empty($userIdList)) {
- $userIdList = array_map('intval', $userIdList);
- $userIdList = implode('","', $userIdList);
- $sql .= ' AND user.id IN ("'.$userIdList.'")';
- }
- if (isset($filterByActive)) {
- $filterByActive = (int) $filterByActive;
- $sql .= " AND user.active = $filterByActive";
- }
- if (!empty($searchByKeyword)) {
- $searchByKeyword = Database::escape_string($searchByKeyword);
- $sql .= " AND (
- user.firstname LIKE '$searchByKeyword' OR
- user.username LIKE '$searchByKeyword' OR
- user.lastname LIKE '$searchByKeyword'
- ) ";
- }
- $sql .= " $order_by $limit";
- $rs = Database::query($sql);
- $users = [];
- $extra_fields = UserManager::get_extra_fields(
- 0,
- 100,
- null,
- null,
- true,
- true
- );
- $counter = 1;
- $count_rows = Database::num_rows($rs);
- if ($return_count && $resumed_report) {
- return $count_rows;
- }
- $table_user_field_value = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
- $tableExtraField = Database::get_main_table(TABLE_EXTRA_FIELD);
- if ($count_rows) {
- while ($user = Database::fetch_array($rs)) {
- if ($return_count) {
- return $user['count'];
- }
- $report_info = [];
- $user_info = $user;
- $user_info['status'] = $user['status'];
- if (isset($user['is_tutor'])) {
- $user_info['is_tutor'] = $user['is_tutor'];
- }
- if (!empty($session_id)) {
- $user_info['status_session'] = $user['status_session'];
- }
- $sessionId = isset($user['session_id']) ? $user['session_id'] : 0;
- $course_code = isset($user['code']) ? $user['code'] : null;
- if ($add_reports) {
- if ($resumed_report) {
- $extra = [];
- if (!empty($extra_fields)) {
- foreach ($extra_fields as $extra) {
- if (in_array($extra['1'], $extra_field)) {
- $user_data = UserManager::get_extra_user_data_by_field(
- $user['user_id'],
- $extra['1']
- );
- break;
- }
- }
- }
- $row_key = '-1';
- $name = '-';
- if (!empty($extra)) {
- if (!empty($user_data[$extra['1']])) {
- $row_key = $user_data[$extra['1']];
- $name = $user_data[$extra['1']];
- $users[$row_key]['extra_'.$extra['1']] = $name;
- }
- }
- if (empty($users[$row_key])) {
- $users[$row_key] = [];
- }
- if (!array_key_exists('training_hours', $users[$row_key])) {
- $users[$row_key]['training_hours'] = 0;
- }
- $users[$row_key]['training_hours'] += Tracking::get_time_spent_on_the_course(
- $user['user_id'],
- $courseId,
- $sessionId
- );
- if (!array_key_exists('count_users', $users[$row_key])) {
- $users[$row_key]['count_users'] = 0;
- }
- $users[$row_key]['count_users'] += $counter;
- $registered_users_with_extra_field = self::getCountRegisteredUsersWithCourseExtraField(
- $name,
- $tableExtraField,
- $table_user_field_value
- );
- $users[$row_key]['count_users_registered'] = $registered_users_with_extra_field;
- $users[$row_key]['average_hours_per_user'] = $users[$row_key]['training_hours'] / $users[$row_key]['count_users'];
- $category = Category:: load(
- null,
- null,
- $course_code,
- null,
- null,
- $sessionId
- );
- if (!isset($users[$row_key]['count_certificates'])) {
- $users[$row_key]['count_certificates'] = 0;
- }
- if (isset($category[0]) && $category[0]->is_certificate_available($user['user_id'])) {
- $users[$row_key]['count_certificates']++;
- }
- foreach ($extra_fields as $extra) {
- if ($extra['1'] == 'ruc') {
- continue;
- }
- if (!isset($users[$row_key][$extra['1']])) {
- $user_data = UserManager::get_extra_user_data_by_field($user['user_id'], $extra['1']);
- if (!empty($user_data[$extra['1']])) {
- $users[$row_key][$extra['1']] = $user_data[$extra['1']];
- }
- }
- }
- } else {
- $sessionName = !empty($sessionId) ? ' - '.$user['session_name'] : '';
- $report_info['course'] = $user['title'].$sessionName;
- $report_info['user'] = api_get_person_name($user['firstname'], $user['lastname']);
- $report_info['email'] = $user['email'];
- $report_info['time'] = api_time_to_hms(
- Tracking::get_time_spent_on_the_course(
- $user['user_id'],
- empty($user['c_id']) ? $courseId : $user['c_id'],
- $sessionId
- )
- );
- $category = Category:: load(
- null,
- null,
- $course_code,
- null,
- null,
- $sessionId
- );
- $report_info['certificate'] = Display::label(get_lang('No'));
- if (isset($category[0]) && $category[0]->is_certificate_available($user['user_id'])) {
- $report_info['certificate'] = Display::label(get_lang('Yes'), 'success');
- }
- $progress = intval(
- Tracking::get_avg_student_progress(
- $user['user_id'],
- $course_code,
- [],
- $sessionId
- )
- );
- $report_info['progress_100'] = $progress == 100 ? Display::label(get_lang('Yes'), 'success') : Display::label(get_lang('No'));
- $report_info['progress'] = $progress."%";
- foreach ($extra_fields as $extra) {
- $user_data = UserManager::get_extra_user_data_by_field($user['user_id'], $extra['1']);
- $report_info[$extra['1']] = $user_data[$extra['1']];
- }
- $report_info['user_id'] = $user['user_id'];
- $users[] = $report_info;
- }
- } else {
- $users[$user['user_id']] = $user_info;
- }
- }
- }
- return $users;
- }
- /**
- * @param bool $resumed_report
- * @param array $extra_field
- * @param array $courseCodeList
- * @param array $userIdList
- * @param array $sessionIdList
- *
- * @return array|int
- */
- public static function get_count_user_list_from_course_code(
- $resumed_report = false,
- $extra_field = [],
- $courseCodeList = [],
- $userIdList = [],
- $sessionIdList = []
- ) {
- return self::get_user_list_from_course_code(
- null,
- 0,
- null,
- null,
- null,
- true,
- false,
- $resumed_report,
- $extra_field,
- $courseCodeList,
- $userIdList,
- null,
- $sessionIdList
- );
- }
- /**
- * Gets subscribed users in a course or in a course/session.
- *
- * @param string $course_code
- * @param int $session_id
- *
- * @return int
- */
- public static function get_users_count_in_course(
- $course_code,
- $session_id = 0,
- $status = null
- ) {
- // variable initialisation
- $session_id = (int) $session_id;
- $course_code = Database::escape_string($course_code);
- $tblUser = Database::get_main_table(TABLE_MAIN_USER);
- $tblSessionCourseUser = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
- $tblCourseUser = Database::get_main_table(TABLE_MAIN_COURSE_USER);
- $tblUrlUser = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
- $courseInfo = api_get_course_info($course_code);
- $courseId = $courseInfo['real_id'];
- $sql = "
- SELECT DISTINCT count(user.id) as count
- FROM $tblUser as user
- ";
- $where = [];
- if (!empty($session_id)) {
- $sql .= "
- LEFT JOIN $tblSessionCourseUser as session_course_user
- ON user.user_id = session_course_user.user_id
- AND session_course_user.c_id = $courseId
- AND session_course_user.session_id = $session_id
- ";
- $where[] = ' session_course_user.c_id IS NOT NULL ';
- } else {
- $sql .= "
- LEFT JOIN $tblCourseUser as course_rel_user
- ON user.user_id = course_rel_user.user_id
- AND course_rel_user.relation_type <> ".COURSE_RELATION_TYPE_RRHH."
- AND course_rel_user.c_id = $courseId
- ";
- $where[] = ' course_rel_user.c_id IS NOT NULL ';
- }
- $multiple_access_url = api_get_multiple_access_url();
- if ($multiple_access_url) {
- $sql .= " LEFT JOIN $tblUrlUser au ON (au.user_id = user.user_id) ";
- }
- $sql .= ' WHERE '.implode(' OR ', $where);
- if ($multiple_access_url) {
- $current_access_url_id = api_get_current_access_url_id();
- $sql .= " AND (access_url_id = $current_access_url_id ) ";
- }
- $rs = Database::query($sql);
- $count = 0;
- if (Database::num_rows($rs)) {
- $user = Database::fetch_array($rs);
- $count = $user['count'];
- }
- return $count;
- }
- /**
- * Get a list of coaches of a course and a session.
- *
- * @param string $course_code
- * @param int $session_id
- * @param bool $addGeneralCoach
- *
- * @return array List of users
- */
- public static function get_coach_list_from_course_code(
- $course_code,
- $session_id,
- $addGeneralCoach = true
- ) {
- if (empty($course_code) || empty($session_id)) {
- return [];
- }
- $course_code = Database::escape_string($course_code);
- $courseInfo = api_get_course_info($course_code);
- $courseId = $courseInfo['real_id'];
- $session_id = (int) $session_id;
- $users = [];
- // We get the coach for the given course in a given session.
- $sql = 'SELECT user_id FROM '.Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER).
- " WHERE session_id = $session_id AND c_id = $courseId AND status = 2";
- $rs = Database::query($sql);
- while ($user = Database::fetch_array($rs)) {
- $userInfo = api_get_user_info($user['user_id']);
- if ($userInfo) {
- $users[$user['user_id']] = $userInfo;
- }
- }
- if ($addGeneralCoach) {
- $table = Database::get_main_table(TABLE_MAIN_SESSION);
- // We get the session coach.
- $sql = "SELECT id_coach FROM $table WHERE id = $session_id";
- $rs = Database::query($sql);
- $session_id_coach = Database::result($rs, 0, 'id_coach');
- if (is_int($session_id_coach)) {
- $userInfo = api_get_user_info($session_id_coach);
- if ($userInfo) {
- $users[$session_id_coach] = $userInfo;
- }
- }
- }
- return $users;
- }
- /**
- * Return user info array of all users registered in a course
- * This only returns the users that are registered in this actual course, not linked courses.
- *
- * @param string $course_code
- * @param bool $with_session
- * @param int $session_id
- * @param string $date_from
- * @param string $date_to
- * @param bool $includeInvitedUsers Whether include the invited users
- * @param int $groupId
- *
- * @return array with user id
- */
- public static function get_student_list_from_course_code(
- $course_code,
- $with_session = false,
- $session_id = 0,
- $date_from = null,
- $date_to = null,
- $includeInvitedUsers = true,
- $groupId = 0
- ) {
- $userTable = Database::get_main_table(TABLE_MAIN_USER);
- $session_id = (int) $session_id;
- $courseInfo = api_get_course_info($course_code);
- if (empty($courseInfo)) {
- return [];
- }
- $courseId = $courseInfo['real_id'];
- $students = [];
- if ($session_id == 0) {
- if (empty($groupId)) {
- // students directly subscribed to the course
- $sql = "SELECT *
- FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)." cu
- INNER JOIN $userTable u
- ON cu.user_id = u.user_id
- WHERE c_id = $courseId AND cu.status = ".STUDENT;
- if (!$includeInvitedUsers) {
- $sql .= " AND u.status != ".INVITEE;
- }
- $rs = Database::query($sql);
- while ($student = Database::fetch_array($rs)) {
- $students[$student['user_id']] = $student;
- }
- } else {
- $students = GroupManager::get_users(
- $groupId,
- false,
- null,
- null,
- false,
- $courseInfo['real_id']
- );
- $students = array_flip($students);
- }
- }
- // students subscribed to the course through a session
- if ($with_session) {
- $joinSession = '';
- //Session creation date
- if (!empty($date_from) && !empty($date_to)) {
- $joinSession = "INNER JOIN ".Database::get_main_table(TABLE_MAIN_SESSION)." s";
- }
- $sql_query = "SELECT *
- FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)." scu
- $joinSession
- INNER JOIN $userTable u ON scu.user_id = u.user_id
- WHERE scu.c_id = $courseId AND scu.status <> 2";
- if (!empty($date_from) && !empty($date_to)) {
- $date_from = Database::escape_string($date_from);
- $date_to = Database::escape_string($date_to);
- $sql_query .= " AND s.access_start_date >= '$date_from' AND s.access_end_date <= '$date_to'";
- }
- if ($session_id != 0) {
- $sql_query .= " AND scu.session_id = $session_id";
- }
- if (!$includeInvitedUsers) {
- $sql_query .= " AND u.status != ".INVITEE;
- }
- $rs = Database::query($sql_query);
- while ($student = Database::fetch_array($rs)) {
- $students[$student['user_id']] = $student;
- }
- }
- return $students;
- }
- /**
- * Return user info array of all teacher-users registered in a course
- * This only returns the users that are registered in this actual course, not linked courses.
- *
- * @param string $course_code
- *
- * @return array with user id
- */
- public static function get_teacher_list_from_course_code($course_code)
- {
- $courseInfo = api_get_course_info($course_code);
- $courseId = $courseInfo['real_id'];
- if (empty($courseId)) {
- return false;
- }
- $sql = "SELECT DISTINCT
- u.id as user_id,
- u.lastname,
- u.firstname,
- u.email,
- u.username,
- u.status
- FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)." cu
- INNER JOIN ".Database::get_main_table(TABLE_MAIN_USER)." u
- ON (cu.user_id = u.id)
- WHERE
- cu.c_id = $courseId AND
- cu.status = 1 ";
- $rs = Database::query($sql);
- $teachers = [];
- while ($teacher = Database::fetch_array($rs)) {
- $teachers[$teacher['user_id']] = $teacher;
- }
- return $teachers;
- }
- /**
- * Return user info array of all teacher-users registered in a course
- * This only returns the users that are registered in this actual course, not linked courses.
- *
- * @param int $courseId
- * @param bool $loadAvatars
- *
- * @return array with user id
- */
- public static function getTeachersFromCourse($courseId, $loadAvatars = true)
- {
- $courseId = (int) $courseId;
- if (empty($courseId)) {
- return false;
- }
- $sql = "SELECT DISTINCT
- u.id as user_id,
- u.lastname,
- u.firstname,
- u.email,
- u.username,
- u.status
- FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)." cu
- INNER JOIN ".Database::get_main_table(TABLE_MAIN_USER)." u
- ON (cu.user_id = u.id)
- WHERE
- cu.c_id = $courseId AND
- cu.status = 1 ";
- $rs = Database::query($sql);
- $listTeachers = [];
- $teachers = [];
- $url = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?a=get_user_popup&course_id='.$courseId;
- while ($teacher = Database::fetch_array($rs)) {
- $teachers['id'] = $teacher['user_id'];
- $teachers['lastname'] = $teacher['lastname'];
- $teachers['firstname'] = $teacher['firstname'];
- $teachers['email'] = $teacher['email'];
- $teachers['username'] = $teacher['username'];
- $teachers['status'] = $teacher['status'];
- $teachers['fullname'] = api_get_person_name($teacher['firstname'], $teacher['lastname']);
- $teachers['avatar'] = '';
- if ($loadAvatars) {
- $userPicture = UserManager::getUserPicture($teacher['user_id'], USER_IMAGE_SIZE_SMALL);
- $teachers['avatar'] = $userPicture;
- }
- $teachers['url'] = $url.'&user_id='.$teacher['user_id'];
- $listTeachers[] = $teachers;
- }
- return $listTeachers;
- }
- /**
- * Returns a string list of teachers assigned to the given course.
- *
- * @param string $course_code
- * @param string $separator between teachers names
- * @param bool $add_link_to_profile Whether to add a link to the teacher's profile
- * @param bool $orderList
- *
- * @return string List of teachers teaching the course
- */
- public static function getTeacherListFromCourseCodeToString(
- $course_code,
- $separator = self::USER_SEPARATOR,
- $add_link_to_profile = false,
- $orderList = false
- ) {
- $teacher_list = self::get_teacher_list_from_course_code($course_code);
- $html = '';
- $list = [];
- if (!empty($teacher_list)) {
- foreach ($teacher_list as $teacher) {
- $teacher_name = api_get_person_name(
- $teacher['firstname'],
- $teacher['lastname']
- );
- if ($add_link_to_profile) {
- $url = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?a=get_user_popup&user_id='.$teacher['user_id'];
- $teacher_name = Display::url(
- $teacher_name,
- $url,
- [
- 'class' => 'ajax',
- 'data-title' => $teacher_name,
- ]
- );
- }
- $list[] = $teacher_name;
- }
- if (!empty($list)) {
- if ($orderList === true) {
- $html .= '<ul class="user-teacher">';
- foreach ($list as $teacher) {
- $html .= '<li>';
- $html .= Display::return_icon('teacher.png', '', null, ICON_SIZE_TINY);
- $html .= ' '.$teacher;
- $html .= '</li>';
- }
- $html .= '</ul>';
- } else {
- $html .= array_to_string($list, $separator);
- }
- }
- }
- return $html;
- }
- /**
- * This function returns information about coachs from a course in session.
- *
- * @param int $session_id
- * @param int $courseId
- *
- * @return array containing user_id, lastname, firstname, username
- */
- public static function get_coachs_from_course($session_id = 0, $courseId = 0)
- {
- if (!empty($session_id)) {
- $session_id = intval($session_id);
- } else {
- $session_id = api_get_session_id();
- }
- if (!empty($courseId)) {
- $courseId = intval($courseId);
- } else {
- $courseId = api_get_course_int_id();
- }
- $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
- $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
- $sql = "SELECT DISTINCT
- u.user_id,
- u.lastname,
- u.firstname,
- u.username
- FROM $tbl_user u
- INNER JOIN $tbl_session_course_user scu
- ON (u.user_id = scu.user_id)
- WHERE
- scu.session_id = $session_id AND
- scu.c_id = $courseId AND
- scu.status = 2";
- $rs = Database::query($sql);
- $coaches = [];
- if (Database::num_rows($rs) > 0) {
- while ($row = Database::fetch_array($rs)) {
- $completeName = api_get_person_name($row['firstname'], $row['lastname']);
- $coaches[] = $row + ['full_name' => $completeName];
- }
- }
- return $coaches;
- }
- /**
- * @param int $session_id
- * @param int $courseId
- * @param string $separator
- * @param bool $add_link_to_profile
- * @param bool $orderList
- *
- * @return string
- */
- public static function get_coachs_from_course_to_string(
- $session_id = 0,
- $courseId = 0,
- $separator = self::USER_SEPARATOR,
- $add_link_to_profile = false,
- $orderList = false
- ) {
- $coachList = self::get_coachs_from_course($session_id, $courseId);
- $course_coachs = [];
- if (!empty($coachList)) {
- foreach ($coachList as $coach_course) {
- $coach_name = $coach_course['full_name'];
- if ($add_link_to_profile) {
- $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;
- $coach_name = Display::url(
- $coach_name,
- $url,
- [
- 'class' => 'ajax',
- 'data-title' => $coach_name,
- ]
- );
- }
- $course_coachs[] = $coach_name;
- }
- }
- $html = '';
- if (!empty($course_coachs)) {
- if ($orderList === true) {
- $html .= '<ul class="user-coachs">';
- foreach ($course_coachs as $coachs) {
- $html .= Display::tag(
- 'li',
- Display::return_icon(
- 'teacher.png',
- get_lang('Coach'),
- null,
- ICON_SIZE_TINY
- ).' '.$coachs
- );
- }
- $html .= '</ul>';
- } else {
- $html = array_to_string($course_coachs, $separator);
- }
- }
- return $html;
- }
- /**
- * Get the list of groups from the course.
- *
- * @param string $course_code
- * @param int $session_id Session ID (optional)
- * @param int $in_get_empty_group get empty groups (optional)
- *
- * @return array List of groups info
- */
- public static function get_group_list_of_course(
- $course_code,
- $session_id = 0,
- $in_get_empty_group = 0
- ) {
- $course_info = api_get_course_info($course_code);
- if (empty($course_info)) {
- return [];
- }
- $course_id = $course_info['real_id'];
- if (empty($course_id)) {
- return [];
- }
- $session_id != 0 ? $session_condition = ' WHERE g.session_id IN(1,'.intval($session_id).')' : $session_condition = ' WHERE g.session_id = 0';
- if ($in_get_empty_group == 0) {
- // get only groups that are not empty
- $sql = "SELECT DISTINCT g.id, g.iid, g.name
- FROM ".Database::get_course_table(TABLE_GROUP)." AS g
- INNER JOIN ".Database::get_course_table(TABLE_GROUP_USER)." gu
- ON (g.id = gu.group_id AND g.c_id = $course_id AND gu.c_id = $course_id)
- $session_condition
- ORDER BY g.name";
- } else {
- // get all groups even if they are empty
- $sql = "SELECT g.id, g.name, g.iid
- FROM ".Database::get_course_table(TABLE_GROUP)." AS g
- $session_condition
- AND c_id = $course_id";
- }
- $result = Database::query($sql);
- $groupList = [];
- while ($groupData = Database::fetch_array($result)) {
- $groupData['userNb'] = GroupManager::number_of_students($groupData['id'], $course_id);
- $groupList[$groupData['iid']] = $groupData;
- }
- return $groupList;
- }
- /**
- * Delete a course
- * This function deletes a whole course-area from the platform. When the
- * given course is a virtual course, the database and directory will not be
- * deleted.
- * When the given course is a real course, also all virtual courses refering
- * to the given course will be deleted.
- * Considering the fact that we remove all traces of the course in the main
- * database, it makes sense to remove all tracking as well (if stats databases exist)
- * so that a new course created with this code would not use the remains of an older
- * course.
- *
- * @param string $code The code of the course to delete
- *
- * @todo When deleting a virtual course: unsubscribe users from that virtual
- * course from the groups in the real course if they are not subscribed in
- * that real course.
- */
- public static function delete_course($code)
- {
- $table_course = Database::get_main_table(TABLE_MAIN_COURSE);
- $table_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
- $table_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
- $table_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
- $table_course_survey = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY);
- $table_course_survey_question = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
- $table_course_survey_question_option = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
- $table_course_rel_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
- $table_stats_hotpots = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
- $table_stats_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
- $table_stats_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
- $table_stats_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
- $table_stats_lastaccess = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
- $table_stats_course_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
- $table_stats_online = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
- $table_stats_default = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DEFAULT);
- $table_stats_downloads = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DOWNLOADS);
- $table_stats_links = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LINKS);
- $table_stats_uploads = Database::get_main_table(TABLE_STATISTIC_TRACK_E_UPLOADS);
- if (empty($code)) {
- return false;
- }
- $codeFiltered = Database::escape_string($code);
- $sql = "SELECT * FROM $table_course
- WHERE code = '$codeFiltered'";
- $res = Database::query($sql);
- if (Database::num_rows($res) == 0) {
- return;
- }
- $course = Database::fetch_array($res);
- $courseId = $course['id']; // int
- $count = 0;
- if (api_is_multiple_url_enabled()) {
- $url_id = 1;
- if (api_get_current_access_url_id() != -1) {
- $url_id = api_get_current_access_url_id();
- }
- UrlManager::delete_url_rel_course($courseId, $url_id);
- $count = UrlManager::getCountUrlRelCourse($courseId);
- }
- if ($count == 0) {
- self::create_database_dump($code);
- $course_tables = AddCourse::get_course_tables();
- // Cleaning group categories
- $groupCategories = GroupManager::get_categories($course['code']);
- if (!empty($groupCategories)) {
- foreach ($groupCategories as $category) {
- GroupManager::delete_category($category['id'], $course['code']);
- }
- }
- // Cleaning groups
- $groups = GroupManager::get_groups($courseId);
- if (!empty($groups)) {
- foreach ($groups as $group) {
- GroupManager::deleteGroup($group, $course['code']);
- }
- }
- // Cleaning c_x tables
- if (!empty($courseId)) {
- foreach ($course_tables as $table) {
- $table = Database::get_course_table($table);
- $sql = "DELETE FROM $table WHERE c_id = $courseId ";
- Database::query($sql);
- }
- }
- $course_dir = api_get_path(SYS_COURSE_PATH).$course['directory'];
- $archive_dir = api_get_path(SYS_ARCHIVE_PATH).$course['directory'].'_'.time();
- if (is_dir($course_dir)) {
- rename($course_dir, $archive_dir);
- }
- Category::deleteFromCourse($course['code']);
- // Unsubscribe all users from the course
- $sql = "DELETE FROM $table_course_user WHERE c_id = $courseId";
- Database::query($sql);
- // Delete the course from the sessions tables
- $sql = "DELETE FROM $table_session_course WHERE c_id = $courseId";
- Database::query($sql);
- $sql = "DELETE FROM $table_session_course_user WHERE c_id = $courseId";
- Database::query($sql);
- // Delete from Course - URL
- $sql = "DELETE FROM $table_course_rel_url WHERE c_id = $courseId";
- Database::query($sql);
- $sql = "SELECT survey_id FROM $table_course_survey WHERE course_code = '$codeFiltered'";
- $result_surveys = Database::query($sql);
- while ($surveys = Database::fetch_array($result_surveys)) {
- $survey_id = $surveys[0]; //int
- $sql = "DELETE FROM $table_course_survey_question WHERE survey_id = $survey_id";
- Database::query($sql);
- $sql = "DELETE FROM $table_course_survey_question_option WHERE survey_id = $survey_id";
- Database::query($sql);
- $sql = "DELETE FROM $table_course_survey WHERE survey_id = $survey_id";
- Database::query($sql);
- }
- // Delete the course from the stats tables
- $sql = "DELETE FROM $table_stats_hotpots WHERE c_id = $courseId";
- Database::query($sql);
- $sql = "DELETE FROM $table_stats_attempt WHERE c_id = $courseId";
- Database::query($sql);
- $sql = "DELETE FROM $table_stats_exercises WHERE c_id = $courseId";
- Database::query($sql);
- $sql = "DELETE FROM $table_stats_access WHERE c_id = $courseId";
- Database::query($sql);
- $sql = "DELETE FROM $table_stats_lastaccess WHERE c_id = $courseId";
- Database::query($sql);
- $sql = "DELETE FROM $table_stats_course_access WHERE c_id = $courseId";
- Database::query($sql);
- $sql = "DELETE FROM $table_stats_online WHERE c_id = $courseId";
- Database::query($sql);
- // Do not delete rows from track_e_default as these include course
- // creation and other important things that do not take much space
- // but give information on the course history
- //$sql = "DELETE FROM $table_stats_default WHERE c_id = $courseId";
- //Database::query($sql);
- $sql = "DELETE FROM $table_stats_downloads WHERE c_id = $courseId";
- Database::query($sql);
- $sql = "DELETE FROM $table_stats_links WHERE c_id = $courseId";
- Database::query($sql);
- $sql = "DELETE FROM $table_stats_uploads WHERE c_id = $courseId";
- Database::query($sql);
- // Update ticket
- $table = Database::get_main_table(TABLE_TICKET_TICKET);
- $sql = "UPDATE $table SET course_id = NULL WHERE course_id = $courseId";
- Database::query($sql);
- // Class
- $table = Database::get_main_table(TABLE_USERGROUP_REL_COURSE);
- $sql = "DELETE FROM $table
- WHERE course_id = $courseId";
- Database::query($sql);
- // Skills
- $table = Database::get_main_table(TABLE_MAIN_SKILL_REL_USER);
- $argumentation = Database::escape_string(sprintf(get_lang('SkillFromCourseXDeletedSinceThen'), $course['code']));
- $sql = "UPDATE $table SET course_id = NULL, session_id = NULL, argumentation = '$argumentation'
- WHERE course_id = $courseId";
- Database::query($sql);
- if (api_get_configuration_value('allow_skill_rel_items')) {
- $sql = "DELETE FROM skill_rel_course WHERE c_id = $courseId";
- Database::query($sql);
- }
- // Deletes all groups, group-users, group-tutors information
- // To prevent fK mix up on some tables
- GroupManager::deleteAllGroupsFromCourse($courseId);
- $app_plugin = new AppPlugin();
- $app_plugin->performActionsWhenDeletingItem('course', $courseId);
- // Delete the course from the database
- $sql = "DELETE FROM $table_course WHERE id = $courseId";
- Database::query($sql);
- // delete extra course fields
- $extraFieldValues = new ExtraFieldValue('course');
- $extraFieldValues->deleteValuesByItem($courseId);
- // Add event to system log
- Event::addEvent(
- LOG_COURSE_DELETE,
- LOG_COURSE_CODE,
- $code,
- api_get_utc_datetime(),
- api_get_user_id(),
- $courseId
- );
- }
- }
- /**
- * Creates a file called mysql_dump.sql in the course folder.
- *
- * @param string $course_code The code of the course
- *
- * @todo Implementation for single database
- */
- public static function create_database_dump($course_code)
- {
- $sql_dump = '';
- $course_code = Database::escape_string($course_code);
- $table_course = Database::get_main_table(TABLE_MAIN_COURSE);
- $sql = "SELECT * FROM $table_course WHERE code = '$course_code'";
- $res = Database::query($sql);
- $course = Database::fetch_array($res);
- $course_tables = AddCourse::get_course_tables();
- if (!empty($course['id'])) {
- //Cleaning c_x tables
- foreach ($course_tables as $table) {
- $table = Database::get_course_table($table);
- $sql = "SELECT * FROM $table WHERE c_id = {$course['id']} ";
- $res_table = Database::query($sql);
- while ($row = Database::fetch_array($res_table, 'ASSOC')) {
- $row_to_save = [];
- foreach ($row as $key => $value) {
- $row_to_save[$key] = $key."='".Database::escape_string($row[$key])."'";
- }
- $sql_dump .= "\nINSERT INTO $table SET ".implode(', ', $row_to_save).';';
- }
- }
- }
- if (is_dir(api_get_path(SYS_COURSE_PATH).$course['directory'])) {
- $file_name = api_get_path(SYS_COURSE_PATH).$course['directory'].'/mysql_dump.sql';
- $handle = fopen($file_name, 'a+');
- if ($handle !== false) {
- fwrite($handle, $sql_dump);
- fclose($handle);
- } else {
- //TODO trigger exception in a try-catch
- }
- }
- }
- /**
- * Sort courses for a specific user ??
- *
- * @param int $user_id User ID
- * @param string $course_code Course code
- *
- * @return int Minimum course order
- *
- * @todo Review documentation
- */
- public static function userCourseSort($user_id, $course_code)
- {
- if ($user_id != strval(intval($user_id))) {
- return false;
- }
- $course_code = Database::escape_string($course_code);
- $TABLECOURSE = Database::get_main_table(TABLE_MAIN_COURSE);
- $TABLECOURSUSER = Database::get_main_table(TABLE_MAIN_COURSE_USER);
- $course_title = Database::result(
- Database::query(
- "SELECT title FROM $TABLECOURSE WHERE code = '$course_code'"
- ),
- 0,
- 0
- );
- if ($course_title === false) {
- $course_title = '';
- }
- $sql = "SELECT course.code as code, course.title as title, cu.sort as sort
- FROM $TABLECOURSUSER as cu, $TABLECOURSE as course
- WHERE course.id = cu.c_id AND user_id = $user_id AND
- cu.relation_type <> ".COURSE_RELATION_TYPE_RRHH." AND
- user_course_cat = 0
- ORDER BY cu.sort";
- $result = Database::query($sql);
- $course_title_precedent = '';
- $counter = 0;
- $course_found = false;
- $course_sort = 1;
- if (Database::num_rows($result) > 0) {
- while ($courses = Database::fetch_array($result)) {
- if ($course_title_precedent == '') {
- $course_title_precedent = $courses['title'];
- }
- if (api_strcasecmp($course_title_precedent, $course_title) < 0) {
- $course_found = true;
- $course_sort = $courses['sort'];
- if ($counter == 0) {
- $sql = "UPDATE $TABLECOURSUSER
- SET sort = sort+1
- WHERE
- user_id= $user_id AND
- relation_type <> ".COURSE_RELATION_TYPE_RRHH."
- AND user_course_cat = 0
- AND sort > $course_sort";
- $course_sort++;
- } else {
- $sql = "UPDATE $TABLECOURSUSER SET sort = sort+1
- WHERE
- user_id= $user_id AND
- relation_type <> ".COURSE_RELATION_TYPE_RRHH." AND
- user_course_cat = 0 AND
- sort >= $course_sort";
- }
- Database::query($sql);
- break;
- } else {
- $course_title_precedent = $courses['title'];
- }
- $counter++;
- }
- // We must register the course in the beginning of the list
- if (!$course_found) {
- $course_sort = Database::result(
- Database::query(
- 'SELECT min(sort) as min_sort FROM '.$TABLECOURSUSER.' WHERE user_id = "'.$user_id.'" AND user_course_cat="0"'
- ),
- 0,
- 0
- );
- Database::query("UPDATE $TABLECOURSUSER SET sort = sort+1 WHERE user_id = $user_id AND user_course_cat = 0");
- }
- }
- return $course_sort;
- }
- /**
- * check if course exists.
- *
- * @param string $courseCode
- *
- * @return int if exists, false else
- */
- public static function course_exists($courseCode)
- {
- $courseCode = Database::escape_string($courseCode);
- $sql = "SELECT 1 FROM ".Database::get_main_table(TABLE_MAIN_COURSE)."
- WHERE code = '$courseCode'";
- return Database::num_rows(Database::query($sql));
- }
- /**
- * Send an email to tutor after the auth-suscription of a student in your course.
- *
- * @author Carlos Vargas <carlos.vargas@dokeos.com>, Dokeos Latino
- *
- * @param int $user_id the id of the user
- * @param string $courseId the course code
- * @param bool $send_to_tutor_also
- *
- * @return false|null we return the message that is displayed when the action is successful
- */
- public static function email_to_tutor($user_id, $courseId, $send_to_tutor_also = false)
- {
- $user_id = (int) $user_id;
- $courseId = (int) $courseId;
- $information = api_get_course_info_by_id($courseId);
- $course_code = $information['code'];
- $student = api_get_user_info($user_id);
- $name_course = $information['title'];
- $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
- WHERE c_id = $courseId";
- // TODO: Ivan: This is a mistake, please, have a look at it. Intention here is diffcult to be guessed.
- //if ($send_to_tutor_also = true)
- // Proposed change:
- if ($send_to_tutor_also) {
- $sql .= ' AND is_tutor = 1';
- } else {
- $sql .= ' AND status = 1';
- }
- $result = Database::query($sql);
- while ($row = Database::fetch_array($result)) {
- $tutor = api_get_user_info($row['user_id']);
- $emailto = $tutor['email'];
- $emailsubject = get_lang('NewUserInTheCourse').': '.$name_course;
- $emailbody = get_lang('Dear').': '.api_get_person_name($tutor['firstname'], $tutor['lastname'])."\n";
- $emailbody .= get_lang('MessageNewUserInTheCourse').': '.$name_course."\n";
- $emailbody .= get_lang('UserName').': '.$student['username']."\n";
- if (api_is_western_name_order()) {
- $emailbody .= get_lang('FirstName').': '.$student['firstname']."\n";
- $emailbody .= get_lang('LastName').': '.$student['lastname']."\n";
- } else {
- $emailbody .= get_lang('LastName').': '.$student['lastname']."\n";
- $emailbody .= get_lang('FirstName').': '.$student['firstname']."\n";
- }
- $emailbody .= get_lang('Email').': <a href="mailto:'.$student['email'].'">'.$student['email']."</a>\n\n";
- $recipient_name = api_get_person_name(
- $tutor['firstname'],
- $tutor['lastname'],
- null,
- PERSON_NAME_EMAIL_ADDRESS
- );
- $sender_name = api_get_person_name(
- api_get_setting('administratorName'),
- api_get_setting('administratorSurname'),
- null,
- PERSON_NAME_EMAIL_ADDRESS
- );
- $email_admin = api_get_setting('emailAdministrator');
- $additionalParameters = [
- 'smsType' => SmsPlugin::NEW_USER_SUBSCRIBED_COURSE,
- 'userId' => $tutor['user_id'],
- 'userUsername' => $student['username'],
- 'courseCode' => $course_code,
- ];
- api_mail_html(
- $recipient_name,
- $emailto,
- $emailsubject,
- $emailbody,
- $sender_name,
- $email_admin,
- null,
- null,
- null,
- $additionalParameters
- );
- }
- }
- /**
- * @return array
- */
- public static function get_special_course_list()
- {
- $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
- $tbl_course_field = Database::get_main_table(TABLE_EXTRA_FIELD);
- $tbl_course_field_value = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
- //we filter the courses from the URL
- $join_access_url = $where_access_url = '';
- if (api_get_multiple_access_url()) {
- $access_url_id = api_get_current_access_url_id();
- if ($access_url_id != -1) {
- $tbl_url_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
- $join_access_url = "LEFT JOIN $tbl_url_course url_rel_course
- ON url_rel_course.c_id = tcfv.item_id ";
- $where_access_url = " AND access_url_id = $access_url_id ";
- }
- }
- $extraFieldType = EntityExtraField::COURSE_FIELD_TYPE;
- // get course list auto-register
- $sql = "SELECT DISTINCT(c.id)
- FROM $tbl_course_field_value tcfv
- INNER JOIN $tbl_course_field tcf
- ON tcfv.field_id = tcf.id $join_access_url
- INNER JOIN $courseTable c
- ON (c.id = tcfv.item_id)
- WHERE
- tcf.extra_field_type = $extraFieldType AND
- tcf.variable = 'special_course' AND
- tcfv.value = 1 $where_access_url";
- $result = Database::query($sql);
- $courseList = [];
- if (Database::num_rows($result) > 0) {
- while ($row = Database::fetch_array($result)) {
- $courseList[] = $row['id'];
- }
- }
- return $courseList;
- }
- /**
- * Get the course codes that have been restricted in the catalogue, and if byUserId is set
- * then the courses that the user is allowed or not to see in catalogue.
- *
- * @param bool $allowed Either if the courses have some users that are or are not allowed to see in catalogue
- * @param int $byUserId if the courses are or are not allowed to see to the user
- *
- * @return array Course codes allowed or not to see in catalogue by some user or the user
- */
- public static function getCatalogueCourseList($allowed = true, $byUserId = -1)
- {
- $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
- $tblCourseRelUserCatalogue = Database::get_main_table(TABLE_MAIN_COURSE_CATALOGUE_USER);
- $visibility = $allowed ? 1 : 0;
- // Restriction by user id
- $currentUserRestriction = '';
- if ($byUserId > 0) {
- $byUserId = (int) $byUserId;
- $currentUserRestriction = " AND tcruc.user_id = $byUserId ";
- }
- //we filter the courses from the URL
- $joinAccessUrl = '';
- $whereAccessUrl = '';
- if (api_get_multiple_access_url()) {
- $accessUrlId = api_get_current_access_url_id();
- if ($accessUrlId != -1) {
- $tblUrlCourse = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
- $joinAccessUrl = "LEFT JOIN $tblUrlCourse url_rel_course
- ON url_rel_course.c_id = c.id ";
- $whereAccessUrl = " AND access_url_id = $accessUrlId ";
- }
- }
- // get course list auto-register
- $sql = "SELECT DISTINCT(c.code)
- FROM $tblCourseRelUserCatalogue tcruc
- INNER JOIN $courseTable c
- ON (c.id = tcruc.c_id) $joinAccessUrl
- WHERE tcruc.visible = $visibility $currentUserRestriction $whereAccessUrl";
- $result = Database::query($sql);
- $courseList = [];
- if (Database::num_rows($result) > 0) {
- while ($resultRow = Database::fetch_array($result)) {
- $courseList[] = $resultRow['code'];
- }
- }
- return $courseList;
- }
- /**
- * Get list of courses for a given user.
- *
- * @param int $user_id
- * @param bool $include_sessions Whether to include courses from session or not
- * @param bool $adminGetsAllCourses If the user is platform admin,
- * whether he gets all the courses or just his. Note: This does *not* include all sessions
- * @param bool $loadSpecialCourses
- * @param array $skipCourseList List of course ids to skip
- * @param bool $useUserLanguageFilterIfAvailable
- * @param bool $showCoursesSessionWithDifferentKey
- *
- * @return array List of codes and db name
- *
- * @author isaac flores paz
- */
- public static function get_courses_list_by_user_id(
- $user_id,
- $include_sessions = false,
- $adminGetsAllCourses = false,
- $loadSpecialCourses = true,
- $skipCourseList = [],
- $useUserLanguageFilterIfAvailable = true,
- $showCoursesSessionWithDifferentKey = false
- ) {
- $user_id = intval($user_id);
- $urlId = api_get_current_access_url_id();
- $course_list = [];
- $codes = [];
- $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
- $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
- $tbl_user_course_category = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
- $tableCourseUrl = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
- $languageCondition = '';
- $onlyInUserLanguage = api_get_configuration_value('my_courses_show_courses_in_user_language_only');
- if ($useUserLanguageFilterIfAvailable && $onlyInUserLanguage) {
- $userInfo = api_get_user_info(api_get_user_id());
- if (!empty($userInfo['language'])) {
- $languageCondition = " AND course.course_language = '".$userInfo['language']."' ";
- }
- }
- if ($adminGetsAllCourses && UserManager::is_admin($user_id)) {
- // get the whole courses list
- $sql = "SELECT DISTINCT(course.code), course.id as real_id, course.title
- FROM $tbl_course course
- INNER JOIN $tableCourseUrl url
- ON (course.id = url.c_id)
- WHERE
- url.access_url_id = $urlId
- $languageCondition
- ";
- } else {
- $withSpecialCourses = $withoutSpecialCourses = '';
- if ($loadSpecialCourses) {
- $specialCourseList = self::get_special_course_list();
- if (!empty($specialCourseList)) {
- $specialCourseToString = '"'.implode('","', $specialCourseList).'"';
- $withSpecialCourses = ' AND course.id IN ('.$specialCourseToString.')';
- $withoutSpecialCourses = ' AND course.id NOT IN ('.$specialCourseToString.')';
- }
- if (!empty($withSpecialCourses)) {
- $sql = "SELECT DISTINCT (course.code),
- course.id as real_id,
- course.category_code AS category,
- course.title
- FROM $tbl_course_user course_rel_user
- LEFT JOIN $tbl_course course
- ON course.id = course_rel_user.c_id
- LEFT JOIN $tbl_user_course_category user_course_category
- ON course_rel_user.user_course_cat = user_course_category.id
- INNER JOIN $tableCourseUrl url
- ON (course.id = url.c_id)
- WHERE url.access_url_id = $urlId
- $withSpecialCourses
- $languageCondition
- GROUP BY course.code
- ORDER BY user_course_category.sort, course.title, course_rel_user.sort ASC
- ";
- $result = Database::query($sql);
- if (Database::num_rows($result) > 0) {
- while ($result_row = Database::fetch_array($result, 'ASSOC')) {
- $result_row['special_course'] = 1;
- $course_list[] = $result_row;
- $codes[] = $result_row['real_id'];
- }
- }
- }
- }
- // get course list not auto-register. Use Distinct to avoid multiple
- // entries when a course is assigned to a HRD (DRH) as watcher
- $sql = "SELECT
- DISTINCT(course.code),
- course.id as real_id,
- course.category_code AS category,
- course.title
- FROM $tbl_course course
- INNER JOIN $tbl_course_user cru
- ON (course.id = cru.c_id)
- INNER JOIN $tableCourseUrl url
- ON (course.id = url.c_id)
- WHERE
- url.access_url_id = $urlId AND
- cru.user_id = $user_id
- $withoutSpecialCourses
- $languageCondition
- ORDER BY course.title
- ";
- }
- $result = Database::query($sql);
- if (Database::num_rows($result)) {
- while ($row = Database::fetch_array($result, 'ASSOC')) {
- if (!empty($skipCourseList)) {
- if (in_array($row['real_id'], $skipCourseList)) {
- continue;
- }
- }
- $course_list[] = $row;
- $codes[] = $row['real_id'];
- }
- }
- if ($include_sessions === true) {
- $sql = "SELECT DISTINCT (c.code),
- c.id as real_id,
- c.category_code AS category,
- s.id as session_id,
- s.name as session_name
- FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)." scu
- INNER JOIN $tbl_course c
- ON (scu.c_id = c.id)
- INNER JOIN ".Database::get_main_table(TABLE_MAIN_SESSION)." s
- ON (s.id = scu.session_id)
- WHERE user_id = $user_id ";
- $r = Database::query($sql);
- while ($row = Database::fetch_array($r, 'ASSOC')) {
- if (!empty($skipCourseList)) {
- if (in_array($row['real_id'], $skipCourseList)) {
- continue;
- }
- }
- if ($showCoursesSessionWithDifferentKey) {
- $course_list[] = $row;
- } else {
- if (!in_array($row['real_id'], $codes)) {
- $course_list[] = $row;
- }
- }
- }
- }
- return $course_list;
- }
- /**
- * Get course ID from a given course directory name.
- *
- * @param string $path Course directory (without any slash)
- *
- * @return string Course code, or false if not found
- */
- public static function getCourseCodeFromDirectory($path)
- {
- $path = Database::escape_string(str_replace('.', '', str_replace('/', '', $path)));
- $res = Database::query("SELECT code FROM ".Database::get_main_table(TABLE_MAIN_COURSE)."
- WHERE directory LIKE BINARY '$path'");
- if ($res === false) {
- return false;
- }
- if (Database::num_rows($res) != 1) {
- return false;
- }
- $row = Database::fetch_array($res);
- return $row['code'];
- }
- /**
- * Get course code(s) from visual code.
- *
- * @deprecated
- *
- * @param string Visual code
- *
- * @return array List of codes for the given visual code
- */
- public static function get_courses_info_from_visual_code($code)
- {
- $result = [];
- $sql_result = Database::query("SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE)."
- WHERE visual_code = '".Database::escape_string($code)."'");
- while ($virtual_course = Database::fetch_array($sql_result)) {
- $result[] = $virtual_course;
- }
- return $result;
- }
- /**
- * Creates a new extra field for a given course.
- *
- * @param string $variable Field's internal variable name
- * @param int $fieldType Field's type
- * @param string $displayText Field's language var name
- * @param string $default Optional. The default value
- *
- * @return int New extra field ID
- */
- public static function create_course_extra_field($variable, $fieldType, $displayText, $default = '')
- {
- $extraField = new ExtraField('course');
- $params = [
- 'variable' => $variable,
- 'field_type' => $fieldType,
- 'display_text' => $displayText,
- 'default_value' => $default,
- ];
- return $extraField->save($params);
- }
- /**
- * Update course attributes. Will only update attributes with a non-empty value.
- * Note that you NEED to check that your attributes are valid before using this function.
- *
- * @param int Course id
- * @param array Associative array with field names as keys and field values as values
- *
- * @return Doctrine\DBAL\Driver\Statement|null True if update was successful, false otherwise
- */
- public static function update_attributes($id, $attributes)
- {
- $id = (int) $id;
- $table = Database::get_main_table(TABLE_MAIN_COURSE);
- $sql = "UPDATE $table SET ";
- $i = 0;
- foreach ($attributes as $name => $value) {
- if ($value != '') {
- if ($i > 0) {
- $sql .= ", ";
- }
- $sql .= " $name = '".Database::escape_string($value)."'";
- $i++;
- }
- }
- $sql .= " WHERE id = $id";
- return Database::query($sql);
- }
- /**
- * Update an extra field value for a given course.
- *
- * @param string $course_code Course code
- * @param string $variable Field variable name
- * @param string $value Optional. Default field value
- *
- * @return bool|int An integer when register a new extra field. And boolean when update the extrafield
- */
- public static function update_course_extra_field_value($course_code, $variable, $value = '')
- {
- $courseInfo = api_get_course_info($course_code);
- $courseId = $courseInfo['real_id'];
- $extraFieldValues = new ExtraFieldValue('course');
- $params = [
- 'item_id' => $courseId,
- 'variable' => $variable,
- 'value' => $value,
- ];
- return $extraFieldValues->save($params);
- }
- /**
- * @param int $sessionId
- *
- * @return mixed
- */
- public static function get_session_category_id_by_session_id($sessionId)
- {
- if (empty($sessionId)) {
- return [];
- }
- $sessionId = intval($sessionId);
- $sql = 'SELECT sc.id session_category
- FROM '.Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY).' sc
- INNER JOIN '.Database::get_main_table(TABLE_MAIN_SESSION).' s
- ON sc.id = s.session_category_id
- WHERE s.id = '.$sessionId;
- return Database::result(
- Database::query($sql),
- 0,
- 'session_category'
- );
- }
- /**
- * Gets the value of a course extra field. Returns null if it was not found.
- *
- * @param string $variable Name of the extra field
- * @param string $code Course code
- *
- * @return string Value
- */
- public static function get_course_extra_field_value($variable, $code)
- {
- $courseInfo = api_get_course_info($code);
- $courseId = $courseInfo['real_id'];
- $extraFieldValues = new ExtraFieldValue('course');
- $result = $extraFieldValues->get_values_by_handler_and_field_variable($courseId, $variable);
- if (!empty($result['value'])) {
- return $result['value'];
- }
- return null;
- }
- /**
- * Lists details of the course description.
- *
- * @param array The course description
- * @param string The encoding
- * @param bool If true is displayed if false is hidden
- *
- * @return string The course description in html
- */
- public static function get_details_course_description_html(
- $descriptions,
- $charset,
- $action_show = true
- ) {
- $data = null;
- if (isset($descriptions) && count($descriptions) > 0) {
- foreach ($descriptions as $description) {
- $data .= '<div class="sectiontitle">';
- if (api_is_allowed_to_edit() && $action_show) {
- //delete
- $data .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=delete&description_id='.$description->id.'" onclick="javascript:if(!confirm(\''.addslashes(api_htmlentities(
- get_lang('ConfirmYourChoice'),
- ENT_QUOTES,
- $charset
- )).'\')) return false;">';
- $data .= Display::return_icon(
- 'delete.gif',
- get_lang('Delete'),
- ['style' => 'vertical-align:middle;float:right;']
- );
- $data .= '</a> ';
- //edit
- $data .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&description_id='.$description->id.'">';
- $data .= Display::return_icon(
- 'edit.png',
- get_lang('Edit'),
- ['style' => 'vertical-align:middle;float:right; padding-right:4px;'],
- ICON_SIZE_SMALL
- );
- $data .= '</a> ';
- }
- $data .= $description->title;
- $data .= '</div>';
- $data .= '<div class="sectioncomment">';
- $data .= Security::remove_XSS($description->content);
- $data .= '</div>';
- }
- } else {
- $data .= '<em>'.get_lang('ThisCourseDescriptionIsEmpty').'</em>';
- }
- return $data;
- }
- /**
- * Returns the details of a course category.
- *
- * @param string $code Category code
- *
- * @return array Course category
- */
- public static function get_course_category($code)
- {
- $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
- $code = Database::escape_string($code);
- $sql = "SELECT * FROM $table WHERE code = '$code'";
- return Database::fetch_array(Database::query($sql));
- }
- /**
- * Subscribes courses to human resource manager (Dashboard feature).
- *
- * @param int $hr_manager_id Human Resource Manager id
- * @param array $courses_list Courses code
- *
- * @return int
- */
- public static function subscribeCoursesToDrhManager($hr_manager_id, $courses_list)
- {
- $tbl_course_rel_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
- $tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
- $hr_manager_id = intval($hr_manager_id);
- $affected_rows = 0;
- //Deleting assigned courses to hrm_id
- if (api_is_multiple_url_enabled()) {
- $sql = "SELECT s.c_id FROM $tbl_course_rel_user s
- INNER JOIN $tbl_course_rel_access_url a
- ON (a.c_id = s.c_id)
- WHERE
- user_id = $hr_manager_id AND
- relation_type = ".COURSE_RELATION_TYPE_RRHH." AND
- access_url_id = ".api_get_current_access_url_id();
- } else {
- $sql = "SELECT c_id FROM $tbl_course_rel_user
- WHERE user_id = $hr_manager_id AND relation_type = ".COURSE_RELATION_TYPE_RRHH;
- }
- $result = Database::query($sql);
- if (Database::num_rows($result) > 0) {
- while ($row = Database::fetch_array($result)) {
- $sql = "DELETE FROM $tbl_course_rel_user
- WHERE
- c_id = {$row['c_id']} AND
- user_id = $hr_manager_id AND
- relation_type = ".COURSE_RELATION_TYPE_RRHH;
- Database::query($sql);
- }
- }
- // inserting new courses list
- if (is_array($courses_list)) {
- foreach ($courses_list as $course_code) {
- $courseInfo = api_get_course_info($course_code);
- $courseId = $courseInfo['real_id'];
- $sql = "INSERT IGNORE INTO $tbl_course_rel_user(c_id, user_id, status, relation_type)
- VALUES($courseId, $hr_manager_id, ".DRH.", ".COURSE_RELATION_TYPE_RRHH.")";
- $result = Database::query($sql);
- if (Database::affected_rows($result)) {
- $affected_rows++;
- }
- }
- }
- return $affected_rows;
- }
- /**
- * get courses followed by human resources manager.
- *
- * @param int $user_id
- * @param int $status
- * @param int $from
- * @param int $limit
- * @param string $column
- * @param string $direction
- * @param bool $getCount
- *
- * @return array courses
- */
- public static function get_courses_followed_by_drh(
- $user_id,
- $status = DRH,
- $from = null,
- $limit = null,
- $column = null,
- $direction = null,
- $getCount = false
- ) {
- return self::getCoursesFollowedByUser(
- $user_id,
- $status,
- $from,
- $limit,
- $column,
- $direction,
- $getCount
- );
- }
- /**
- * get courses followed by user.
- *
- * @param int $user_id
- * @param int $status
- * @param int $from
- * @param int $limit
- * @param string $column
- * @param string $direction
- * @param bool $getCount
- * @param string $keyword
- * @param int $sessionId
- * @param bool $showAllAssignedCourses
- *
- * @return array courses
- */
- public static function getCoursesFollowedByUser(
- $user_id,
- $status = null,
- $from = null,
- $limit = null,
- $column = null,
- $direction = null,
- $getCount = false,
- $keyword = null,
- $sessionId = 0,
- $showAllAssignedCourses = false
- ) {
- // Database Table Definitions
- $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
- $tbl_course_rel_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
- $tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
- $sessionId = (int) $sessionId;
- $user_id = (int) $user_id;
- $select = "SELECT DISTINCT c.*, c.id as real_id ";
- if ($getCount) {
- $select = "SELECT COUNT(DISTINCT c.id) as count";
- }
- $whereConditions = '';
- switch ($status) {
- case COURSEMANAGER:
- $whereConditions .= " AND cru.user_id = $user_id";
- if (!$showAllAssignedCourses) {
- $whereConditions .= " AND cru.status = ".COURSEMANAGER;
- } else {
- $whereConditions .= " AND relation_type = ".COURSE_RELATION_TYPE_COURSE_MANAGER;
- }
- break;
- case DRH:
- $whereConditions .= " AND
- cru.user_id = $user_id AND
- cru.status = ".DRH." AND
- relation_type = '".COURSE_RELATION_TYPE_RRHH."'
- ";
- break;
- }
- $keywordCondition = null;
- if (!empty($keyword)) {
- $keyword = Database::escape_string($keyword);
- $keywordCondition = " AND (c.code LIKE '%$keyword%' OR c.title LIKE '%$keyword%' ) ";
- }
- $orderBy = null;
- $extraInnerJoin = null;
- if (!empty($sessionId)) {
- if ($status == COURSEMANAGER) {
- // Teacher of course or teacher inside session
- $whereConditions = " AND (cru.status = ".COURSEMANAGER." OR srcru.status = 2) ";
- }
- $courseList = SessionManager::get_course_list_by_session_id($sessionId);
- if (!empty($courseList)) {
- $courseListToString = implode("','", array_keys($courseList));
- $whereConditions .= " AND c.id IN ('".$courseListToString."')";
- }
- $tableSessionRelCourse = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
- $tableSessionRelCourseRelUser = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
- $orderBy = ' ORDER BY position';
- $extraInnerJoin = " INNER JOIN $tableSessionRelCourse src
- ON (c.id = src.c_id AND src.session_id = $sessionId)
- INNER JOIN $tableSessionRelCourseRelUser srcru
- ON (src.session_id = srcru.session_id AND srcru.c_id = src.c_id)
- ";
- }
- $whereConditions .= $keywordCondition;
- $sql = "$select
- FROM $tbl_course c
- INNER JOIN $tbl_course_rel_user cru
- ON (cru.c_id = c.id)
- INNER JOIN $tbl_course_rel_access_url a
- ON (a.c_id = c.id)
- $extraInnerJoin
- WHERE
- access_url_id = ".api_get_current_access_url_id()."
- $whereConditions
- $orderBy
- ";
- if (isset($from) && isset($limit)) {
- $from = intval($from);
- $limit = intval($limit);
- $sql .= " LIMIT $from, $limit";
- }
- $result = Database::query($sql);
- if ($getCount) {
- $row = Database::fetch_array($result);
- return $row['count'];
- }
- $courses = [];
- if (Database::num_rows($result) > 0) {
- while ($row = Database::fetch_array($result)) {
- $courses[$row['code']] = $row;
- }
- }
- return $courses;
- }
- /**
- * check if a course is special (autoregister).
- *
- * @param int $courseId
- *
- * @return bool
- */
- public static function isSpecialCourse($courseId)
- {
- $extraFieldValue = new ExtraFieldValue('course');
- $result = $extraFieldValue->get_values_by_handler_and_field_variable(
- $courseId,
- 'special_course'
- );
- if (!empty($result)) {
- if ($result['value'] == 1) {
- return true;
- }
- }
- return false;
- }
- /**
- * Update course picture.
- *
- * @param array $courseInfo
- * @param string File name
- * @param string the full system name of the image
- * from which course picture will be created
- * @param string $cropParameters Optional string that contents "x,y,width,height" of a cropped image format
- *
- * @return bool Returns the resulting. In case of internal error or negative validation returns FALSE.
- */
- public static function update_course_picture(
- $courseInfo,
- $filename,
- $source_file = null,
- $cropParameters = null
- ) {
- if (empty($courseInfo)) {
- return false;
- }
- // course path
- $store_path = api_get_path(SYS_COURSE_PATH).$courseInfo['path'];
- // image name for courses
- $course_image = $store_path.'/course-pic.png';
- $course_medium_image = $store_path.'/course-pic85x85.png';
- if (file_exists($course_image)) {
- unlink($course_image);
- }
- if (file_exists($course_medium_image)) {
- unlink($course_medium_image);
- }
- //Crop the image to adjust 4:3 ratio
- $image = new Image($source_file);
- $image->crop($cropParameters);
- //Resize the images in two formats
- $medium = new Image($source_file);
- $medium->resize(85);
- $medium->send_image($course_medium_image, -1, 'png');
- $normal = new Image($source_file);
- $normal->resize(400);
- $normal->send_image($course_image, -1, 'png');
- $result = $medium && $normal;
- return $result ? $result : false;
- }
- /**
- * Deletes the course picture.
- *
- * @param string $courseCode
- */
- public static function deleteCoursePicture($courseCode)
- {
- $course_info = api_get_course_info($courseCode);
- // course path
- $storePath = api_get_path(SYS_COURSE_PATH).$course_info['path'];
- // image name for courses
- $courseImage = $storePath.'/course-pic.png';
- $courseMediumImage = $storePath.'/course-pic85x85.png';
- $courseSmallImage = $storePath.'/course-pic32.png';
- if (file_exists($courseImage)) {
- unlink($courseImage);
- }
- if (file_exists($courseMediumImage)) {
- unlink($courseMediumImage);
- }
- if (file_exists($courseSmallImage)) {
- unlink($courseSmallImage);
- }
- }
- /**
- * Display special courses (and only these) as several HTML divs of class userportal-course-item.
- *
- * Special courses are courses that stick on top of the list and are "auto-registerable"
- * in the sense that any user clicking them is registered as a student
- *
- * @param int $user_id User id
- * @param bool $load_dirs Whether to show the document quick-loader or not
- * @param bool $useUserLanguageFilterIfAvailable
- *
- * @return array
- */
- public static function returnSpecialCourses(
- $user_id,
- $load_dirs = false,
- $useUserLanguageFilterIfAvailable = true
- ) {
- $user_id = (int) $user_id;
- $table = Database::get_main_table(TABLE_MAIN_COURSE);
- $specialCourseList = self::get_special_course_list();
- if (empty($specialCourseList)) {
- return [];
- }
- // Filter by language
- $languageCondition = '';
- $onlyInUserLanguage = api_get_configuration_value('my_courses_show_courses_in_user_language_only');
- if ($useUserLanguageFilterIfAvailable && $onlyInUserLanguage) {
- $userInfo = api_get_user_info(api_get_user_id());
- if (!empty($userInfo['language'])) {
- $languageCondition = " AND course_language = '".$userInfo['language']."' ";
- }
- }
- $sql = "SELECT
- id,
- code,
- subscribe subscr,
- unsubscribe unsubscr
- FROM $table
- WHERE
- id IN ('".implode("','", $specialCourseList)."')
- $languageCondition
- GROUP BY code";
- $rs_special_course = Database::query($sql);
- $number_of_courses = Database::num_rows($rs_special_course);
- $showCustomIcon = api_get_setting('course_images_in_courses_list');
- $courseList = [];
- if ($number_of_courses > 0) {
- while ($course = Database::fetch_array($rs_special_course)) {
- $course_info = api_get_course_info($course['code']);
- $courseId = $course_info['real_id'];
- if ($course_info['visibility'] == COURSE_VISIBILITY_HIDDEN) {
- continue;
- }
- $params = [];
- //Param (course_code) needed to get the student info in page "My courses"
- $params['course_code'] = $course['code'];
- $params['code'] = $course['code'];
- // Get notifications.
- $course_info['id_session'] = null;
- $courseUserInfo = self::getUserCourseInfo($user_id, $courseId);
- if (empty($courseUserInfo)) {
- $course_info['status'] = STUDENT;
- } else {
- $course_info['status'] = $courseUserInfo['status'];
- }
- $show_notification = !api_get_configuration_value('hide_course_notification')
- ? Display::show_notification($course_info)
- : '';
- $params['edit_actions'] = '';
- $params['document'] = '';
- if (api_is_platform_admin()) {
- $params['edit_actions'] .= api_get_path(WEB_CODE_PATH).'course_info/infocours.php?cidReq='.$course['code'];
- if ($load_dirs) {
- $params['document'] = '<a id="document_preview_'.$courseId.'_0" class="document_preview btn btn-default btn-sm" href="javascript:void(0);">'
- .Display::returnFontAwesomeIcon('folder-open').'</a>';
- $params['document'] .= Display::div('', ['id' => 'document_result_'.$courseId.'_0', 'class' => 'document_preview_container']);
- }
- } else {
- if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED && $load_dirs) {
- $params['document'] = '<a id="document_preview_'.$courseId.'_0" class="document_preview btn btn-default btn-sm" href="javascript:void(0);">'
- .Display::returnFontAwesomeIcon('folder-open').'</a>';
- $params['document'] .= Display::div('', ['id' => 'document_result_'.$courseId.'_0', 'class' => 'document_preview_container']);
- }
- }
- $params['visibility'] = $course_info['visibility'];
- $params['status'] = $course_info['status'];
- $params['category'] = $course_info['categoryName'];
- $params['category_code'] = $course_info['categoryCode'];
- $params['icon'] = Display::return_icon(
- 'drawing-pin.png',
- null,
- null,
- ICON_SIZE_LARGE,
- null
- );
- if (api_get_setting('display_coursecode_in_courselist') == 'true') {
- $params['code_course'] = '('.$course_info['visual_code'].')';
- }
- $params['title'] = $course_info['title'];
- $params['title_cut'] = $course_info['title'];
- $params['link'] = $course_info['course_public_url'].'?id_session=0&autoreg=1';
- if (api_get_setting('display_teacher_in_courselist') === 'true') {
- $params['teachers'] = self::getTeachersFromCourse(
- $courseId,
- true
- );
- }
- if ($showCustomIcon === 'true') {
- $params['thumbnails'] = $course_info['course_image'];
- $params['image'] = $course_info['course_image_large'];
- }
- if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED) {
- $params['notifications'] = $show_notification;
- }
- $params['is_special_course'] = true;
- $courseList[] = $params;
- }
- }
- return $courseList;
- }
- /**
- * Display courses (without special courses) as several HTML divs
- * of course categories, as class userportal-catalog-item.
- *
- * @uses \displayCoursesInCategory() to display the courses themselves
- *
- * @param int $user_id
- * @param bool $load_dirs Whether to show the document quick-loader or not
- * @param bool $useUserLanguageFilterIfAvailable
- *
- * @return array
- */
- public static function returnCourses(
- $user_id,
- $load_dirs = false,
- $useUserLanguageFilterIfAvailable = true
- ) {
- $user_id = (int) $user_id;
- if (empty($user_id)) {
- $user_id = api_get_user_id();
- }
- // Step 1: We get all the categories of the user
- $table = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
- $sql = "SELECT * FROM $table
- WHERE user_id = $user_id
- ORDER BY sort ASC";
- $result = Database::query($sql);
- $listItems = [
- 'in_category' => [],
- 'not_category' => [],
- ];
- $collapsable = api_get_configuration_value('allow_user_course_category_collapsable');
- $stok = Security::get_token();
- while ($row = Database::fetch_array($result)) {
- // We simply display the title of the category.
- $courseInCategory = self::returnCoursesCategories(
- $row['id'],
- $load_dirs,
- $user_id,
- $useUserLanguageFilterIfAvailable
- );
- $collapsed = 0;
- $collapsableLink = '';
- if ($collapsable) {
- $url = api_get_path(WEB_CODE_PATH).
- 'auth/courses.php?categoryid='.$row['id'].'&sec_token='.$stok.'&redirect=home';
- $collapsed = isset($row['collapsed']) && $row['collapsed'] ? 1 : 0;
- if ($collapsed === 0) {
- $collapsableLink = Display::url(
- '<i class="fa fa-folder-open"></i>',
- $url.'&action=set_collapsable&option=1'
- );
- } else {
- $collapsableLink = Display::url(
- '<i class="fa fa-folder"></i>',
- $url.'&action=set_collapsable&option=0'
- );
- }
- }
- $params = [
- 'id_category' => $row['id'],
- 'title_category' => $row['title'],
- 'collapsed' => $collapsed,
- 'collapsable_link' => $collapsableLink,
- 'courses' => $courseInCategory,
- ];
- $listItems['in_category'][] = $params;
- }
- // Step 2: We display the course without a user category.
- $coursesNotCategory = self::returnCoursesCategories(
- 0,
- $load_dirs,
- $user_id,
- $useUserLanguageFilterIfAvailable
- );
- if ($coursesNotCategory) {
- $listItems['not_category'] = $coursesNotCategory;
- }
- return $listItems;
- }
- /**
- * Display courses inside a category (without special courses) as HTML dics of
- * class userportal-course-item.
- *
- * @param int $user_category_id User category id
- * @param bool $load_dirs Whether to show the document quick-loader or not
- * @param int $user_id
- * @param bool $useUserLanguageFilterIfAvailable
- *
- * @return array
- */
- public static function returnCoursesCategories(
- $user_category_id,
- $load_dirs = false,
- $user_id = 0,
- $useUserLanguageFilterIfAvailable = true
- ) {
- $user_id = $user_id ? (int) $user_id : api_get_user_id();
- $user_category_id = (int) $user_category_id;
- // Table definitions
- $TABLECOURS = Database::get_main_table(TABLE_MAIN_COURSE);
- $TABLECOURSUSER = Database::get_main_table(TABLE_MAIN_COURSE_USER);
- $TABLE_ACCESS_URL_REL_COURSE = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
- $current_url_id = api_get_current_access_url_id();
- // Get course list auto-register
- $special_course_list = self::get_special_course_list();
- $without_special_courses = '';
- if (!empty($special_course_list)) {
- $without_special_courses = ' AND course.id NOT IN ("'.implode('","', $special_course_list).'")';
- }
- $userCategoryCondition = " (course_rel_user.user_course_cat = $user_category_id) ";
- if (empty($user_category_id)) {
- $userCategoryCondition = ' (course_rel_user.user_course_cat = 0 OR course_rel_user.user_course_cat IS NULL) ';
- }
- $languageCondition = '';
- $onlyInUserLanguage = api_get_configuration_value('my_courses_show_courses_in_user_language_only');
- if ($useUserLanguageFilterIfAvailable && $onlyInUserLanguage) {
- $userInfo = api_get_user_info(api_get_user_id());
- if (!empty($userInfo['language'])) {
- $languageCondition = " AND course.course_language = '".$userInfo['language']."' ";
- }
- }
- $sql = "SELECT DISTINCT
- course.id,
- course_rel_user.status status,
- course.code as course_code,
- user_course_cat,
- course_rel_user.sort
- FROM $TABLECOURS course
- INNER JOIN $TABLECOURSUSER course_rel_user
- ON (course.id = course_rel_user.c_id)
- INNER JOIN $TABLE_ACCESS_URL_REL_COURSE url
- ON (url.c_id = course.id)
- WHERE
- course_rel_user.user_id = $user_id AND
- $userCategoryCondition
- $without_special_courses
- $languageCondition
- ";
- // If multiple URL access mode is enabled, only fetch courses
- // corresponding to the current URL.
- if (api_get_multiple_access_url() && $current_url_id != -1) {
- $sql .= " AND access_url_id = $current_url_id";
- }
- // Use user's classification for courses (if any).
- $sql .= ' ORDER BY course_rel_user.user_course_cat, course_rel_user.sort ASC';
- $result = Database::query($sql);
- $showCustomIcon = api_get_setting('course_images_in_courses_list');
- // Browse through all courses.
- $courseAdded = [];
- $courseList = [];
- while ($row = Database::fetch_array($result)) {
- $course_info = api_get_course_info_by_id($row['id']);
- if (empty($course_info)) {
- continue;
- }
- if (isset($course_info['visibility']) &&
- $course_info['visibility'] == COURSE_VISIBILITY_HIDDEN
- ) {
- continue;
- }
- // Skip if already in list
- if (in_array($course_info['real_id'], $courseAdded)) {
- continue;
- }
- $course_info['id_session'] = null;
- $course_info['status'] = $row['status'];
- // For each course, get if there is any notification icon to show
- // (something that would have changed since the user's last visit).
- $showNotification = !api_get_configuration_value('hide_course_notification')
- ? Display::show_notification($course_info)
- : '';
- $iconName = basename($course_info['course_image']);
- $params = [];
- //Param (course_code) needed to get the student process
- $params['course_code'] = $row['course_code'];
- $params['code'] = $row['course_code'];
- if ($showCustomIcon === 'true' && $iconName != 'course.png') {
- $params['thumbnails'] = $course_info['course_image'];
- $params['image'] = $course_info['course_image_large'];
- }
- $thumbnails = null;
- $image = null;
- if ($showCustomIcon === 'true' && $iconName != 'course.png') {
- $thumbnails = $course_info['course_image'];
- $image = $course_info['course_image_large'];
- } else {
- $image = Display::return_icon(
- 'session_default.png',
- null,
- null,
- null,
- null,
- true
- );
- }
- $params['course_id'] = $course_info['real_id'];
- $params['edit_actions'] = '';
- $params['document'] = '';
- if (api_is_platform_admin()) {
- $params['edit_actions'] .= api_get_path(WEB_CODE_PATH).'course_info/infocours.php?cidReq='.$course_info['code'];
- if ($load_dirs) {
- $params['document'] = '<a id="document_preview_'.$course_info['real_id'].'_0" class="document_preview btn btn-default btn-sm" href="javascript:void(0);">'
- .Display::returnFontAwesomeIcon('folder-open').'</a>';
- $params['document'] .= Display::div(
- '',
- [
- 'id' => 'document_result_'.$course_info['real_id'].'_0',
- 'class' => 'document_preview_container',
- ]
- );
- }
- }
- if ($load_dirs) {
- $params['document'] = '<a id="document_preview_'.$course_info['real_id'].'_0" class="document_preview btn btn-default btn-sm" href="javascript:void(0);">'
- .Display::returnFontAwesomeIcon('folder-open').'</a>';
- $params['document'] .= Display::div(
- '',
- [
- 'id' => 'document_result_'.$course_info['real_id'].'_0',
- 'class' => 'document_preview_container',
- ]
- );
- }
- $courseUrl = api_get_path(WEB_COURSE_PATH).$course_info['path'].'/index.php?id_session=0';
- $teachers = [];
- if (api_get_setting('display_teacher_in_courselist') === 'true') {
- $teachers = self::getTeachersFromCourse(
- $course_info['real_id'],
- true
- );
- }
- $params['status'] = $row['status'];
- if (api_get_setting('display_coursecode_in_courselist') === 'true') {
- $params['code_course'] = '('.$course_info['visual_code'].') ';
- }
- $params['current_user_is_teacher'] = false;
- /** @var array $teacher */
- foreach ($teachers as $teacher) {
- if ($teacher['id'] != $user_id) {
- continue;
- }
- $params['current_user_is_teacher'] = true;
- }
- $params['visibility'] = $course_info['visibility'];
- $params['link'] = $courseUrl;
- $params['thumbnails'] = $thumbnails;
- $params['image'] = $image;
- $params['title'] = $course_info['title'];
- $params['title_cut'] = $params['title'];
- $params['category'] = $course_info['categoryName'];
- $params['category_code'] = $course_info['categoryCode'];
- $params['teachers'] = $teachers;
- $params['real_id'] = $course_info['real_id'];
- if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED) {
- $params['notifications'] = $showNotification;
- }
- $courseAdded[] = $course_info['real_id'];
- $courseList[] = $params;
- }
- return $courseList;
- }
- /**
- * Retrieves the user defined course categories.
- *
- * @param int $userId
- *
- * @return array
- */
- public static function get_user_course_categories($userId = 0)
- {
- $userId = empty($userId) ? api_get_user_id() : (int) $userId;
- $table = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
- $sql = "SELECT * FROM $table
- WHERE user_id = $userId
- ORDER BY sort ASC
- ";
- $result = Database::query($sql);
- $output = [];
- while ($row = Database::fetch_array($result, 'ASSOC')) {
- $output[$row['id']] = $row;
- }
- return $output;
- }
- /**
- * Return an array the user_category id and title for the course $courseId for user $userId.
- *
- * @param $userId
- * @param $courseId
- *
- * @return array
- */
- public static function getUserCourseCategoryForCourse($userId, $courseId)
- {
- $tblCourseRelUser = Database::get_main_table(TABLE_MAIN_COURSE_USER);
- $tblUserCategory = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
- $courseId = intval($courseId);
- $userId = intval($userId);
- $sql = "SELECT user_course_cat, title
- FROM $tblCourseRelUser cru
- LEFT JOIN $tblUserCategory ucc
- ON cru.user_course_cat = ucc.id
- WHERE
- cru.user_id = $userId AND c_id = $courseId ";
- $res = Database::query($sql);
- $data = [];
- if (Database::num_rows($res) > 0) {
- $data = Database::fetch_assoc($res);
- }
- return $data;
- }
- /**
- * Get the course id based on the original id and field name in the extra fields.
- * Returns 0 if course was not found.
- *
- * @param string $value Original course code
- * @param string $variable Original field name
- *
- * @return array
- */
- public static function getCourseInfoFromOriginalId($value, $variable)
- {
- $extraFieldValue = new ExtraFieldValue('course');
- $result = $extraFieldValue->get_item_id_from_field_variable_and_field_value(
- $variable,
- $value
- );
- if (!empty($result)) {
- $courseInfo = api_get_course_info_by_id($result['item_id']);
- return $courseInfo;
- }
- return [];
- }
- /**
- * Display code for one specific course a logged in user is subscribed to.
- * Shows a link to the course, what's new icons...
- *
- * $my_course['d'] - course directory
- * $my_course['i'] - course title
- * $my_course['c'] - visual course code
- * $my_course['k'] - system course code
- *
- * @param array Course details
- * @param int Session ID
- * @param string CSS class to apply to course entry
- * @param bool Whether the session is supposedly accessible now
- * (not in the case it has passed and is in invisible/unaccessible mode)
- * @param bool Whether to show the document quick-loader or not
- *
- * @return string The HTML to be printed for the course entry
- *
- * @version 1.0.3
- *
- * @todo refactor into different functions for database calls | logic | display
- * @todo replace single-character $my_course['d'] indices
- * @todo move code for what's new icons to a separate function to clear things up
- * @todo add a parameter user_id so that it is possible to show the
- * courselist of other users (=generalisation).
- * This will prevent having to write a new function for this.
- */
- public static function get_logged_user_course_html(
- $course,
- $session_id = 0,
- $class = 'courses',
- $session_accessible = true,
- $load_dirs = false
- ) {
- $now = date('Y-m-d h:i:s');
- $user_id = api_get_user_id();
- $course_info = api_get_course_info_by_id($course['real_id']);
- $course_visibility = (int) $course_info['visibility'];
- if ($course_visibility === COURSE_VISIBILITY_HIDDEN) {
- return '';
- }
- $userInCourseStatus = self::getUserInCourseStatus(
- $user_id,
- $course_info['real_id']
- );
- $course_info['status'] = empty($session_id) ? $userInCourseStatus : STUDENT;
- $course_info['id_session'] = $session_id;
- $is_coach = api_is_coach($session_id, $course_info['real_id']);
- // Display course entry.
- // Show a hyperlink to the course, unless the course is closed and user is not course admin.
- $session_url = '';
- $params = [];
- $params['icon'] = Display::return_icon(
- 'blackboard_blue.png',
- null,
- [],
- ICON_SIZE_LARGE,
- null,
- true
- );
- $params['real_id'] = $course_info['real_id'];
- // Display the "what's new" icons
- $notifications = '';
- if (
- ($course_visibility != COURSE_VISIBILITY_CLOSED && $course_visibility != COURSE_VISIBILITY_HIDDEN) ||
- !api_get_configuration_value('hide_course_notification')
- ) {
- $notifications .= Display::show_notification($course_info);
- }
- if ($session_accessible) {
- if ($course_visibility != COURSE_VISIBILITY_CLOSED ||
- $userInCourseStatus == COURSEMANAGER
- ) {
- if (empty($course_info['id_session'])) {
- $course_info['id_session'] = 0;
- }
- $sessionCourseAvailable = false;
- $sessionCourseStatus = api_get_session_visibility($session_id, $course_info['real_id']);
- if (in_array(
- $sessionCourseStatus,
- [SESSION_VISIBLE_READ_ONLY, SESSION_VISIBLE, SESSION_AVAILABLE]
- )) {
- $sessionCourseAvailable = true;
- }
- if ($userInCourseStatus === COURSEMANAGER || $sessionCourseAvailable) {
- $session_url = $course_info['course_public_url'].'?id_session='.$course_info['id_session'];
- $session_title = '<a title="'.$course_info['name'].'" href="'.$session_url.'">'.
- $course_info['name'].'</a>'.$notifications;
- } else {
- $session_title = $course_info['name'];
- }
- } else {
- $session_title =
- $course_info['name'].' '.
- Display::tag('span', get_lang('CourseClosed'), ['class' => 'item_closed']);
- }
- } else {
- $session_title = $course_info['name'];
- }
- $thumbnails = null;
- $image = null;
- $showCustomIcon = api_get_setting('course_images_in_courses_list');
- $iconName = basename($course_info['course_image']);
- if ($showCustomIcon === 'true' && $iconName != 'course.png') {
- $thumbnails = $course_info['course_image'];
- $image = $course_info['course_image_large'];
- } else {
- $image = Display::return_icon(
- 'session_default.png',
- null,
- null,
- null,
- null,
- true
- );
- }
- $params['thumbnails'] = $thumbnails;
- $params['image'] = $image;
- $params['link'] = $session_url;
- $params['title'] = $session_title;
- $params['name'] = $course_info['name'];
- $params['edit_actions'] = '';
- $params['document'] = '';
- $params['category'] = $course_info['categoryName'];
- if ($course_visibility != COURSE_VISIBILITY_CLOSED &&
- $course_visibility != COURSE_VISIBILITY_HIDDEN
- ) {
- if (api_is_platform_admin()) {
- $params['edit_actions'] .= api_get_path(WEB_CODE_PATH).'course_info/infocours.php?cidReq='.$course_info['code'];
- if ($load_dirs) {
- $params['document'] .= '<a
- id="document_preview_'.$course_info['real_id'].'_'.$course_info['id_session'].'"
- class="document_preview btn btn-default btn-sm"
- href="javascript:void(0);">'.
- Display::returnFontAwesomeIcon('folder-open').'</a>';
- $params['document'] .= Display::div('', [
- 'id' => 'document_result_'.$course_info['real_id'].'_'.$course_info['id_session'],
- 'class' => 'document_preview_container',
- ]);
- }
- }
- }
- if (api_get_setting('display_teacher_in_courselist') === 'true') {
- $teacher_list = self::getTeachersFromCourse(
- $course_info['real_id'],
- true
- );
- $course_coachs = self::get_coachs_from_course(
- $course_info['id_session'],
- $course_info['real_id']
- );
- $params['teachers'] = $teacher_list;
- if (($course_info['status'] == STUDENT && !empty($course_info['id_session'])) ||
- ($is_coach && $course_info['status'] != COURSEMANAGER)
- ) {
- $params['coaches'] = $course_coachs;
- }
- }
- $special = isset($course['special_course']) ? true : false;
- $params['title'] = $session_title;
- $params['special'] = $special;
- if (api_get_setting('display_coursecode_in_courselist') === 'true') {
- $params['visual_code'] = '('.$course_info['visual_code'].')';
- }
- $params['extra'] = '';
- $html = $params;
- $session_category_id = null;
- if (1) {
- $session = '';
- $active = false;
- if (!empty($course_info['id_session'])) {
- $session = api_get_session_info($course_info['id_session']);
- $sessionCoachName = '';
- if (!empty($session['id_coach'])) {
- $coachInfo = api_get_user_info($session['id_coach']);
- $sessionCoachName = $coachInfo['complete_name'];
- }
- $session_category_id = self::get_session_category_id_by_session_id($course_info['id_session']);
- if (
- $session['access_start_date'] === '0000-00-00 00:00:00' || empty($session['access_start_date']) ||
- $session['access_start_date'] === '0000-00-00'
- ) {
- $session['dates'] = '';
- if (api_get_setting('show_session_coach') === 'true') {
- $session['coach'] = get_lang('GeneralCoach').': '.$sessionCoachName;
- }
- $active = true;
- } else {
- $session['dates'] = ' - '.
- get_lang('From').' '.$session['access_start_date'].' '.
- get_lang('To').' '.$session['access_end_date'];
- if (api_get_setting('show_session_coach') === 'true') {
- $session['coach'] = get_lang('GeneralCoach').': '.$sessionCoachName;
- }
- $date_start = $session['access_start_date'];
- $date_end = $session['access_end_date'];
- $active = !$date_end ? ($date_start <= $now) : ($date_start <= $now && $date_end >= $now);
- }
- }
- $user_course_category = '';
- if (isset($course_info['user_course_cat'])) {
- $user_course_category = $course_info['user_course_cat'];
- }
- $output = [
- $user_course_category,
- $html,
- $course_info['id_session'],
- $session,
- 'active' => $active,
- 'session_category_id' => $session_category_id,
- ];
- if (Skill::isAllowed($user_id, false)) {
- $em = Database::getManager();
- $objUser = api_get_user_entity($user_id);
- /** @var Course $objCourse */
- $objCourse = $em->find('ChamiloCoreBundle:Course', $course['real_id']);
- $objSession = $em->find('ChamiloCoreBundle:Session', $session_id);
- $skill = $em->getRepository('ChamiloCoreBundle:Skill')->getLastByUser($objUser, $objCourse, $objSession);
- $output['skill'] = null;
- if ($skill) {
- $output['skill']['name'] = $skill->getName();
- $output['skill']['icon'] = $skill->getIcon();
- }
- }
- } else {
- $output = [$course_info['user_course_cat'], $html];
- }
- return $output;
- }
- /**
- * @param string $source_course_code
- * @param int $source_session_id
- * @param string $destination_course_code
- * @param int $destination_session_id
- * @param array $params
- *
- * @return bool
- */
- public static function copy_course(
- $source_course_code,
- $source_session_id,
- $destination_course_code,
- $destination_session_id,
- $params = []
- ) {
- $course_info = api_get_course_info($source_course_code);
- if (!empty($course_info)) {
- $cb = new CourseBuilder('', $course_info);
- $course = $cb->build($source_session_id, $source_course_code, true);
- $course_restorer = new CourseRestorer($course);
- $course_restorer->skip_content = $params;
- $course_restorer->restore(
- $destination_course_code,
- $destination_session_id,
- true,
- true
- );
- return true;
- }
- return false;
- }
- /**
- * A simpler version of the copy_course, the function creates an empty course with an autogenerated course code.
- *
- * @param string $new_title new course title
- * @param string source course code
- * @param int source session id
- * @param int destination session id
- * @param array $params
- *
- * @return array
- */
- public static function copy_course_simple(
- $new_title,
- $source_course_code,
- $source_session_id = 0,
- $destination_session_id = 0,
- $params = []
- ) {
- $source_course_info = api_get_course_info($source_course_code);
- if (!empty($source_course_info)) {
- $new_course_code = self::generate_nice_next_course_code($source_course_code);
- if ($new_course_code) {
- $new_course_info = self::create_course(
- $new_title,
- $new_course_code,
- false
- );
- if (!empty($new_course_info['code'])) {
- $result = self::copy_course(
- $source_course_code,
- $source_session_id,
- $new_course_info['code'],
- $destination_session_id,
- $params
- );
- if ($result) {
- return $new_course_info;
- }
- }
- }
- }
- return false;
- }
- /**
- * Creates a new course code based in a given code.
- *
- * @param string wanted code
- * <code> $wanted_code = 'curse' if there are in the DB codes like curse1 curse2 the function will return: course3</code>
- * if the course code doest not exist in the DB the same course code will be returned
- *
- * @return string wanted unused code
- */
- public static function generate_nice_next_course_code($wanted_code)
- {
- $course_code_ok = !self::course_code_exists($wanted_code);
- if (!$course_code_ok) {
- $wanted_code = self::generate_course_code($wanted_code);
- $table = Database::get_main_table(TABLE_MAIN_COURSE);
- $wanted_code = Database::escape_string($wanted_code);
- $sql = "SELECT count(id) as count
- FROM $table
- WHERE code LIKE '$wanted_code%'";
- $result = Database::query($sql);
- if (Database::num_rows($result) > 0) {
- $row = Database::fetch_array($result);
- $count = $row['count'] + 1;
- $wanted_code = $wanted_code.'_'.$count;
- $result = api_get_course_info($wanted_code);
- if (empty($result)) {
- return $wanted_code;
- }
- }
- return false;
- }
- return $wanted_code;
- }
- /**
- * Gets the status of the users agreement in a course course-session.
- *
- * @param int $user_id
- * @param string $course_code
- * @param int $session_id
- *
- * @return bool
- */
- public static function is_user_accepted_legal($user_id, $course_code, $session_id = 0)
- {
- $user_id = intval($user_id);
- $course_code = Database::escape_string($course_code);
- $session_id = intval($session_id);
- $courseInfo = api_get_course_info($course_code);
- $courseId = $courseInfo['real_id'];
- // Course legal
- $enabled = api_get_plugin_setting('courselegal', 'tool_enable');
- if ($enabled == 'true') {
- require_once api_get_path(SYS_PLUGIN_PATH).'courselegal/config.php';
- $plugin = CourseLegalPlugin::create();
- return $plugin->isUserAcceptedLegal($user_id, $course_code, $session_id);
- }
- if (empty($session_id)) {
- $table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
- $sql = "SELECT legal_agreement FROM $table
- WHERE user_id = $user_id AND c_id = $courseId ";
- $result = Database::query($sql);
- if (Database::num_rows($result) > 0) {
- $result = Database::fetch_array($result);
- if ($result['legal_agreement'] == 1) {
- return true;
- }
- }
- return false;
- } else {
- $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
- $sql = "SELECT legal_agreement FROM $table
- WHERE user_id = $user_id AND c_id = $courseId AND session_id = $session_id";
- $result = Database::query($sql);
- if (Database::num_rows($result) > 0) {
- $result = Database::fetch_array($result);
- if ($result['legal_agreement'] == 1) {
- return true;
- }
- }
- return false;
- }
- }
- /**
- * Saves the user-course legal agreement.
- *
- * @param int user id
- * @param string course code
- * @param int session id
- *
- * @return mixed
- */
- public static function save_user_legal($user_id, $course_code, $session_id = null)
- {
- // Course plugin legal
- $enabled = api_get_plugin_setting('courselegal', 'tool_enable');
- if ($enabled == 'true') {
- require_once api_get_path(SYS_PLUGIN_PATH).'courselegal/config.php';
- $plugin = CourseLegalPlugin::create();
- return $plugin->saveUserLegal($user_id, $course_code, $session_id);
- }
- $user_id = intval($user_id);
- $course_code = Database::escape_string($course_code);
- $session_id = intval($session_id);
- $courseInfo = api_get_course_info($course_code);
- $courseId = $courseInfo['real_id'];
- if (empty($session_id)) {
- $table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
- $sql = "UPDATE $table SET legal_agreement = '1'
- WHERE user_id = $user_id AND c_id = $courseId ";
- Database::query($sql);
- } else {
- $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
- $sql = "UPDATE $table SET legal_agreement = '1'
- WHERE user_id = $user_id AND c_id = $courseId AND session_id = $session_id";
- Database::query($sql);
- }
- }
- /**
- * @param int $user_id
- * @param int $course_id
- * @param int $session_id
- * @param int $url_id
- *
- * @return bool
- */
- public static function get_user_course_vote($user_id, $course_id, $session_id = 0, $url_id = 0)
- {
- $table_user_course_vote = Database::get_main_table(TABLE_MAIN_USER_REL_COURSE_VOTE);
- $session_id = !isset($session_id) ? api_get_session_id() : intval($session_id);
- $url_id = empty($url_id) ? api_get_current_access_url_id() : intval($url_id);
- $user_id = intval($user_id);
- if (empty($user_id)) {
- return false;
- }
- $params = [
- 'user_id' => $user_id,
- 'c_id' => $course_id,
- 'session_id' => $session_id,
- 'url_id' => $url_id,
- ];
- $result = Database::select(
- 'vote',
- $table_user_course_vote,
- [
- 'where' => [
- 'user_id = ? AND c_id = ? AND session_id = ? AND url_id = ?' => $params,
- ],
- ],
- 'first'
- );
- if (!empty($result)) {
- return $result['vote'];
- }
- return false;
- }
- /**
- * @param int $course_id
- * @param int $session_id
- * @param int $url_id
- *
- * @return array
- */
- public static function get_course_ranking(
- $course_id,
- $session_id = 0,
- $url_id = 0
- ) {
- $table_course_ranking = Database::get_main_table(TABLE_STATISTIC_TRACK_COURSE_RANKING);
- $session_id = empty($session_id) ? api_get_session_id() : intval($session_id);
- $url_id = empty($url_id) ? api_get_current_access_url_id() : intval($url_id);
- $now = api_get_utc_datetime();
- $params = [
- 'c_id' => $course_id,
- 'session_id' => $session_id,
- 'url_id' => $url_id,
- 'creation_date' => $now,
- ];
- $result = Database::select(
- 'c_id, accesses, total_score, users',
- $table_course_ranking,
- ['where' => ['c_id = ? AND session_id = ? AND url_id = ?' => $params]],
- 'first'
- );
- $point_average_in_percentage = 0;
- $point_average_in_star = 0;
- $users_who_voted = 0;
- if (!empty($result['users'])) {
- $users_who_voted = $result['users'];
- $point_average_in_percentage = round($result['total_score'] / $result['users'] * 100 / 5, 2);
- $point_average_in_star = round($result['total_score'] / $result['users'], 1);
- }
- $result['user_vote'] = false;
- if (!api_is_anonymous()) {
- $result['user_vote'] = self::get_user_course_vote(api_get_user_id(), $course_id, $session_id, $url_id);
- }
- $result['point_average'] = $point_average_in_percentage;
- $result['point_average_star'] = $point_average_in_star;
- $result['users_who_voted'] = $users_who_voted;
- return $result;
- }
- /**
- * Updates the course ranking.
- *
- * @param int course id
- * @param int $session_id
- * @param int url id
- * @param $points_to_add
- * @param bool $add_access
- * @param bool $add_user
- *
- * @return array
- */
- public static function update_course_ranking(
- $course_id = 0,
- $session_id = 0,
- $url_id = 0,
- $points_to_add = null,
- $add_access = true,
- $add_user = true
- ) {
- // Course catalog stats modifications see #4191
- $table_course_ranking = Database::get_main_table(TABLE_STATISTIC_TRACK_COURSE_RANKING);
- $now = api_get_utc_datetime();
- $course_id = empty($course_id) ? api_get_course_int_id() : intval($course_id);
- $session_id = empty($session_id) ? api_get_session_id() : intval($session_id);
- $url_id = empty($url_id) ? api_get_current_access_url_id() : intval($url_id);
- $params = [
- 'c_id' => $course_id,
- 'session_id' => $session_id,
- 'url_id' => $url_id,
- 'creation_date' => $now,
- 'total_score' => 0,
- 'users' => 0,
- ];
- $result = Database::select(
- 'id, accesses, total_score, users',
- $table_course_ranking,
- ['where' => ['c_id = ? AND session_id = ? AND url_id = ?' => $params]],
- 'first'
- );
- // Problem here every time we load the courses/XXXX/index.php course home page we update the access
- if (empty($result)) {
- if ($add_access) {
- $params['accesses'] = 1;
- }
- //The votes and users are empty
- if (isset($points_to_add) && !empty($points_to_add)) {
- $params['total_score'] = intval($points_to_add);
- }
- if ($add_user) {
- $params['users'] = 1;
- }
- $result = Database::insert($table_course_ranking, $params);
- } else {
- $my_params = [];
- if ($add_access) {
- $my_params['accesses'] = intval($result['accesses']) + 1;
- }
- if (isset($points_to_add) && !empty($points_to_add)) {
- $my_params['total_score'] = $result['total_score'] + $points_to_add;
- }
- if ($add_user) {
- $my_params['users'] = $result['users'] + 1;
- }
- if (!empty($my_params)) {
- $result = Database::update(
- $table_course_ranking,
- $my_params,
- ['c_id = ? AND session_id = ? AND url_id = ?' => $params]
- );
- }
- }
- return $result;
- }
- /**
- * Add user vote to a course.
- *
- * @param int user id
- * @param int vote [1..5]
- * @param int course id
- * @param int session id
- * @param int url id (access_url_id)
- *
- * @return false|string 'added', 'updated' or 'nothing'
- */
- public static function add_course_vote(
- $user_id,
- $vote,
- $course_id,
- $session_id = 0,
- $url_id = 0
- ) {
- $table_user_course_vote = Database::get_main_table(TABLE_MAIN_USER_REL_COURSE_VOTE);
- $course_id = empty($course_id) ? api_get_course_int_id() : intval($course_id);
- if (empty($course_id) || empty($user_id)) {
- return false;
- }
- if (!in_array($vote, [1, 2, 3, 4, 5])) {
- return false;
- }
- $session_id = empty($session_id) ? api_get_session_id() : intval($session_id);
- $url_id = empty($url_id) ? api_get_current_access_url_id() : intval($url_id);
- $vote = intval($vote);
- $params = [
- 'user_id' => intval($user_id),
- 'c_id' => $course_id,
- 'session_id' => $session_id,
- 'url_id' => $url_id,
- 'vote' => $vote,
- ];
- $action_done = 'nothing';
- $result = Database::select(
- 'id, vote',
- $table_user_course_vote,
- ['where' => ['user_id = ? AND c_id = ? AND session_id = ? AND url_id = ?' => $params]],
- 'first'
- );
- if (empty($result)) {
- Database::insert($table_user_course_vote, $params);
- $points_to_add = $vote;
- $add_user = true;
- $action_done = 'added';
- } else {
- $my_params = ['vote' => $vote];
- $points_to_add = $vote - $result['vote'];
- $add_user = false;
- Database::update(
- $table_user_course_vote,
- $my_params,
- ['user_id = ? AND c_id = ? AND session_id = ? AND url_id = ?' => $params]
- );
- $action_done = 'updated';
- }
- // Current points
- if (!empty($points_to_add)) {
- self::update_course_ranking(
- $course_id,
- $session_id,
- $url_id,
- $points_to_add,
- false,
- $add_user
- );
- }
- return $action_done;
- }
- /**
- * Remove course ranking + user votes.
- *
- * @param int $course_id
- * @param int $session_id
- * @param int $url_id
- */
- public static function remove_course_ranking($course_id, $session_id, $url_id = null)
- {
- $table_course_ranking = Database::get_main_table(TABLE_STATISTIC_TRACK_COURSE_RANKING);
- $table_user_course_vote = Database::get_main_table(TABLE_MAIN_USER_REL_COURSE_VOTE);
- if (!empty($course_id) && isset($session_id)) {
- $url_id = empty($url_id) ? api_get_current_access_url_id() : intval($url_id);
- $params = [
- 'c_id' => $course_id,
- 'session_id' => $session_id,
- 'url_id' => $url_id,
- ];
- Database::delete($table_course_ranking, ['c_id = ? AND session_id = ? AND url_id = ?' => $params]);
- Database::delete($table_user_course_vote, ['c_id = ? AND session_id = ? AND url_id = ?' => $params]);
- }
- }
- /**
- * Returns an array with the hottest courses.
- *
- * @param int $days number of days
- * @param int $limit number of hottest courses
- *
- * @return array
- */
- public static function return_hot_courses($days = 30, $limit = 6)
- {
- if (api_is_invitee()) {
- return [];
- }
- $limit = (int) $limit;
- $userId = api_get_user_id();
- // Getting my courses
- $my_course_list = self::get_courses_list_by_user_id($userId);
- $codeList = [];
- foreach ($my_course_list as $course) {
- $codeList[$course['real_id']] = $course['real_id'];
- }
- if (api_is_drh()) {
- $courses = self::get_courses_followed_by_drh($userId);
- foreach ($courses as $course) {
- $codeList[$course['real_id']] = $course['real_id'];
- }
- }
- $table_course_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
- $table_course = Database::get_main_table(TABLE_MAIN_COURSE);
- $table_course_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
- $urlId = api_get_current_access_url_id();
- //$table_course_access table uses the now() and interval ...
- $now = api_get_utc_datetime();
- $sql = "SELECT COUNT(course_access_id) course_count, a.c_id, visibility
- FROM $table_course c
- INNER JOIN $table_course_access a
- ON (c.id = a.c_id)
- INNER JOIN $table_course_url u
- ON u.c_id = c.id
- WHERE
- u.access_url_id = $urlId AND
- login_course_date <= '$now' AND
- login_course_date > DATE_SUB('$now', INTERVAL $days DAY) AND
- visibility <> ".COURSE_VISIBILITY_CLOSED." AND
- visibility <> ".COURSE_VISIBILITY_HIDDEN."
- GROUP BY a.c_id
- ORDER BY course_count DESC
- LIMIT $limit
- ";
- $result = Database::query($sql);
- $courses = [];
- if (Database::num_rows($result)) {
- $courses = Database::store_result($result, 'ASSOC');
- $courses = self::processHotCourseItem($courses, $codeList);
- }
- return $courses;
- }
- /**
- * @param array $courses
- * @param array $codeList
- *
- * @return mixed
- */
- public static function processHotCourseItem($courses, $codeList = [])
- {
- $hotCourses = [];
- $ajax_url = api_get_path(WEB_AJAX_PATH).'course.ajax.php?a=add_course_vote';
- $stok = Security::get_existing_token();
- $user_id = api_get_user_id();
- foreach ($courses as $courseId) {
- $course_info = api_get_course_info_by_id($courseId['c_id']);
- $courseCode = $course_info['code'];
- $categoryCode = !empty($course_info['categoryCode']) ? $course_info['categoryCode'] : "";
- $my_course = $course_info;
- $my_course['go_to_course_button'] = '';
- $my_course['register_button'] = '';
- $access_link = self::get_access_link_by_user(
- api_get_user_id(),
- $course_info,
- $codeList
- );
- $userRegisteredInCourse = self::is_user_subscribed_in_course($user_id, $course_info['code']);
- $userRegisteredInCourseAsTeacher = self::is_course_teacher($user_id, $course_info['code']);
- $userRegistered = $userRegisteredInCourse && $userRegisteredInCourseAsTeacher;
- $my_course['is_course_student'] = $userRegisteredInCourse;
- $my_course['is_course_teacher'] = $userRegisteredInCourseAsTeacher;
- $my_course['is_registered'] = $userRegistered;
- $my_course['title_cut'] = cut($course_info['title'], 45);
- // Course visibility
- if ($access_link && in_array('register', $access_link)) {
- $my_course['register_button'] = Display::url(
- get_lang('Subscribe').' '.
- Display::returnFontAwesomeIcon('sign-in'),
- api_get_path(WEB_COURSE_PATH).$course_info['path'].
- '/index.php?action=subscribe&sec_token='.$stok,
- [
- 'class' => 'btn btn-success btn-sm',
- 'title' => get_lang('Subscribe'),
- 'aria-label' => get_lang('Subscribe'),
- ]
- );
- }
- if ($access_link && in_array('enter', $access_link) ||
- $course_info['visibility'] == COURSE_VISIBILITY_OPEN_WORLD
- ) {
- $my_course['go_to_course_button'] = Display::url(
- get_lang('GoToCourse').' '.
- Display::returnFontAwesomeIcon('share'),
- api_get_path(WEB_COURSE_PATH).$course_info['path'].'/index.php',
- [
- 'class' => 'btn btn-default btn-sm',
- 'title' => get_lang('GoToCourse'),
- 'aria-label' => get_lang('GoToCourse'),
- ]
- );
- }
- if ($access_link && in_array('unsubscribe', $access_link)) {
- $my_course['unsubscribe_button'] = Display::url(
- get_lang('Unreg').' '.
- Display::returnFontAwesomeIcon('sign-out'),
- api_get_path(WEB_CODE_PATH).'auth/courses.php?action=unsubscribe&unsubscribe='.$courseCode
- .'&sec_token='.$stok.'&category_code='.$categoryCode,
- [
- 'class' => 'btn btn-danger btn-sm',
- 'title' => get_lang('Unreg'),
- 'aria-label' => get_lang('Unreg'),
- ]
- );
- }
- // start buycourse validation
- // display the course price and buy button if the buycourses plugin is enabled and this course is configured
- $plugin = BuyCoursesPlugin::create();
- $isThisCourseInSale = $plugin->buyCoursesForGridCatalogValidator(
- $course_info['real_id'],
- BuyCoursesPlugin::PRODUCT_TYPE_COURSE
- );
- if ($isThisCourseInSale) {
- // set the price label
- $my_course['price'] = $isThisCourseInSale['html'];
- // set the Buy button instead register.
- if ($isThisCourseInSale['verificator'] && !empty($my_course['register_button'])) {
- $my_course['register_button'] = $plugin->returnBuyCourseButton(
- $course_info['real_id'],
- BuyCoursesPlugin::PRODUCT_TYPE_COURSE
- );
- }
- }
- // end buycourse validation
- // Description
- $my_course['description_button'] = self::returnDescriptionButton($course_info);
- $my_course['teachers'] = self::getTeachersFromCourse($course_info['real_id'], true);
- $point_info = self::get_course_ranking($course_info['real_id'], 0);
- $my_course['rating_html'] = '';
- if (api_get_configuration_value('hide_course_rating') === false) {
- $my_course['rating_html'] = Display::return_rating_system(
- 'star_'.$course_info['real_id'],
- $ajax_url.'&course_id='.$course_info['real_id'],
- $point_info
- );
- }
- $hotCourses[] = $my_course;
- }
- return $hotCourses;
- }
- /**
- * Get courses count.
- *
- * @param int $access_url_id Access URL ID (optional)
- * @param int $visibility
- *
- * @return int Number of courses
- */
- public static function count_courses($access_url_id = null, $visibility = null)
- {
- $table_course = Database::get_main_table(TABLE_MAIN_COURSE);
- $table_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
- $sql = "SELECT count(c.id) FROM $table_course c";
- if (!empty($access_url_id) && $access_url_id == intval($access_url_id)) {
- $sql .= ", $table_course_rel_access_url u
- WHERE c.id = u.c_id AND u.access_url_id = $access_url_id";
- if (!empty($visibility)) {
- $visibility = intval($visibility);
- $sql .= " AND visibility = $visibility ";
- }
- } else {
- if (!empty($visibility)) {
- $visibility = intval($visibility);
- $sql .= " WHERE visibility = $visibility ";
- }
- }
- $res = Database::query($sql);
- $row = Database::fetch_row($res);
- return $row[0];
- }
- /**
- * Get active courses count.
- * Active = all courses except the ones with hidden visibility.
- *
- * @param int $urlId Access URL ID (optional)
- *
- * @return int Number of courses
- */
- public static function countActiveCourses($urlId = null)
- {
- $table_course = Database::get_main_table(TABLE_MAIN_COURSE);
- $table_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
- $sql = "SELECT count(id) FROM $table_course c";
- if (!empty($urlId) && $urlId == intval($urlId)) {
- $sql .= ", $table_course_rel_access_url u
- WHERE
- c.id = u.c_id AND
- u.access_url_id = $urlId AND
- visibility <> ".COURSE_VISIBILITY_HIDDEN;
- } else {
- $sql .= " WHERE visibility <> ".COURSE_VISIBILITY_HIDDEN;
- }
- $res = Database::query($sql);
- $row = Database::fetch_row($res);
- return $row[0];
- }
- /**
- * Returns the SQL conditions to filter course only visible by the user in the catalogue.
- *
- * @param string $courseTableAlias Alias of the course table
- * @param bool $hideClosed Whether to hide closed and hidden courses
- *
- * @return string SQL conditions
- */
- public static function getCourseVisibilitySQLCondition(
- $courseTableAlias,
- $hideClosed = false
- ) {
- $visibilityCondition = '';
- $hidePrivate = api_get_setting('course_catalog_hide_private');
- if ($hidePrivate === 'true') {
- $visibilityCondition .= " AND $courseTableAlias.visibility <> ".COURSE_VISIBILITY_REGISTERED;
- }
- if ($hideClosed) {
- $visibilityCondition .= " AND $courseTableAlias.visibility NOT IN (".COURSE_VISIBILITY_CLOSED.','.COURSE_VISIBILITY_HIDDEN.')';
- }
- // Check if course have users allowed to see it in the catalogue, then show only if current user is allowed to see it
- $currentUserId = api_get_user_id();
- $restrictedCourses = self::getCatalogueCourseList(true);
- $allowedCoursesToCurrentUser = self::getCatalogueCourseList(true, $currentUserId);
- if (!empty($restrictedCourses)) {
- $visibilityCondition .= ' AND ('.$courseTableAlias.'.code NOT IN ("'.implode('","', $restrictedCourses).'")';
- $visibilityCondition .= ' OR '.$courseTableAlias.'.code IN ("'.implode('","', $allowedCoursesToCurrentUser).'"))';
- }
- // Check if course have users denied to see it in the catalogue, then show only if current user is not denied to see it
- $restrictedCourses = self::getCatalogueCourseList(false);
- $notAllowedCoursesToCurrentUser = self::getCatalogueCourseList(false, $currentUserId);
- if (!empty($restrictedCourses)) {
- $visibilityCondition .= ' AND ('.$courseTableAlias.'.code NOT IN ("'.implode('","', $restrictedCourses).'")';
- $visibilityCondition .= ' OR '.$courseTableAlias.'.code NOT IN ("'.implode('","', $notAllowedCoursesToCurrentUser).'"))';
- }
- return $visibilityCondition;
- }
- /**
- * Return a link to go to the course, validating the visibility of the
- * course and the user status.
- *
- * @param int $uid User ID
- * @param array Course details array
- * @param array List of courses to which the user is subscribed (if not provided, will be generated)
- *
- * @return mixed 'enter' for a link to go to the course or 'register' for a link to subscribe, or false if no access
- */
- public static function get_access_link_by_user($uid, $course, $user_courses = [])
- {
- if (empty($uid) || empty($course)) {
- return false;
- }
- if (empty($user_courses)) {
- // get the array of courses to which the user is subscribed
- $user_courses = self::get_courses_list_by_user_id($uid);
- foreach ($user_courses as $k => $v) {
- $user_courses[$k] = $v['real_id'];
- }
- }
- if (!isset($course['real_id']) && empty($course['real_id'])) {
- $course = api_get_course_info($course['code']);
- }
- if ($course['visibility'] == COURSE_VISIBILITY_HIDDEN) {
- return [];
- }
- $is_admin = api_is_platform_admin_by_id($uid);
- $options = [];
- // Register button
- if (!api_is_anonymous($uid) &&
- (
- ($course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD || $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM)
- //$course['visibility'] == COURSE_VISIBILITY_REGISTERED && $course['subscribe'] == SUBSCRIBE_ALLOWED
- ) &&
- $course['subscribe'] == SUBSCRIBE_ALLOWED &&
- (!in_array($course['real_id'], $user_courses) || empty($user_courses))
- ) {
- $options[] = 'register';
- }
- // Go To Course button (only if admin, if course public or if student already subscribed)
- if ($is_admin ||
- $course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD && empty($course['registration_code']) ||
- (api_user_is_login($uid) && $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM && empty($course['registration_code'])) ||
- (in_array($course['real_id'], $user_courses) && $course['visibility'] != COURSE_VISIBILITY_CLOSED)
- ) {
- $options[] = 'enter';
- }
- if ($is_admin ||
- $course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD && empty($course['registration_code']) ||
- (api_user_is_login($uid) && $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM && empty($course['registration_code'])) ||
- (in_array($course['real_id'], $user_courses) && $course['visibility'] != COURSE_VISIBILITY_CLOSED)
- ) {
- $options[] = 'enter';
- }
- if ($course['visibility'] != COURSE_VISIBILITY_HIDDEN &&
- empty($course['registration_code']) &&
- $course['unsubscribe'] == UNSUBSCRIBE_ALLOWED &&
- api_user_is_login($uid) &&
- in_array($course['real_id'], $user_courses)
- ) {
- $options[] = 'unsubscribe';
- }
- return $options;
- }
- /**
- * @param array $courseInfo
- * @param array $teachers
- * @param bool $deleteTeachersNotInList
- * @param bool $editTeacherInSessions
- * @param bool $deleteSessionTeacherNotInList
- * @param array $teacherBackup
- * @param Monolog\Logger $logger
- *
- * @return false|null
- */
- public static function updateTeachers(
- $courseInfo,
- $teachers,
- $deleteTeachersNotInList = true,
- $editTeacherInSessions = false,
- $deleteSessionTeacherNotInList = false,
- $teacherBackup = [],
- $logger = null
- ) {
- if (!is_array($teachers)) {
- $teachers = [$teachers];
- }
- if (empty($courseInfo) || !isset($courseInfo['real_id'])) {
- return false;
- }
- $teachers = array_filter($teachers);
- $courseId = $courseInfo['real_id'];
- $course_code = $courseInfo['code'];
- $course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
- $alreadyAddedTeachers = self::get_teacher_list_from_course_code($course_code);
- if ($deleteTeachersNotInList) {
- // Delete only teacher relations that doesn't match the selected teachers
- $cond = null;
- if (count($teachers) > 0) {
- foreach ($teachers as $key) {
- $key = Database::escape_string($key);
- $cond .= " AND user_id <> '".$key."'";
- }
- }
- // Recover user categories
- $sql = "SELECT * FROM $course_user_table
- WHERE c_id = $courseId AND status = 1 AND relation_type = 0 ".$cond;
- $result = Database::query($sql);
- if (Database::num_rows($result)) {
- $teachersToDelete = Database::store_result($result, 'ASSOC');
- foreach ($teachersToDelete as $data) {
- $userId = $data['user_id'];
- $teacherBackup[$userId][$course_code] = $data;
- }
- }
- $sql = "DELETE FROM $course_user_table
- WHERE c_id = $courseId AND status = 1 AND relation_type = 0 ".$cond;
- Database::query($sql);
- }
- if (count($teachers) > 0) {
- foreach ($teachers as $userId) {
- $userId = intval($userId);
- // We check if the teacher is already subscribed in this course
- $sql = "SELECT 1 FROM $course_user_table
- WHERE user_id = $userId AND c_id = $courseId";
- $result = Database::query($sql);
- if (Database::num_rows($result)) {
- $sql = "UPDATE $course_user_table
- SET status = 1
- WHERE c_id = $courseId AND user_id = $userId ";
- } else {
- $userCourseCategory = '0';
- if (isset($teacherBackup[$userId]) &&
- isset($teacherBackup[$userId][$course_code])
- ) {
- $courseUserData = $teacherBackup[$userId][$course_code];
- $userCourseCategory = $courseUserData['user_course_cat'];
- if ($logger) {
- $logger->addInfo("Recovering user_course_cat: $userCourseCategory");
- }
- }
- $sql = "INSERT INTO $course_user_table SET
- c_id = $courseId,
- user_id = $userId,
- status = 1,
- is_tutor = 0,
- sort = 0,
- relation_type = 0,
- user_course_cat = $userCourseCategory
- ";
- }
- Database::query($sql);
- }
- }
- if ($editTeacherInSessions) {
- $sessions = SessionManager::get_session_by_course($courseId);
- if (!empty($sessions)) {
- if ($logger) {
- $logger->addInfo("Edit teachers in sessions");
- }
- foreach ($sessions as $session) {
- $sessionId = $session['id'];
- // Remove old and add new
- if ($deleteSessionTeacherNotInList) {
- foreach ($teachers as $userId) {
- if ($logger) {
- $logger->addInfo("Set coach #$userId in session #$sessionId of course #$courseId ");
- }
- SessionManager::set_coach_to_course_session(
- $userId,
- $sessionId,
- $courseId
- );
- }
- $teachersToDelete = [];
- if (!empty($alreadyAddedTeachers)) {
- $teachersToDelete = array_diff(array_keys($alreadyAddedTeachers), $teachers);
- }
- if (!empty($teachersToDelete)) {
- foreach ($teachersToDelete as $userId) {
- if ($logger) {
- $logger->addInfo("Delete coach #$userId in session #$sessionId of course #$courseId ");
- }
- SessionManager::set_coach_to_course_session(
- $userId,
- $sessionId,
- $courseId,
- true
- );
- }
- }
- } else {
- // Add new teachers only
- foreach ($teachers as $userId) {
- if ($logger) {
- $logger->addInfo("Add coach #$userId in session #$sessionId of course #$courseId ");
- }
- SessionManager::set_coach_to_course_session(
- $userId,
- $sessionId,
- $courseId
- );
- }
- }
- }
- }
- }
- }
- /**
- * Course available settings variables see c_course_setting table.
- *
- * @param AppPlugin $appPlugin
- *
- * @return array
- */
- public static function getCourseSettingVariables(AppPlugin $appPlugin)
- {
- $pluginCourseSettings = $appPlugin->getAllPluginCourseSettings();
- $courseSettings = [
- // Get allow_learning_path_theme from table
- 'allow_learning_path_theme',
- // Get allow_open_chat_window from table
- 'allow_open_chat_window',
- 'allow_public_certificates',
- // Get allow_user_edit_agenda from table
- 'allow_user_edit_agenda',
- // Get allow_user_edit_announcement from table
- 'allow_user_edit_announcement',
- // Get allow_user_image_forum from table
- 'allow_user_image_forum',
- //Get allow show user list
- 'allow_user_view_user_list',
- // Get course_theme from table
- 'course_theme',
- //Get allow show user list
- 'display_info_advance_inside_homecourse',
- 'documents_default_visibility',
- // Get send_mail_setting (work)from table
- 'email_alert_manager_on_new_doc',
- // Get send_mail_setting (work)from table
- 'email_alert_manager_on_new_quiz',
- // Get send_mail_setting (dropbox) from table
- 'email_alert_on_new_doc_dropbox',
- 'email_alert_students_on_new_homework',
- // Get send_mail_setting (auth)from table
- 'email_alert_to_teacher_on_new_user_in_course',
- 'enable_lp_auto_launch',
- 'enable_exercise_auto_launch',
- 'enable_document_auto_launch',
- 'pdf_export_watermark_text',
- 'show_system_folders',
- 'exercise_invisible_in_session',
- 'enable_forum_auto_launch',
- 'show_course_in_user_language',
- 'email_to_teachers_on_new_work_feedback',
- 'student_delete_own_publication',
- 'hide_forum_notifications',
- 'quiz_question_limit_per_day',
- 'subscribe_users_to_forum_notifications',
- ];
- $courseModels = ExerciseLib::getScoreModels();
- if (!empty($courseModels)) {
- $courseSettings[] = 'score_model_id';
- }
- $allowLPReturnLink = api_get_setting('allow_lp_return_link');
- if ($allowLPReturnLink === 'true') {
- $courseSettings[] = 'lp_return_link';
- }
- if (!empty($pluginCourseSettings)) {
- $courseSettings = array_merge(
- $courseSettings,
- $pluginCourseSettings
- );
- }
- return $courseSettings;
- }
- /**
- * @param AppPlugin $appPlugin
- * @param string $variable
- * @param string|array $value
- * @param int $courseId
- *
- * @return bool
- */
- public static function saveCourseConfigurationSetting(AppPlugin $appPlugin, $variable, $value, $courseId)
- {
- $settingList = self::getCourseSettingVariables($appPlugin);
- if (!in_array($variable, $settingList)) {
- return false;
- }
- $courseSettingTable = Database::get_course_table(TABLE_COURSE_SETTING);
- if (is_array($value)) {
- $value = implode(',', $value);
- }
- if (self::hasCourseSetting($variable, $courseId)) {
- // Update
- Database::update(
- $courseSettingTable,
- ['value' => $value],
- ['variable = ? AND c_id = ?' => [$variable, $courseId]]
- );
- } else {
- // Create
- Database::insert(
- $courseSettingTable,
- [
- 'title' => $variable,
- 'value' => $value,
- 'c_id' => $courseId,
- 'variable' => $variable,
- ]
- );
- }
- return true;
- }
- /**
- * Check if course setting exists.
- *
- * @param string $variable
- * @param int $courseId
- *
- * @return bool
- */
- public static function hasCourseSetting($variable, $courseId)
- {
- $courseSetting = Database::get_course_table(TABLE_COURSE_SETTING);
- $courseId = (int) $courseId;
- $variable = Database::escape_string($variable);
- $sql = "SELECT variable FROM $courseSetting
- WHERE c_id = $courseId AND variable = '$variable'";
- $result = Database::query($sql);
- return Database::num_rows($result) > 0;
- }
- /**
- * Get information from the track_e_course_access table.
- *
- * @param int $courseId
- * @param int $sessionId
- * @param string $startDate
- * @param string $endDate
- *
- * @return array
- */
- public static function getCourseAccessPerCourseAndSession(
- $courseId,
- $sessionId,
- $startDate,
- $endDate
- ) {
- $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
- $courseId = (int) $courseId;
- $sessionId = (int) $sessionId;
- $startDate = Database::escape_string($startDate);
- $endDate = Database::escape_string($endDate);
- $sql = "SELECT * FROM $table
- WHERE
- c_id = $courseId AND
- session_id = $sessionId AND
- login_course_date BETWEEN '$startDate' AND '$endDate'
- ";
- $result = Database::query($sql);
- return Database::store_result($result);
- }
- /**
- * Get login information from the track_e_course_access table, for any
- * course in the given session.
- *
- * @param int $sessionId
- * @param int $userId
- *
- * @return array
- */
- public static function getFirstCourseAccessPerSessionAndUser($sessionId, $userId)
- {
- $sessionId = (int) $sessionId;
- $userId = (int) $userId;
- $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
- $sql = "SELECT * FROM $table
- WHERE session_id = $sessionId AND user_id = $userId
- ORDER BY login_course_date ASC
- LIMIT 1";
- $result = Database::query($sql);
- $courseAccess = [];
- if (Database::num_rows($result)) {
- $courseAccess = Database::fetch_array($result, 'ASSOC');
- }
- return $courseAccess;
- }
- /**
- * @param int $courseId
- * @param int $sessionId
- * @param bool $getAllSessions
- *
- * @return mixed
- */
- public static function getCountForum(
- $courseId,
- $sessionId = 0,
- $getAllSessions = false
- ) {
- $forum = Database::get_course_table(TABLE_FORUM);
- if ($getAllSessions) {
- $sql = "SELECT count(*) as count
- FROM $forum f
- WHERE f.c_id = %s";
- } else {
- $sql = "SELECT count(*) as count
- FROM $forum f
- WHERE f.c_id = %s and f.session_id = %s";
- }
- $sql = sprintf($sql, intval($courseId), intval($sessionId));
- $result = Database::query($sql);
- $row = Database::fetch_array($result);
- return $row['count'];
- }
- /**
- * @param int $userId
- * @param int $courseId
- * @param int $sessionId
- *
- * @return mixed
- */
- public static function getCountPostInForumPerUser(
- $userId,
- $courseId,
- $sessionId = 0
- ) {
- $forum = Database::get_course_table(TABLE_FORUM);
- $forum_post = Database::get_course_table(TABLE_FORUM_POST);
- $sql = "SELECT count(distinct post_id) as count
- FROM $forum_post p
- INNER JOIN $forum f
- ON f.forum_id = p.forum_id AND f.c_id = p.c_id
- WHERE p.poster_id = %s and f.session_id = %s and p.c_id = %s";
- $sql = sprintf(
- $sql,
- intval($userId),
- intval($sessionId),
- intval($courseId)
- );
- $result = Database::query($sql);
- $row = Database::fetch_array($result);
- return $row['count'];
- }
- /**
- * @param int $userId
- * @param int $courseId
- * @param int $sessionId
- *
- * @return mixed
- */
- public static function getCountForumPerUser(
- $userId,
- $courseId,
- $sessionId = 0
- ) {
- $forum = Database::get_course_table(TABLE_FORUM);
- $forum_post = Database::get_course_table(TABLE_FORUM_POST);
- $sql = "SELECT count(distinct f.forum_id) as count
- FROM $forum_post p
- INNER JOIN $forum f
- ON f.forum_id = p.forum_id AND f.c_id = p.c_id
- WHERE p.poster_id = %s and f.session_id = %s and p.c_id = %s";
- $sql = sprintf(
- $sql,
- intval($userId),
- intval($sessionId),
- intval($courseId)
- );
- $result = Database::query($sql);
- $row = Database::fetch_array($result);
- return $row['count'];
- }
- /**
- * Returns the course name from a given code.
- *
- * @param string $code
- *
- * @return string
- */
- public static function getCourseNameFromCode($code)
- {
- $tbl_main_categories = Database::get_main_table(TABLE_MAIN_COURSE);
- $code = Database::escape_string($code);
- $sql = "SELECT title
- FROM $tbl_main_categories
- WHERE code = '$code'";
- $result = Database::query($sql);
- if ($col = Database::fetch_array($result)) {
- return $col['title'];
- }
- }
- /**
- * Generates a course code from a course title.
- *
- * @todo Such a function might be useful in other places too. It might be moved in the CourseManager class.
- * @todo the function might be upgraded for avoiding code duplications (currently,
- * it might suggest a code that is already in use)
- *
- * @param string $title A course title
- *
- * @return string A proposed course code
- * +
- * @assert (null,null) === false
- * @assert ('ABC_DEF', null) === 'ABCDEF'
- * @assert ('ABC09*^[%A', null) === 'ABC09A'
- */
- public static function generate_course_code($title)
- {
- return substr(
- preg_replace('/[^A-Z0-9]/', '', strtoupper(api_replace_dangerous_char($title))),
- 0,
- self::MAX_COURSE_LENGTH_CODE
- );
- }
- /**
- * this function gets all the users of the course,
- * including users from linked courses.
- *
- * @param $filterByActive
- *
- * @return array
- */
- public static function getCourseUsers($filterByActive = null)
- {
- // This would return only the users from real courses:
- $userList = self::get_user_list_from_course_code(
- api_get_course_id(),
- api_get_session_id(),
- null,
- null,
- null,
- null,
- false,
- false,
- [],
- [],
- [],
- $filterByActive
- );
- return $userList;
- }
- /**
- * this function gets all the groups of the course,
- * not including linked courses.
- */
- public static function getCourseGroups()
- {
- $sessionId = api_get_session_id();
- if ($sessionId != 0) {
- $groupList = self::get_group_list_of_course(
- api_get_course_id(),
- $sessionId,
- 1
- );
- } else {
- $groupList = self::get_group_list_of_course(
- api_get_course_id(),
- 0,
- 1
- );
- }
- return $groupList;
- }
- /**
- * @param FormValidator $form
- * @param array $alreadySelected
- *
- * @return HTML_QuickForm_element
- */
- public static function addUserGroupMultiSelect(&$form, $alreadySelected)
- {
- $userList = self::getCourseUsers(true);
- $groupList = self::getCourseGroups();
- $array = self::buildSelectOptions(
- $groupList,
- $userList,
- $alreadySelected
- );
- $result = [];
- foreach ($array as $content) {
- $result[$content['value']] = $content['content'];
- }
- return $form->addElement(
- 'advmultiselect',
- 'users',
- get_lang('Users'),
- $result,
- ['select_all_checkbox' => true]
- );
- }
- /**
- * This function separates the users from the groups
- * users have a value USER:XXX (with XXX the groups id have a value
- * GROUP:YYY (with YYY the group id).
- *
- * @param array $to Array of strings that define the type and id of each destination
- *
- * @return array Array of groups and users (each an array of IDs)
- */
- public static function separateUsersGroups($to)
- {
- $groupList = [];
- $userList = [];
- foreach ($to as $to_item) {
- if (!empty($to_item)) {
- $parts = explode(':', $to_item);
- $type = isset($parts[0]) ? $parts[0] : '';
- $id = isset($parts[1]) ? $parts[1] : '';
- switch ($type) {
- case 'GROUP':
- $groupList[] = (int) $id;
- break;
- case 'USER':
- $userList[] = (int) $id;
- break;
- }
- }
- }
- $send_to['groups'] = $groupList;
- $send_to['users'] = $userList;
- return $send_to;
- }
- /**
- * Shows the form for sending a message to a specific group or user.
- *
- * @param FormValidator $form
- * @param array $groupInfo
- * @param array $to
- *
- * @return HTML_QuickForm_element
- */
- public static function addGroupMultiSelect($form, $groupInfo, $to = [])
- {
- $groupUsers = GroupManager::get_subscribed_users($groupInfo);
- $array = self::buildSelectOptions([$groupInfo], $groupUsers, $to);
- $result = [];
- foreach ($array as $content) {
- $result[$content['value']] = $content['content'];
- }
- return $form->addElement('advmultiselect', 'users', get_lang('Users'), $result);
- }
- /**
- * this function shows the form for sending a message to a specific group or user.
- *
- * @param array $groupList
- * @param array $userList
- * @param array $alreadySelected
- *
- * @return array
- */
- public static function buildSelectOptions(
- $groupList = [],
- $userList = [],
- $alreadySelected = []
- ) {
- if (empty($alreadySelected)) {
- $alreadySelected = [];
- }
- $result = [];
- // adding the groups to the select form
- if ($groupList) {
- foreach ($groupList as $thisGroup) {
- $groupId = $thisGroup['iid'];
- if (is_array($alreadySelected)) {
- if (!in_array(
- "GROUP:".$groupId,
- $alreadySelected
- )
- ) {
- $userCount = isset($thisGroup['userNb']) ? $thisGroup['userNb'] : 0;
- if (empty($userCount)) {
- $userCount = isset($thisGroup['count_users']) ? $thisGroup['count_users'] : 0;
- }
- // $alreadySelected is the array containing the groups (and users) that are already selected
- $user_label = ($userCount > 0) ? get_lang('Users') : get_lang('LowerCaseUser');
- $user_disabled = ($userCount > 0) ? "" : "disabled=disabled";
- $result[] = [
- 'disabled' => $user_disabled,
- 'value' => "GROUP:".$groupId,
- // The space before "G" is needed in order to advmultiselect.php js puts groups first
- 'content' => " G: ".$thisGroup['name']." - ".$userCount." ".$user_label,
- ];
- }
- }
- }
- }
- // adding the individual users to the select form
- if ($userList) {
- foreach ($userList as $user) {
- if (is_array($alreadySelected)) {
- if (!in_array(
- "USER:".$user['user_id'],
- $alreadySelected
- )
- ) {
- // $alreadySelected is the array containing the users (and groups) that are already selected
- $result[] = [
- 'value' => "USER:".$user['user_id'],
- 'content' => api_get_person_name($user['firstname'], $user['lastname']),
- ];
- }
- }
- }
- }
- return $result;
- }
- /**
- * @return array a list (array) of all courses
- */
- public static function get_course_list()
- {
- $table = Database::get_main_table(TABLE_MAIN_COURSE);
- return Database::store_result(Database::query("SELECT *, id as real_id FROM $table"));
- }
- /**
- * Returns course code from a given gradebook category's id.
- *
- * @param int Category ID
- *
- * @return string Course code
- */
- public static function get_course_by_category($category_id)
- {
- $category_id = (int) $category_id;
- $info = Database::fetch_array(
- Database::query(
- 'SELECT course_code
- FROM '.Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY).'
- WHERE id = '.$category_id
- ),
- 'ASSOC'
- );
- return $info ? $info['course_code'] : false;
- }
- /**
- * This function gets all the courses that are not in a session.
- *
- * @param date Start date
- * @param date End date
- * @param bool $includeClosed Whether to include closed and hidden courses
- *
- * @return array Not-in-session courses
- */
- public static function getCoursesWithoutSession(
- $startDate = null,
- $endDate = null,
- $includeClosed = false
- ) {
- $dateConditional = ($startDate && $endDate) ?
- " WHERE session_id IN (SELECT id FROM ".Database::get_main_table(TABLE_MAIN_SESSION).
- " WHERE access_start_date = '$startDate' AND access_end_date = '$endDate')" : null;
- $visibility = ($includeClosed ? '' : 'visibility NOT IN (0, 4) AND ');
- $sql = "SELECT id, code, title
- FROM ".Database::get_main_table(TABLE_MAIN_COURSE)."
- WHERE $visibility code NOT IN (
- SELECT DISTINCT course_code
- FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE).$dateConditional."
- )
- ORDER BY id";
- $result = Database::query($sql);
- $courses = [];
- while ($row = Database::fetch_array($result)) {
- $courses[] = $row;
- }
- return $courses;
- }
- /**
- * Get list of courses based on users of a group for a group admin.
- *
- * @param int $userId The user id
- *
- * @return array
- */
- public static function getCoursesFollowedByGroupAdmin($userId)
- {
- $coursesList = [];
- $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
- $courseUserTable = Database::get_main_table(TABLE_MAIN_COURSE_USER);
- $userGroup = new UserGroup();
- $userIdList = $userGroup->getGroupUsersByUser($userId);
- if (empty($userIdList)) {
- return [];
- }
- $sql = "SELECT DISTINCT(c.id), c.title
- FROM $courseTable c
- INNER JOIN $courseUserTable cru ON c.id = cru.c_id
- WHERE (
- cru.user_id IN (".implode(', ', $userIdList).")
- AND cru.relation_type = 0
- )";
- if (api_is_multiple_url_enabled()) {
- $courseAccessUrlTable = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
- $accessUrlId = api_get_current_access_url_id();
- if ($accessUrlId != -1) {
- $sql = "SELECT DISTINCT(c.id), c.title
- FROM $courseTable c
- INNER JOIN $courseUserTable cru ON c.id = cru.c_id
- INNER JOIN $courseAccessUrlTable crau ON c.id = crau.c_id
- WHERE crau.access_url_id = $accessUrlId
- AND (
- cru.id_user IN (".implode(', ', $userIdList).") AND
- cru.relation_type = 0
- )";
- }
- }
- $result = Database::query($sql);
- while ($row = Database::fetch_assoc($result)) {
- $coursesList[] = $row;
- }
- return $coursesList;
- }
- /**
- * Direct course link see #5299.
- *
- * You can send to your students an URL like this
- * http://chamilodev.beeznest.com/main/auth/inscription.php?c=ABC&e=3
- * Where "c" is the course code and "e" is the exercise Id, after a successful
- * registration the user will be sent to the course or exercise
- *
- * @param array $form_data
- *
- * @return array
- */
- public static function redirectToCourse($form_data)
- {
- $course_code_redirect = Session::read('course_redirect');
- $_user = api_get_user_info();
- $userId = api_get_user_id();
- if (!empty($course_code_redirect)) {
- $course_info = api_get_course_info($course_code_redirect);
- if (!empty($course_info)) {
- if (in_array(
- $course_info['visibility'],
- [COURSE_VISIBILITY_OPEN_PLATFORM, COURSE_VISIBILITY_OPEN_WORLD]
- )
- ) {
- if (self::is_user_subscribed_in_course($userId, $course_info['code'])) {
- $form_data['action'] = $course_info['course_public_url'];
- $form_data['message'] = sprintf(get_lang('YouHaveBeenRegisteredToCourseX'), $course_info['title']);
- $form_data['button'] = Display::button(
- 'next',
- get_lang('GoToCourse', null, $_user['language']),
- ['class' => 'btn btn-primary btn-large']
- );
- $exercise_redirect = intval(Session::read('exercise_redirect'));
- // Specify the course id as the current context does not
- // hold a global $_course array
- $objExercise = new Exercise($course_info['real_id']);
- $result = $objExercise->read($exercise_redirect);
- if (!empty($exercise_redirect) && !empty($result)) {
- $form_data['action'] = api_get_path(WEB_CODE_PATH).
- 'exercise/overview.php?exerciseId='.$exercise_redirect.'&cidReq='.$course_info['code'];
- $form_data['message'] .= '<br />'.get_lang('YouCanAccessTheExercise');
- $form_data['button'] = Display::button(
- 'next',
- get_lang('Go', null, $_user['language']),
- ['class' => 'btn btn-primary btn-large']
- );
- }
- if (!empty($form_data['action'])) {
- header('Location: '.$form_data['action']);
- exit;
- }
- }
- }
- }
- }
- return $form_data;
- }
- /**
- * Return tab of params to display a course title in the My Courses tab
- * Check visibility, right, and notification icons, and load_dirs option
- * get html course params.
- *
- * @param $courseId
- * @param bool $loadDirs
- *
- * @return array with keys ['right_actions'] ['teachers'] ['notifications']
- */
- public static function getCourseParamsForDisplay($courseId, $loadDirs = false)
- {
- $userId = api_get_user_id();
- $courseId = intval($courseId);
- // Table definitions
- $TABLECOURS = Database::get_main_table(TABLE_MAIN_COURSE);
- $TABLECOURSUSER = Database::get_main_table(TABLE_MAIN_COURSE_USER);
- $TABLE_ACCESS_URL_REL_COURSE = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
- $current_url_id = api_get_current_access_url_id();
- // Get course list auto-register
- $special_course_list = self::get_special_course_list();
- $without_special_courses = '';
- if (!empty($special_course_list)) {
- $without_special_courses = ' AND course.id NOT IN ("'.implode('","', $special_course_list).'")';
- }
- //AND course_rel_user.relation_type<>".COURSE_RELATION_TYPE_RRHH."
- $sql = "SELECT
- course.id,
- course.title,
- course.code,
- course.subscribe subscr,
- course.unsubscribe unsubscr,
- course_rel_user.status status,
- course_rel_user.sort sort,
- course_rel_user.user_course_cat user_course_cat
- FROM
- $TABLECOURS course
- INNER JOIN $TABLECOURSUSER course_rel_user
- ON (course.id = course_rel_user.c_id)
- INNER JOIN $TABLE_ACCESS_URL_REL_COURSE url
- ON (url.c_id = course.id)
- WHERE
- course.id = $courseId AND
- course_rel_user.user_id = $userId
- $without_special_courses
- ";
- // If multiple URL access mode is enabled, only fetch courses
- // corresponding to the current URL.
- if (api_get_multiple_access_url() && $current_url_id != -1) {
- $sql .= " AND url.c_id = course.id AND access_url_id = $current_url_id";
- }
- // Use user's classification for courses (if any).
- $sql .= " ORDER BY course_rel_user.user_course_cat, course_rel_user.sort ASC";
- $result = Database::query($sql);
- // Browse through all courses. We can only have one course because
- // of the course.id=".intval($courseId) in sql query
- $course = Database::fetch_array($result);
- $course_info = api_get_course_info_by_id($courseId);
- if (empty($course_info)) {
- return '';
- }
- //$course['id_session'] = null;
- $course_info['id_session'] = null;
- $course_info['status'] = $course['status'];
- // For each course, get if there is any notification icon to show
- // (something that would have changed since the user's last visit).
- $show_notification = !api_get_configuration_value('hide_course_notification')
- ? Display::show_notification($course_info)
- : '';
- // New code displaying the user's status in respect to this course.
- $status_icon = Display::return_icon(
- 'blackboard.png',
- $course_info['title'],
- [],
- ICON_SIZE_LARGE
- );
- $params = [];
- $params['right_actions'] = '';
- if (api_is_platform_admin()) {
- if ($loadDirs) {
- $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>';
- $params['right_actions'] .= '<a href="'.api_get_path(WEB_CODE_PATH).'course_info/infocours.php?cidReq='.$course['code'].'">'.
- Display::return_icon('edit.png', get_lang('Edit'), ['align' => 'absmiddle'], ICON_SIZE_SMALL).
- '</a>';
- $params['right_actions'] .= Display::div(
- '',
- [
- 'id' => 'document_result_'.$course_info['real_id'].'_0',
- 'class' => 'document_preview_container',
- ]
- );
- } else {
- $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'].'">'.
- Display::returnFontAwesomeIcon('pencil').'</a>';
- }
- } else {
- if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED) {
- if ($loadDirs) {
- $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>';
- $params['right_actions'] .= Display::div(
- '',
- [
- 'id' => 'document_result_'.$course_info['real_id'].'_0',
- 'class' => 'document_preview_container',
- ]
- );
- } else {
- if ($course_info['status'] == COURSEMANAGER) {
- $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'].'">'.
- Display::returnFontAwesomeIcon('pencil').'</a>';
- }
- }
- }
- }
- $course_title_url = '';
- if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED || $course['status'] == COURSEMANAGER) {
- $course_title_url = api_get_path(WEB_COURSE_PATH).$course_info['path'].'/?id_session=0';
- $course_title = Display::url($course_info['title'], $course_title_url);
- } else {
- $course_title = $course_info['title'].' '.Display::tag(
- 'span',
- get_lang('CourseClosed'),
- ['class' => 'item_closed']
- );
- }
- // Start displaying the course block itself
- if (api_get_setting('display_coursecode_in_courselist') === 'true') {
- $course_title .= ' ('.$course_info['visual_code'].') ';
- }
- $teachers = '';
- if (api_get_setting('display_teacher_in_courselist') === 'true') {
- $teachers = self::getTeacherListFromCourseCodeToString(
- $course['code'],
- self::USER_SEPARATOR,
- true
- );
- }
- $params['link'] = $course_title_url;
- $params['icon'] = $status_icon;
- $params['title'] = $course_title;
- $params['teachers'] = $teachers;
- if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED) {
- $params['notifications'] = $show_notification;
- }
- return $params;
- }
- /**
- * Get the course id based on the original id and field name in the extra fields.
- * Returns 0 if course was not found.
- *
- * @param string $original_course_id_value Original course id
- * @param string $original_course_id_name Original field name
- *
- * @return int Course id
- */
- public static function get_course_id_from_original_id($original_course_id_value, $original_course_id_name)
- {
- $extraFieldValue = new ExtraFieldValue('course');
- $value = $extraFieldValue->get_item_id_from_field_variable_and_field_value(
- $original_course_id_name,
- $original_course_id_value
- );
- if ($value) {
- return $value['item_id'];
- }
- return 0;
- }
- /**
- * Helper function to create a default gradebook (if necessary) upon course creation.
- *
- * @param int $modelId The gradebook model ID
- * @param string $courseCode Course code
- */
- public static function createDefaultGradebook($modelId, $courseCode)
- {
- if (api_get_setting('gradebook_enable_grade_model') === 'true') {
- //Create gradebook_category for the new course and add
- // a gradebook model for the course
- if (isset($modelId) &&
- !empty($modelId) &&
- $modelId != '-1'
- ) {
- GradebookUtils::create_default_course_gradebook(
- $courseCode,
- $modelId
- );
- }
- }
- }
- /**
- * Helper function to check if there is a course template and, if so, to
- * copy the template as basis for the new course.
- *
- * @param string $courseCode Course code
- * @param int $courseTemplate 0 if no course template is defined
- */
- public static function useTemplateAsBasisIfRequired($courseCode, $courseTemplate)
- {
- $template = api_get_setting('course_creation_use_template');
- $teacherCanSelectCourseTemplate = api_get_setting('teacher_can_select_course_template') === 'true';
- $courseTemplate = isset($courseTemplate) ? intval($courseTemplate) : 0;
- $useTemplate = false;
- if ($teacherCanSelectCourseTemplate && $courseTemplate) {
- $useTemplate = true;
- $originCourse = api_get_course_info_by_id($courseTemplate);
- } elseif (!empty($template)) {
- $useTemplate = true;
- $originCourse = api_get_course_info_by_id($template);
- }
- if ($useTemplate) {
- // Include the necessary libraries to generate a course copy
- // Call the course copy object
- $originCourse['official_code'] = $originCourse['code'];
- $cb = new CourseBuilder(null, $originCourse);
- $course = $cb->build(null, $originCourse['code']);
- $cr = new CourseRestorer($course);
- $cr->set_file_option();
- $cr->restore($courseCode);
- }
- }
- /**
- * Helper method to get the number of users defined with a specific course extra field.
- *
- * @param string $name Field title
- * @param string $tableExtraFields The extra fields table name
- * @param string $tableUserFieldValues The user extra field value table name
- *
- * @return int The number of users with this extra field with a specific value
- */
- public static function getCountRegisteredUsersWithCourseExtraField(
- $name,
- $tableExtraFields = '',
- $tableUserFieldValues = ''
- ) {
- if (empty($tableExtraFields)) {
- $tableExtraFields = Database::get_main_table(TABLE_EXTRA_FIELD);
- }
- if (empty($tableUserFieldValues)) {
- $tableUserFieldValues = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
- }
- $registered_users_with_extra_field = 0;
- if (!empty($name) && $name != '-') {
- $extraFieldType = EntityExtraField::COURSE_FIELD_TYPE;
- $name = Database::escape_string($name);
- $sql = "SELECT count(v.item_id) as count
- FROM $tableUserFieldValues v
- INNER JOIN $tableExtraFields f
- ON (f.id = v.field_id)
- WHERE value = '$name' AND extra_field_type = $extraFieldType";
- $result_count = Database::query($sql);
- if (Database::num_rows($result_count)) {
- $row_count = Database::fetch_array($result_count);
- $registered_users_with_extra_field = $row_count['count'];
- }
- }
- return $registered_users_with_extra_field;
- }
- /**
- * Get the course categories form a course list.
- *
- * @param array $courseList
- *
- * @return array
- */
- public static function getCourseCategoriesFromCourseList(array $courseList)
- {
- $allCategories = array_column($courseList, 'category');
- $categories = array_unique($allCategories);
- sort($categories);
- return $categories;
- }
- /**
- * Display the description button of a course in the course catalog.
- *
- * @param array $course
- *
- * @return string HTML string
- */
- public static function returnDescriptionButton($course)
- {
- if (empty($course)) {
- return '';
- }
- if (api_get_setting('show_courses_descriptions_in_catalog') == 'true') {
- $title = $course['title'];
- $url = api_get_path(WEB_CODE_PATH).'inc/ajax/course_home.ajax.php?a=show_course_information&code='.$course['code'];
- $html = Display::url(
- Display::returnFontAwesomeIcon('info-circle', 'lg'),
- $url,
- [
- 'class' => 'ajax btn btn-default btn-sm',
- 'data-title' => $title,
- 'title' => get_lang('Description'),
- 'aria-label' => get_lang('Description'),
- 'data-size' => 'lg',
- ]
- );
- return $html;
- }
- return '';
- }
- /**
- * @param Course $course
- *
- * @return bool
- */
- public static function hasPicture(Course $course)
- {
- return file_exists(api_get_path(SYS_COURSE_PATH).$course->getDirectory().'/course-pic85x85.png');
- }
- /**
- * Get the course picture path.
- *
- * @param Course $course
- * @param bool $fullSize
- *
- * @return string|null
- */
- public static function getPicturePath(Course $course, $fullSize = false)
- {
- if (!self::hasPicture($course)) {
- return null;
- }
- if ($fullSize) {
- return api_get_path(WEB_COURSE_PATH).$course->getDirectory().'/course-pic.png';
- }
- return api_get_path(WEB_COURSE_PATH).$course->getDirectory().'/course-pic85x85.png';
- }
- /**
- * @return int
- */
- public static function getCountOpenCourses()
- {
- $visibility = [
- COURSE_VISIBILITY_REGISTERED,
- COURSE_VISIBILITY_OPEN_PLATFORM,
- COURSE_VISIBILITY_OPEN_WORLD,
- ];
- $table = Database::get_main_table(TABLE_MAIN_COURSE);
- $sql = "SELECT count(id) count
- FROM $table
- WHERE visibility IN (".implode(',', $visibility).")";
- $result = Database::query($sql);
- $row = Database::fetch_array($result);
- return (int) $row['count'];
- }
- /**
- * @return int
- */
- public static function getCountExercisesFromOpenCourse()
- {
- $visibility = [
- COURSE_VISIBILITY_REGISTERED,
- COURSE_VISIBILITY_OPEN_PLATFORM,
- COURSE_VISIBILITY_OPEN_WORLD,
- ];
- $table = Database::get_main_table(TABLE_MAIN_COURSE);
- $tableExercise = Database::get_course_table(TABLE_QUIZ_TEST);
- $sql = "SELECT count(e.iid) count
- FROM $table c INNER JOIN $tableExercise e
- ON (c.id = e.c_id)
- WHERE e.active <> -1 AND visibility IN (".implode(',', $visibility).")";
- $result = Database::query($sql);
- $row = Database::fetch_array($result);
- return (int) $row['count'];
- }
- /**
- * Check if a specific access-url-related setting is a problem or not.
- *
- * @param array $_configuration The $_configuration array
- * @param int $accessUrlId The access URL ID
- * @param string $param
- * @param string $msgLabel
- *
- * @return bool|string
- */
- private static function checkCreateCourseAccessUrlParam($_configuration, $accessUrlId, $param, $msgLabel)
- {
- if (isset($_configuration[$accessUrlId][$param]) && $_configuration[$accessUrlId][$param] > 0) {
- $num = self::count_courses($accessUrlId);
- if ($num >= $_configuration[$accessUrlId][$param]) {
- api_warn_hosting_contact($param);
- Display::addFlash(
- Display::return_message($msgLabel)
- );
- }
- }
- return false;
- }
- /**
- * Fill course with all necessary items.
- *
- * @param array $courseInfo Course info array
- * @param array $params Parameters from the course creation form
- * @param int $authorId
- */
- private static function fillCourse($courseInfo, $params, $authorId = 0)
- {
- $authorId = empty($authorId) ? api_get_user_id() : (int) $authorId;
- AddCourse::prepare_course_repository($courseInfo['directory']);
- AddCourse::fill_db_course(
- $courseInfo['real_id'],
- $courseInfo['directory'],
- $courseInfo['course_language'],
- $params['exemplary_content'],
- $authorId
- );
- if (isset($params['gradebook_model_id'])) {
- self::createDefaultGradebook(
- $params['gradebook_model_id'],
- $courseInfo['code']
- );
- }
- // If parameter defined, copy the contents from a specific
- // template course into this new course
- if (isset($params['course_template'])) {
- self::useTemplateAsBasisIfRequired(
- $courseInfo['id'],
- $params['course_template']
- );
- }
- $params['course_code'] = $courseInfo['code'];
- $params['item_id'] = $courseInfo['real_id'];
- $courseFieldValue = new ExtraFieldValue('course');
- $courseFieldValue->saveFieldValues($params);
- }
- }
|