course.lib.php 222 KB

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