course.lib.php 236 KB

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