course.lib.php 222 KB

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