course.lib.php 237 KB

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