course.lib.php 240 KB

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