course.lib.php 234 KB

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