course.lib.php 238 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986
  1. <?php
  2. /* For licensing terms, see /license.txt*/
  3. /**
  4. * This is the course library for Chamilo.
  5. *
  6. * All main course functions should be placed here.
  7. *
  8. *
  9. * The implementation changed, initially a course was a real course
  10. * if target_course_code was 0 , this was changed to NULL.
  11. * There are probably some places left with the wrong code.
  12. *
  13. * @package chamilo.library
  14. */
  15. /**
  16. * CourseManager Class
  17. * @package chamilo.library
  18. */
  19. class CourseManager
  20. {
  21. const MAX_COURSE_LENGTH_CODE = 40;
  22. //This constant is used to show separate user names in the course list (userportal), footer, etc
  23. const USER_SEPARATOR = ' |';
  24. public $columns = array();
  25. /**
  26. * Creates a course
  27. * @param array with the columns in the main.course table
  28. * @param mixed false if the course was not created, array with the course info
  29. * @return mixed False on error, or an array with course attributes on success
  30. * @todo remove globals
  31. * @assert () === false
  32. */
  33. public static function create_course($params)
  34. {
  35. global $_configuration;
  36. // Check portal limits
  37. $access_url_id = 1;
  38. if (api_get_multiple_access_url()) {
  39. $access_url_id = api_get_current_access_url_id();
  40. }
  41. if (is_array($_configuration[$access_url_id]) && isset($_configuration[$access_url_id]['hosting_limit_courses']) && $_configuration[$access_url_id]['hosting_limit_courses'] > 0) {
  42. $num = self::count_courses();
  43. if ($num >= $_configuration[$access_url_id]['hosting_limit_courses']) {
  44. return api_set_failure('PortalCoursesLimitReached');
  45. }
  46. }
  47. if (empty($params['title'])) {
  48. return false;
  49. }
  50. if (empty($params['wanted_code'])) {
  51. $params['wanted_code'] = $params['title'];
  52. // Check whether the requested course code has already been occupied.
  53. $params['wanted_code'] = self::generate_course_code(api_substr($params['title'], 0, self::MAX_COURSE_LENGTH_CODE));
  54. }
  55. // Create the course keys
  56. $keys = self::define_course_keys($params['wanted_code']);
  57. $params['exemplary_content'] = isset($params['exemplary_content']) ? $params['exemplary_content'] : false;
  58. if (count($keys)) {
  59. $params['code'] = $keys['currentCourseCode'];
  60. $params['visual_code'] = $keys['currentCourseId'];
  61. $params['directory'] = $keys['currentCourseRepository'];
  62. $course_info = api_get_course_info($params['code']);
  63. if (empty($course_info)) {
  64. $course_id = self::register_course($params);
  65. $course_info = api_get_course_info_by_id($course_id);
  66. if (!empty($course_info)) {
  67. self::prepare_course_repository($course_info['directory'], $course_info['code']);
  68. self::fill_db_course($course_id, $course_info['directory'], $course_info['course_language'], $params['exemplary_content']);
  69. //Create an empty gradebook
  70. if (isset($params['create_gradebook_evaluation']) && $params['create_gradebook_evaluation'] == true) {
  71. require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/gradebook_functions.inc.php';
  72. $category_id = create_default_course_gradebook($course_info['code']);
  73. if ($category_id && isset($params['gradebook_params'])) {
  74. $eval = new Evaluation();
  75. $eval->set_name($params['gradebook_params']['name']);
  76. $eval->set_user_id($params['gradebook_params']['user_id']);
  77. $eval->set_course_code($course_info['code']);
  78. $eval->set_category_id($category_id);
  79. $eval->set_weight($params['gradebook_params']['weight']);
  80. $eval->set_max($params['gradebook_params']['max']);
  81. $eval->set_visible(0);
  82. $eval->add();
  83. }
  84. }
  85. if (api_get_setting('gradebook_enable_grade_model') == 'true') {
  86. //Create gradebook_category for the new course and add a gradebook model for the course
  87. if (isset($params['gradebook_model_id']) && !empty($params['gradebook_model_id']) && $params['gradebook_model_id'] != '-1') {
  88. require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/gradebook_functions.inc.php';
  89. create_default_course_gradebook($course_info['code'], $params['gradebook_model_id']);
  90. }
  91. }
  92. //Saving extra course fields
  93. $field_value = new ExtraFieldValue('course');
  94. $params['course_code'] = $course_info['code'];
  95. $field_value->save_field_values($params);
  96. return $course_info;
  97. }
  98. } else {
  99. //Course already exists
  100. if (isset($params['return_item_if_already_exists']) && $params['return_item_if_already_exists']) {
  101. return $course_info;
  102. }
  103. }
  104. }
  105. return false;
  106. }
  107. /**
  108. * Updates a course with the given array of attributes
  109. * @param array Array of attributes
  110. * @return array Array of course attributes
  111. * @assert () === false
  112. */
  113. public static function update($params)
  114. {
  115. if (!is_array($params) or count($params)<1) {
  116. return false;
  117. }
  118. $course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  119. $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
  120. $course_code = $params['code'];
  121. $courseInfo = api_get_course_info($course_code);
  122. $visual_code = $params['visual_code'];
  123. $field_value = new ExtraFieldValue('course');
  124. $params['course_code'] = $course_code;
  125. $field_value->save_field_values($params);
  126. /*$tutor_id = $params['tutor_name'];
  127. $tutor_name=$platform_teachers[$tutor_id];*/
  128. $teachers = $params['group']['course_teachers'];
  129. $title = $params['title'];
  130. $category_code = $params['category_code'];
  131. $department_name = $params['department_name'];
  132. $department_url = $params['department_url'];
  133. $course_language = $params['course_language'];
  134. $course['disk_quota'] = $params['disk_quota']*1024*1024;
  135. $disk_quota = $params['disk_quota'];
  136. $visibility = $params['visibility'];
  137. $subscribe = $params['subscribe'];
  138. $unsubscribe = $params['unsubscribe'];
  139. if (!stristr($department_url, 'http://')) {
  140. $department_url = 'http://'.$department_url;
  141. }
  142. //tutor_name='".Database::escape_string($tutor_name)."',
  143. $sql = "UPDATE $course_table SET
  144. course_language='".Database::escape_string($course_language)."',
  145. title='".Database::escape_string($title)."',
  146. category_code='".Database::escape_string($category_code)."',
  147. visual_code='".Database::escape_string($visual_code)."',
  148. department_name='".Database::escape_string($department_name)."',
  149. department_url='".Database::escape_string($department_url)."',
  150. disk_quota='".Database::escape_string($disk_quota)."',
  151. visibility = '".Database::escape_string($visibility)."',
  152. subscribe = '".Database::escape_string($subscribe)."',
  153. unsubscribe='".Database::escape_string($unsubscribe)."'
  154. WHERE code='".Database::escape_string($course_code)."'";
  155. Database::query($sql);
  156. //Delete only teacher relations that doesn't match the selected teachers
  157. $cond='';
  158. if (count($teachers)>0) {
  159. foreach($teachers as $key) {
  160. $cond.=" AND user_id<>'".$key."'";
  161. }
  162. }
  163. $sql = 'DELETE FROM '.$course_user_table.' WHERE c_id = "'.Database::escape_string($courseInfo['real_id']).'" AND status="1"'.$cond;
  164. Database::query($sql);
  165. if (count($teachers)>0) {
  166. foreach ($teachers as $key) {
  167. //We check if the teacher is already subscribed in this course
  168. $sql_select_teacher = 'SELECT 1 FROM '.$course_user_table.' WHERE user_id = "'.$key.'" AND c_id = "'.$courseInfo['real_id'].'" ';
  169. $result = Database::query($sql_select_teacher);
  170. if (Database::num_rows($result) == 1) {
  171. $sql = 'UPDATE '.$course_user_table.' SET status = "1" WHERE c_id = "'.$courseInfo['real_id'].'" AND user_id = "'.$key.'" ';
  172. } else {
  173. $sql = "INSERT INTO ".$course_user_table . " SET
  174. c_id = '".Database::escape_string($courseInfo['real_id']). "',
  175. user_id = '".$key . "',
  176. status = '1',
  177. role = '',
  178. tutor_id = '0',
  179. sort = '0',
  180. user_course_cat = '0'";
  181. }
  182. Database::query($sql);
  183. }
  184. }
  185. //user_id = '".$tutor_id . "',
  186. $sql = "INSERT IGNORE INTO ".$course_user_table . " SET
  187. course_code = '".Database::escape_string($course_code). "',
  188. status = '1',
  189. role = '',
  190. tutor_id='0',
  191. sort='0',
  192. user_course_cat='0'";
  193. Database::query($sql);
  194. $course_info = api_get_course_info($course_code);
  195. return $course_info;
  196. }
  197. /**
  198. * Returns all the information of a given coursecode from the course table
  199. * @param string $course_code, the course code
  200. * @return an array with all the fields of the course table
  201. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  202. * @assert (array(1,2,3)) === false
  203. */
  204. public static function get_course_information($course_code)
  205. {
  206. return Database::fetch_array(Database::query(
  207. "SELECT *, id as real_id FROM ".Database::get_main_table(TABLE_MAIN_COURSE)."
  208. WHERE code='".Database::escape_string($course_code)."'"),'ASSOC'
  209. );
  210. }
  211. /**
  212. * Returns all the information of a given coursecode from the course
  213. * table by it integer ID
  214. * @param int the course id
  215. * @return an array with all the fields of the course table
  216. * @assert (-1) === false
  217. */
  218. public static function get_course_information_by_id($course_id)
  219. {
  220. return Database::select('*, id as real_id', Database::get_main_table(TABLE_MAIN_COURSE), array('where'=>array('id = ?' =>intval($course_id))),'first');
  221. }
  222. /**
  223. * Returns a list of courses. Should work with quickform syntax
  224. * @param integer Offset (from the 7th = '6'). Optional.
  225. * @param integer Number of results we want. Optional.
  226. * @param string The column we want to order it by. Optional, defaults to first column.
  227. * @param string The direction of the order (ASC or DESC). Optional, defaults to ASC.
  228. * @param string The visibility of the course, or all by default.
  229. * @param string If defined, only return results for which the course *title* begins with this string
  230. * @return mixed Array of courses details, or false on error
  231. * @assert (array(1,2,3)) === false
  232. */
  233. public static function get_courses_list($from = 0, $howmany = 0, $orderby = 1, $orderdirection = 'ASC', $visibility = -1, $startwith = '')
  234. {
  235. $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE)." ";
  236. if (!empty($startwith)) {
  237. $sql .= "WHERE title LIKE '".Database::escape_string($startwith)."%' ";
  238. if ($visibility !== -1 && $visibility == strval(intval($visibility))) {
  239. $sql .= " AND visibility = $visibility ";
  240. }
  241. } else {
  242. $sql .= "WHERE 1 ";
  243. if ($visibility !== -1 && $visibility == strval(intval($visibility))) {
  244. $sql .= " AND visibility = $visibility ";
  245. }
  246. }
  247. if (!empty($orderby)) {
  248. $sql .= " ORDER BY ".Database::escape_string($orderby)." ";
  249. } else {
  250. $sql .= " ORDER BY 1 ";
  251. }
  252. if (!in_array($orderdirection, array('ASC', 'DESC'))) {
  253. $sql .= 'ASC';
  254. } else {
  255. $sql .= Database::escape_string($orderdirection);
  256. }
  257. if (!empty($howmany) && is_int($howmany) and $howmany > 0) {
  258. $sql .= ' LIMIT '.Database::escape_string($howmany);
  259. } else {
  260. $sql .= ' LIMIT 1000000'; //virtually no limit
  261. }
  262. if (!empty($from)) {
  263. $from = intval($from);
  264. $sql .= ' OFFSET '.Database::escape_string($from);
  265. } else {
  266. $sql .= ' OFFSET 0';
  267. }
  268. return Database::store_result(Database::query($sql));
  269. }
  270. /**
  271. * Returns the access settings of the course:
  272. * which visibility;
  273. * wether subscribing is allowed;
  274. * wether unsubscribing is allowed.
  275. *
  276. * @param string $course_code, the course code
  277. * @todo for more consistency: use course_info call from database API
  278. * @return an array with int fields "visibility", "subscribe", "unsubscribe"
  279. * @assert () === false
  280. */
  281. public static function get_access_settings($course_code)
  282. {
  283. return Database::fetch_array(Database::query(
  284. "SELECT visibility, subscribe, unsubscribe from ".Database::get_main_table(TABLE_MAIN_COURSE)."
  285. WHERE code = '".Database::escape_string($course_code)."'")
  286. );
  287. }
  288. /**
  289. * Returns the status of a user in a course, which is COURSEMANAGER
  290. * or STUDENT.
  291. * @param int User ID
  292. * @param string Course code
  293. * @return int the status of the user in that course
  294. * @assert () === false
  295. */
  296. public static function get_user_in_course_status($user_id, $courseId)
  297. {
  298. $result = Database::fetch_array(Database::query(
  299. "SELECT status FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  300. WHERE c_id = '".Database::escape_string($courseId)."' AND user_id = ".Database::escape_string($user_id))
  301. );
  302. return $result['status'];
  303. }
  304. /**
  305. * Gets the ID of a course tutor for a user, given the user and the course
  306. * @param int User ID
  307. * @param string Course code
  308. * @return mixed The tutor ID
  309. * @assert () === false
  310. */
  311. public static function get_tutor_in_course_status($user_id, $courseId)
  312. {
  313. $result = Database::fetch_array(Database::query(
  314. "SELECT tutor_id FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  315. WHERE c_id = '".Database::escape_string($courseId)."' AND user_id = ".Database::escape_string($user_id))
  316. );
  317. return $result['tutor_id'];
  318. }
  319. /**
  320. * Unsubscribe one or more users from a course
  321. * @param mixed user_id or an array with user ids
  322. * @param int session id
  323. * @param int course id
  324. * @return mixed False on user ID not found, void otherwise
  325. * @assert () === false
  326. */
  327. public static function unsubscribe_user($user_id, $courseId, $session_id = 0)
  328. {
  329. if (!isset($user_id)) {
  330. return false;
  331. }
  332. if (!is_array($user_id)) {
  333. $user_id = array($user_id);
  334. }
  335. if (count($user_id) == 0) {
  336. return false;
  337. }
  338. $table_user = Database :: get_main_table(TABLE_MAIN_USER);
  339. if (!empty($session_id)) {
  340. $session_id = intval($session_id);
  341. } else {
  342. $session_id = api_get_session_id();
  343. }
  344. $user_list = array();
  345. //Cleaning the $user_id variable
  346. if (is_array($user_id)) {
  347. $new_user_id_list = array();
  348. foreach ($user_id as $my_user_id) {
  349. $new_user_id_list[]= intval($my_user_id);
  350. }
  351. $new_user_id_list = array_filter($new_user_id_list);
  352. $user_list = $new_user_id_list;
  353. $user_ids = implode(',', $new_user_id_list);
  354. } else {
  355. $user_ids = intval($user_id);
  356. $user_list[] = $user_id;
  357. }
  358. $courseId = intval($courseId);
  359. $courseInfo = api_get_course_info_by_id($courseId);
  360. $courseCode = $courseInfo['code'];
  361. // Unsubscribe user from all groups in the course.
  362. Database::query("DELETE FROM ".Database::get_course_table(TABLE_GROUP_USER)." WHERE c_id = $courseId AND user_id IN (".$user_ids.")");
  363. Database::query("DELETE FROM ".Database::get_course_table(TABLE_GROUP_TUTOR)." WHERE c_id = $courseId AND user_id IN (".$user_ids.")");
  364. // Erase user student publications (works) in the course - by André Boivin
  365. //@todo field student_publication.author should be the user id
  366. $sqlu = "SELECT * FROM $table_user WHERE user_id IN (".$user_ids.")";
  367. $resu = Database::query($sqlu);
  368. $username = Database::fetch_array($resu,'ASSOC');
  369. $userfirstname = $username['firstname'];
  370. $userlastname = $username['lastname'];
  371. $publication_name = $userfirstname.' '.$userlastname ;
  372. $table_course_user_publication = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
  373. $sql = "DELETE FROM $table_course_user_publication WHERE c_id = $courseId AND author = '".Database::escape_string($publication_name)."'";
  374. Database::query($sql);
  375. // Unsubscribe user from all blogs in the course.
  376. Database::query("DELETE FROM ".Database::get_course_table(TABLE_BLOGS_REL_USER)." WHERE c_id = $courseId AND user_id IN (".$user_ids.")");
  377. Database::query("DELETE FROM ".Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER)." WHERE c_id = $courseId AND user_id IN (".$user_ids.")");
  378. //Deleting users in forum_notification and mailqueue course tables
  379. $sql_delete_forum_notification = "DELETE FROM ".Database::get_course_table(TABLE_FORUM_NOTIFICATION)." WHERE c_id = $courseId AND user_id IN (".$user_ids.")";
  380. Database::query($sql_delete_forum_notification);
  381. $sql_delete_mail_queue = "DELETE FROM ".Database::get_course_table(TABLE_FORUM_MAIL_QUEUE)." WHERE c_id = $courseId AND user_id IN (".$user_ids.")";
  382. Database::query($sql_delete_mail_queue);
  383. $item_property_lp_subscription = "DELETE FROM ".Database::get_course_table(TABLE_ITEM_PROPERTY)."
  384. WHERE lastedit_type = 'LearnpathSubscription' AND tool = 'learnpath' AND c_id = $courseId AND to_user_id IN (".$user_ids.")";
  385. Database::query($item_property_lp_subscription);
  386. // Unsubscribe user from the course.
  387. if (!empty($session_id)) {
  388. // Delete in table session_rel_course_rel_user
  389. Database::query("DELETE FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)."
  390. WHERE id_session ='".$session_id."' AND c_id = '".$courseId."' AND id_user IN ($user_ids)");
  391. foreach ($user_id as $uid) {
  392. // check if a user is register in the session with other course
  393. $sql = "SELECT id_user FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)." WHERE id_session='$session_id' AND id_user='$uid'";
  394. $rs = Database::query($sql);
  395. if (Database::num_rows($rs) == 0) {
  396. // Delete in table session_rel_user
  397. Database::query("DELETE FROM ".Database::get_main_table(TABLE_MAIN_SESSION_USER)."
  398. WHERE id_session ='".$session_id."' AND id_user='$uid' AND relation_type<>".SESSION_RELATION_TYPE_RRHH."");
  399. }
  400. }
  401. // Update the table session
  402. $row = Database::fetch_array(Database::query("SELECT COUNT(*) FROM ".Database::get_main_table(TABLE_MAIN_SESSION_USER)."
  403. WHERE id_session = '".$session_id."' AND relation_type<>".SESSION_RELATION_TYPE_RRHH." "));
  404. $count = $row[0]; // number of users by session
  405. $result = Database::query("UPDATE ".Database::get_main_table(TABLE_MAIN_SESSION)." SET nbr_users = '$count'
  406. WHERE id = '".$session_id."'");
  407. // Update the table session_rel_course
  408. $row = Database::fetch_array(@Database::query("SELECT COUNT(*) FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)."
  409. WHERE id_session = '$session_id' AND c_id = '$courseId' AND status<>2" ));
  410. $count = $row[0]; // number of users by session and course
  411. $result = @Database::query("UPDATE ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE)." SET nbr_users = '$count' WHERE id_session = '$session_id' AND c_id = '$courseId' ");
  412. } else {
  413. Database::query("DELETE FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  414. WHERE user_id IN (".$user_ids.") AND relation_type<>".COURSE_RELATION_TYPE_RRHH." AND c_id = '".$courseId."'");
  415. // add event to system log
  416. $user_id = api_get_user_id();
  417. event_system(LOG_UNSUBSCRIBE_USER_FROM_COURSE, LOG_COURSE_CODE, $courseCode, api_get_utc_datetime(), $user_id);
  418. foreach ($user_list as $user_id_to_delete) {
  419. $user_info = api_get_user_info($user_id_to_delete);
  420. event_system(LOG_UNSUBSCRIBE_USER_FROM_COURSE, LOG_USER_OBJECT, $user_info, api_get_utc_datetime(), $user_id);
  421. }
  422. }
  423. }
  424. /**
  425. * Subscribe a user to a course. No checks are performed here to see if
  426. * course subscription is allowed.
  427. * @param int User ID
  428. * @param string Course code
  429. * @param int Status (STUDENT, COURSEMANAGER, COURSE_ADMIN, NORMAL_COURSE_MEMBER)
  430. * @return bool True on success, false on failure
  431. * @see add_user_to_course
  432. */
  433. public static function subscribe_user($user_id, $course_code, $status = STUDENT, $session_id = 0)
  434. {
  435. if ($user_id != strval(intval($user_id))) {
  436. return false; //detected possible SQL injection
  437. }
  438. $course_code = Database::escape_string($course_code);
  439. $courseInfo = api_get_course_info($course_code);
  440. $courseId = $courseInfo['real_id'];
  441. if (empty($user_id) || empty ($course_code)) {
  442. return false;
  443. }
  444. if (!empty($session_id)) {
  445. $session_id = intval($session_id);
  446. } else {
  447. $session_id = api_get_session_id();
  448. }
  449. $status = ($status == STUDENT || $status == COURSEMANAGER) ? $status : STUDENT;
  450. //$role_id = ($status == COURSEMANAGER) ? COURSE_ADMIN : NORMAL_COURSE_MEMBER;
  451. // A preliminary check whether the user has bben already registered on the platform.
  452. if (Database::num_rows(@Database::query("SELECT status FROM ".Database::get_main_table(TABLE_MAIN_USER)."
  453. WHERE user_id = '$user_id' ")) == 0) {
  454. return false; // The user has not been registered to the platform.
  455. }
  456. // Check whether the user has not been already subscribed to the course.
  457. if (empty($session_id)) {
  458. if (Database::num_rows(@Database::query("SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  459. WHERE user_id = '$user_id' AND relation_type<>".COURSE_RELATION_TYPE_RRHH." AND c_id = ".$courseId)) > 0) {
  460. return false; // The user has been already subscribed to the course.
  461. }
  462. }
  463. if (!empty($session_id)) {
  464. // Check whether the user has not already been stored in the session_rel_course_user table
  465. if (Database::num_rows(@Database::query("SELECT * FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)."
  466. WHERE c_id = '".$courseId."'
  467. AND id_session ='".$session_id."'
  468. AND id_user = '".$user_id."'")) > 0) {
  469. return false;
  470. }
  471. // check if the user is registered in the session with other course
  472. $sql = "SELECT id_user FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)." WHERE id_session='".$session_id."' AND id_user='$user_id'";
  473. $rs = Database::query($sql);
  474. if (Database::num_rows($rs) == 0) {
  475. // Check whether the user has not already been stored in the session_rel_user table
  476. if (Database::num_rows(@Database::query("SELECT * FROM ".Database::get_main_table(TABLE_MAIN_SESSION_USER)."
  477. WHERE id_session ='".$session_id."' AND id_user = '".$user_id."' AND relation_type<>".SESSION_RELATION_TYPE_RRHH." ")) > 0) {
  478. return false;
  479. }
  480. }
  481. // Add him/her in the table session_rel_course_rel_user
  482. @Database::query("INSERT INTO ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)."
  483. SET id_session ='".$session_id."',
  484. c_id = '".$courseId."',
  485. id_user = '".$user_id."'");
  486. // Add him/her in the table session_rel_user
  487. @Database::query("INSERT INTO ".Database::get_main_table(TABLE_MAIN_SESSION_USER)."SET id_session ='".$session_id."', id_user = '".$user_id."'");
  488. // Update the table session
  489. $row = Database::fetch_array(@Database::query("SELECT COUNT(*) FROM ".Database::get_main_table(TABLE_MAIN_SESSION_USER)."
  490. WHERE id_session = '".$session_id."' AND relation_type<>".SESSION_RELATION_TYPE_RRHH.""));
  491. $count = $row[0]; // number of users by session
  492. $result = @Database::query("UPDATE ".Database::get_main_table(TABLE_MAIN_SESSION)." SET nbr_users = '$count' WHERE id = '".$session_id."'");
  493. // Update the table session_rel_course
  494. $row = Database::fetch_array(@Database::query("SELECT COUNT(*) FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)."
  495. WHERE id_session = '".$session_id."' AND c_id = ".$courseId." AND status <> 2" ));
  496. $count = $row[0]; // number of users by session
  497. $result = @Database::query("UPDATE ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE)." SET nbr_users = '$count'
  498. WHERE id_session = '".$session_id."' AND c_id = '$courseId' ");
  499. } else {
  500. $course_sort = self::userCourseSort($user_id, $courseId);
  501. $result = @Database::query("INSERT INTO ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  502. SET
  503. c_id = ".$courseId.",
  504. user_id = '$user_id',
  505. status = '".$status."',
  506. sort = '". ($course_sort)."'");
  507. // Add event to the system log
  508. event_system(LOG_SUBSCRIBE_USER_TO_COURSE, LOG_COURSE_CODE, $course_code, api_get_utc_datetime(), api_get_user_id());
  509. $user_info = api_get_user_info($user_id);
  510. event_system(LOG_SUBSCRIBE_USER_TO_COURSE, LOG_USER_OBJECT, $user_info, api_get_utc_datetime(), api_get_user_id());
  511. }
  512. return (bool)$result;
  513. }
  514. /**
  515. * Get the course id based on the original id and field name in the extra fields. Returns 0 if course was not found
  516. *
  517. * @param string Original course id
  518. * @param string Original field name
  519. * @return int Course id
  520. * @assert ('', '') === false
  521. */
  522. public static function get_course_code_from_original_id($original_course_id_value, $original_course_id_name) {
  523. $t_cfv = Database::get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
  524. $table_field = Database::get_main_table(TABLE_MAIN_COURSE_FIELD);
  525. $sql_course = "SELECT course_code FROM $table_field cf INNER JOIN $t_cfv cfv ON cfv.field_id=cf.id
  526. WHERE field_variable='$original_course_id_name' AND field_value='$original_course_id_value'";
  527. $res = Database::query($sql_course);
  528. $row = Database::fetch_object($res);
  529. if ($row) {
  530. return $row->course_code;
  531. } else {
  532. return 0;
  533. }
  534. }
  535. /**
  536. * Gets the course code from the course id. Returns null if course id was not found
  537. *
  538. * @param int Course id
  539. * @return string Course code
  540. * @assert ('') === false
  541. */
  542. public static function get_course_code_from_course_id($id) {
  543. $table = Database::get_main_table(TABLE_MAIN_COURSE);
  544. $id = intval($id);
  545. $sql = "SELECT code FROM $table WHERE id = '$id' ";
  546. $res = Database::query($sql);
  547. $row = Database::fetch_object($res);
  548. if ($row) {
  549. return $row->code;
  550. } else {
  551. return null;
  552. }
  553. }
  554. /**
  555. * Subscribe a user $user_id to a course $course_code.
  556. * @author Hugues Peeters
  557. * @author Roan Embrechts
  558. *
  559. * @param int $user_id the id of the user
  560. * @param int $courseId the course code
  561. * @param string $status (optional) The user's status in the course
  562. *
  563. * @return boolean true if subscription succeeds, boolean false otherwise.
  564. * @assert ('', '') === false
  565. */
  566. public static function add_user_to_course($user_id, $courseId, $status = STUDENT) {
  567. $debug = false;
  568. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  569. $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
  570. $course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  571. $status = ($status == STUDENT || $status == COURSEMANAGER) ? $status : STUDENT;
  572. if (empty($user_id) || empty($courseId) || ($user_id != strval(intval($user_id)))) {
  573. return false;
  574. }
  575. $courseId = Database::escape_string($courseId);
  576. // Check in advance whether the user has already been registered on the platform.
  577. if (Database::num_rows(Database::query("SELECT status FROM ".$user_table." WHERE user_id = '$user_id' ")) == 0) {
  578. if ($debug) error_log('The user has not been registered to the platform');
  579. return false; // The user has not been registered to the platform.
  580. }
  581. // Check whether the user has already been subscribed to this course.
  582. if (Database::num_rows(Database::query("SELECT * FROM ".$course_user_table." WHERE user_id = '$user_id' AND relation_type<>".COURSE_RELATION_TYPE_RRHH." AND c_id = '$courseId'")) > 0) {
  583. if ($debug) error_log('The user has been already subscribed to the course');
  584. return false; // The user has been subscribed to the course.
  585. }
  586. // Check in advance whether subscription is allowed or not for this course.
  587. if (Database::num_rows(Database::query("SELECT code, visibility FROM ".$course_table." WHERE id = '$courseId' AND subscribe = '".SUBSCRIBE_NOT_ALLOWED."'")) > 0) {
  588. if ($debug) error_log('Subscription is not allowed for this course');
  589. return false; // Subscription is not allowed for this course.
  590. }
  591. // Ok, subscribe the user.
  592. $max_sort = api_max_sort_value('0', $user_id);
  593. return (bool)Database::query("INSERT INTO ".$course_user_table."
  594. SET c_id = '$courseId',
  595. user_id = '$user_id',
  596. status = '".$status."',
  597. sort = '". ($max_sort + 1)."'");
  598. }
  599. /**
  600. * @return true if there already are one or more courses
  601. * with the same code OR visual_code (visualcode), false otherwise
  602. */
  603. public static function course_code_exists($wanted_course_code) {
  604. $wanted_course_code = Database::escape_string($wanted_course_code);
  605. $result = Database::fetch_array(Database::query("SELECT COUNT(*) as number FROM ".Database::get_main_table(TABLE_MAIN_COURSE)."
  606. WHERE code = '$wanted_course_code' OR visual_code = '$wanted_course_code'"));
  607. return $result['number'] > 0;
  608. }
  609. /**
  610. * @return an array with the course info of all real courses on the platform
  611. */
  612. public static function get_real_course_list() {
  613. $sql_result = Database::query("SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE)." WHERE target_course_code IS NULL");
  614. $real_course_list = array();
  615. while ($result = Database::fetch_array($sql_result)) {
  616. $real_course_list[$result['code']] = $result;
  617. }
  618. return $real_course_list;
  619. }
  620. /**
  621. * Get course list as coach
  622. *
  623. * @param int user id
  624. * @return array course list
  625. *
  626. * */
  627. public static function get_course_list_as_coach($user_id, $include_courses_in_sessions = false) {
  628. //1. Getting courses as teacher (No session)
  629. $courses_temp = CourseManager::get_course_list_of_user_as_course_admin($user_id);
  630. $courses_as_admin = array();
  631. if (!empty($courses_temp)) {
  632. foreach($courses_temp as $course_item) {
  633. $courses_as_admin[0][$course_item['real_id']] = $course_item['real_id'];
  634. }
  635. }
  636. //2. Include courses in sessions
  637. if ($include_courses_in_sessions) {
  638. $sessions = SessionManager::get_sessions_coached_by_user($user_id);
  639. if (!empty($sessions)) {
  640. foreach($sessions as $session_item) {
  641. $courses = Tracking :: get_courses_followed_by_coach($user_id, $session_item['id']);
  642. if (is_array($courses)) {
  643. foreach($courses as $course_item) {
  644. $courses_as_admin[$session_item['id']][$course_item] = $course_item;
  645. }
  646. }
  647. }
  648. }
  649. }
  650. return $courses_as_admin;
  651. }
  652. public static function get_user_list_from_courses_as_coach($user_id, $include_sessions = true) {
  653. $students_in_courses = array();
  654. $sessions = CourseManager::get_course_list_as_coach($user_id, true);
  655. if (!empty($sessions)) {
  656. foreach($sessions as $session_id => $courses) {
  657. if (!$include_sessions) {
  658. if (!empty($session_id)) {
  659. continue;
  660. }
  661. }
  662. if (empty($session_id)) {
  663. foreach($courses as $course_code) {
  664. $students_in_course = CourseManager::get_user_list_from_course_code($course_code);
  665. foreach($students_in_course as $user_item) {
  666. //Only students
  667. if ($user_item['status_rel'] == STUDENT)
  668. $students_in_courses[$user_item['user_id']] = $user_item['user_id'];
  669. }
  670. }
  671. } else {
  672. $students_in_course = SessionManager::get_users_by_session($session_id, '0');
  673. if (is_array($students_in_course)) {
  674. foreach ($students_in_course as $user_item) {
  675. if ($user_item['moved_to'] == 0) {
  676. $students_in_courses[$user_item['user_id']] = $user_item['user_id'];
  677. }
  678. }
  679. }
  680. }
  681. }
  682. }
  683. $students = Tracking :: get_student_followed_by_coach($user_id);
  684. if (!empty($students_in_courses)) {
  685. if (!empty($students)) {
  686. $students = array_merge($students, $students_in_courses);
  687. } else {
  688. $students = $students_in_courses;
  689. }
  690. }
  691. if (!empty($students)) {
  692. $students = array_unique($students);
  693. }
  694. return $students;
  695. }
  696. /**
  697. * @return an array with the course info of all the courses of whichthe current user is course admin
  698. */
  699. public static function get_course_list_of_user_as_course_admin($user_id) {
  700. if ($user_id != strval(intval($user_id))) {
  701. return array();
  702. }
  703. // Definitions database tables and variables
  704. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  705. $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  706. $user_id = intval($user_id);
  707. $data = array();
  708. $sql_nb_cours = "SELECT course_rel_user.c_id,
  709. course.title, course.id,
  710. course.db_name,
  711. course.id as real_id
  712. FROM $tbl_course_user as course_rel_user
  713. INNER JOIN $tbl_course as course
  714. ON course.id = course_rel_user.c_id
  715. WHERE course_rel_user.user_id='$user_id' AND course_rel_user.status='1'
  716. ORDER BY course.title";
  717. if (api_get_multiple_access_url()) {
  718. $tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  719. $access_url_id = api_get_current_access_url_id();
  720. if ($access_url_id != -1) {
  721. $sql_nb_cours = " SELECT course_rel_user.c_id, course.title, course.id, course.db_name, course.id as real_id
  722. FROM $tbl_course_user as course_rel_user
  723. INNER JOIN $tbl_course as course
  724. ON course.id = course_rel_user.c_id
  725. INNER JOIN $tbl_course_rel_access_url course_rel_url
  726. ON (course_rel_url.c_id = course.id)
  727. WHERE access_url_id = $access_url_id AND course_rel_user.user_id='$user_id' AND course_rel_user.status='1'
  728. ORDER BY course.title";
  729. }
  730. }
  731. $result_nb_cours = Database::query($sql_nb_cours);
  732. if (Database::num_rows($result_nb_cours) > 0) {
  733. while ($row = Database::fetch_array($result_nb_cours,'ASSOC')) {
  734. $data[$row['c_id']] = $row;
  735. }
  736. }
  737. return $data;
  738. }
  739. /**
  740. * Check if user is subscribed inside a course
  741. * @param int User id
  742. * @param string Course code, if this parameter is null, it'll check for all courses
  743. * @param bool True for checking inside sessions too, by default is not checked
  744. * @return bool true if the user is registered in the course, false otherwise
  745. */
  746. public static function is_user_subscribed_in_course($user_id, $courseId = null, $in_a_session = false, $session_id = null) {
  747. $user_id = intval($user_id);
  748. if (empty($session_id)) {
  749. $session_id = api_get_session_id();
  750. } else {
  751. $session_id = intval($session_id);
  752. }
  753. $condition_course_id = null;
  754. if (isset($courseId)) {
  755. $courseId = intval($courseId);
  756. $condition_course_id = ' AND c_id = "'.$courseId.'" ';
  757. }
  758. $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  759. WHERE user_id = $user_id AND relation_type<>".COURSE_RELATION_TYPE_RRHH." $condition_course_id ";
  760. $result = Database::fetch_array(Database::query($sql));
  761. if (!empty($result)) {
  762. return true; // The user has been registered in this course.
  763. }
  764. if (!$in_a_session) {
  765. return false; // The user has not been registered in this course.
  766. }
  767. if (Database::num_rows(Database::query('SELECT 1 FROM '.Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER).
  768. ' WHERE id_user = '.$user_id.' '.$condition_course_id.' ')) > 0) {
  769. return true;
  770. }
  771. if (Database::num_rows(Database::query('SELECT 1 FROM '.Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER).
  772. ' WHERE id_user = '.$user_id.' AND status=2 '.$condition_course_id.' ')) > 0) {
  773. return true;
  774. }
  775. if (Database::num_rows(Database::query('SELECT 1 FROM '.Database::get_main_table(TABLE_MAIN_SESSION).
  776. ' WHERE id='.$session_id.' AND id_coach='.$user_id)) > 0) {
  777. return true;
  778. }
  779. return false;
  780. }
  781. /**
  782. * Is the user a teacher in the given course?
  783. *
  784. * @param int $user_id, the id (int) of the user
  785. * @param int $course_code, the course code
  786. *
  787. * @return true if the user is a teacher in the course, false otherwise
  788. */
  789. public static function is_course_teacher($user_id, $courseId) {
  790. if ($user_id != strval(intval($user_id))) {
  791. return false;
  792. }
  793. $sql_result = Database::query('SELECT status FROM '.Database::get_main_table(TABLE_MAIN_COURSE_USER).
  794. ' WHERE c_id ="'.Database::escape_string($courseId).'" and user_id="'.$user_id.'"');
  795. if (Database::num_rows($sql_result) > 0) {
  796. return Database::result($sql_result, 0, 'status') == 1;
  797. }
  798. return false;
  799. }
  800. /**
  801. * Is the user subscribed in the real course or linked courses?
  802. *
  803. * @param int the id of the user
  804. * @param array info about the course (comes from course table, see database lib)
  805. *
  806. * @return true if the user is registered in the real course or linked courses, false otherwise
  807. */
  808. public static function is_user_subscribed_in_real_or_linked_course ($user_id, $courseId, $session_id = '') {
  809. if ($user_id != strval(intval($user_id))) {
  810. return false;
  811. }
  812. $session_id = intval($session_id);
  813. $courseId = Database::escape_string($courseId);
  814. if ($session_id == '') {
  815. $result = Database::fetch_array(Database::query("SELECT *
  816. FROM ".Database::get_main_table(TABLE_MAIN_COURSE)." course
  817. LEFT JOIN ".Database::get_main_table(TABLE_MAIN_COURSE_USER)." course_user
  818. ON course.id = course_user.c_id
  819. WHERE course_user.user_id = '$user_id' AND
  820. course_user.relation_type<>".COURSE_RELATION_TYPE_RRHH." AND
  821. course.id = '$courseId'"));
  822. return !empty($result);
  823. }
  824. // From here we trust session id.
  825. // Is he/she subscribed to the session's course?
  826. // A user?
  827. if (Database::num_rows(Database::query("SELECT id_user
  828. FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)."
  829. WHERE id_session='".$session_id."'
  830. AND id_user='$user_id'"))) {
  831. return true;
  832. }
  833. // A course coach?
  834. if (Database::num_rows(Database::query("SELECT id_user
  835. FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)."
  836. WHERE id_session='".$session_id."'
  837. AND id_user = '$user_id' AND status = 2
  838. AND c_id ='$courseId'"))) {
  839. return true;
  840. }
  841. // A session coach?
  842. if (Database::num_rows(Database::query("SELECT id_coach
  843. FROM ".Database::get_main_table(TABLE_MAIN_SESSION)." AS session
  844. WHERE session.id='".$session_id."'
  845. AND id_coach='$user_id'"))) {
  846. return true;
  847. }
  848. return false;
  849. }
  850. /**
  851. * Return user info array of all users registered in the specified course
  852. * This only returns the users that are registered in this actual course, not linked courses.
  853. *
  854. * @param string $course_code the code of the course
  855. * @param boolean $with_session determines if the course is used in a session or not
  856. * @param integer $session_id the id of the session
  857. * @param string $limit the LIMIT statement of the sql statement
  858. * @param string $order_by the field to order the users by. Valid values are 'lastname', 'firstname', 'username', 'email', 'official_code' OR a part of a SQL statement that starts with ORDER BY ...
  859. * @param int if using the session_id: 0 or 2 (student, coach), if using session_id = 0 STUDENT or COURSEMANAGER
  860. * @return array
  861. */
  862. public static function get_user_list_from_course_code($course_code = null, $session_id = 0, $limit = null, $order_by = null, $filter_by_status = null, $return_count = null, $add_reports = false, $resumed_report = false, $extra_field = null)
  863. {
  864. // variable initialisation
  865. $session_id = intval($session_id);
  866. $course_code = Database::escape_string($course_code);
  867. $where = array();
  868. // if the $order_by does not contain 'ORDER BY' we have to check if it is a valid field that can be sorted on
  869. if (!strstr($order_by,'ORDER BY')) {
  870. //if (!empty($order_by) AND in_array($order_by, array('lastname', 'firstname', 'username', 'email', 'official_code'))) {
  871. if (!empty($order_by)) {
  872. $order_by = 'ORDER BY '.$order_by;
  873. } else {
  874. $order_by = '';
  875. }
  876. }
  877. $courseInfo = api_get_course_info($course_code);
  878. $courseId = null;
  879. if ($courseInfo) {
  880. $courseId = $courseInfo['real_id'];
  881. }
  882. $filter_by_status_condition = null;
  883. if (!empty($session_id) && !empty($courseId)) {
  884. $sql = 'SELECT DISTINCT user.user_id, session_course_user.status as status_session, user.* ';
  885. $sql .= ' FROM '.Database::get_main_table(TABLE_MAIN_USER).' as user ';
  886. $sql .= ' LEFT JOIN '.Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER).' as session_course_user
  887. ON user.user_id = session_course_user.id_user
  888. AND session_course_user.c_id="'.$courseId.'"
  889. AND session_course_user.id_session = '.$session_id;
  890. $where[] = ' session_course_user.c_id IS NOT NULL ';
  891. // 2 = coach
  892. // 0 = student
  893. if (isset($filter_by_status)) {
  894. $filter_by_status = intval($filter_by_status);
  895. $filter_by_status_condition = " session_course_user.status = $filter_by_status AND ";
  896. }
  897. } else {
  898. if ($return_count) {
  899. $sql = " SELECT COUNT(*) as count";
  900. if ($resumed_report) {
  901. //$sql = " SELECT count(field_id) ";
  902. }
  903. } else {
  904. if (empty($course_code)) {
  905. $sql = 'SELECT DISTINCT course.title, course.code, course_rel_user.status as status_rel, user.user_id, course_rel_user.role, course_rel_user.tutor_id, user.* ';
  906. } else {
  907. $sql = 'SELECT DISTINCT course_rel_user.status as status_rel, user.user_id, course_rel_user.role, course_rel_user.tutor_id, user.* ';
  908. }
  909. }
  910. $sql .= ' FROM '.Database::get_main_table(TABLE_MAIN_USER).' as user ';
  911. $sql .= ' LEFT JOIN '.Database::get_main_table(TABLE_MAIN_COURSE_USER).' as course_rel_user
  912. ON user.user_id = course_rel_user.user_id AND
  913. course_rel_user.relation_type <> '.COURSE_RELATION_TYPE_RRHH;
  914. if (!empty($courseInfo)) {
  915. $sql .= " AND course_rel_user.c_id = ".$courseId;
  916. } else {
  917. $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
  918. $sql .= " INNER JOIN $course_table course ON course_rel_user.c_id = course.id";
  919. }
  920. $where[] = ' course_rel_user.c_id IS NOT NULL ';
  921. if (isset($filter_by_status) && $filter_by_status != '') {
  922. $filter_by_status = intval($filter_by_status);
  923. $filter_by_status_condition = " course_rel_user.status = $filter_by_status AND ";
  924. }
  925. }
  926. $multiple_access_url = api_get_multiple_access_url();
  927. if ($multiple_access_url) {
  928. $sql .= ' LEFT JOIN '.Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER).' au ON (au.user_id = user.user_id) ';
  929. }
  930. if ($return_count && $resumed_report) {
  931. $extra_field_info = UserManager::get_extra_field_information_by_name($extra_field);
  932. $sql .= ' LEFT JOIN '.Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES).' as ufv ON (user.user_id = ufv.user_id AND (field_id = '.$extra_field_info['id'].' OR field_id IS NULL ) )';
  933. }
  934. $sql .= ' WHERE '.$filter_by_status_condition.' '.implode(' OR ', $where);
  935. if ($multiple_access_url) {
  936. $current_access_url_id = api_get_current_access_url_id();
  937. $sql .= " AND (access_url_id = $current_access_url_id ) ";
  938. }
  939. if ($return_count && $resumed_report) {
  940. $sql .= ' AND field_id IS NOT NULL GROUP BY field_value ';
  941. }
  942. $sql .= ' '.$order_by.' '.$limit;
  943. $rs = Database::query($sql);
  944. $users = array();
  945. if ($add_reports) {
  946. $extra_fields = UserManager::get_extra_fields(0, 100, null, null, true, true);
  947. }
  948. $counter = 1;
  949. $count_rows = Database::num_rows($rs);
  950. if ($return_count && $resumed_report) {
  951. return $count_rows;
  952. }
  953. $table_user_field_value = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
  954. if ($count_rows) {
  955. while ($user = Database::fetch_array($rs)) {
  956. $report_info = array();
  957. if ($return_count) {
  958. return $user['count'];
  959. }
  960. $user_info = $user;
  961. $user_info['status'] = $user['status'];
  962. if (isset($user['role'])) {
  963. $user_info['role'] = $user['role'];
  964. }
  965. if (isset($user['tutor_id'])) {
  966. $user_info['tutor_id'] = $user['tutor_id'];
  967. }
  968. if (!empty($session_id)) {
  969. $user_info['status_session'] = $user['status_session'];
  970. }
  971. $user_info['complete_name'] = api_get_person_name($user_info['firstname'], $user_info['lastname']);
  972. if ($add_reports) {
  973. $course_code = $user['code'];
  974. if ($resumed_report) {
  975. foreach ($extra_fields as $extra) {
  976. if ($extra['1'] == $extra_field) {
  977. $user_data = UserManager::get_extra_user_data_by_field($user['user_id'], $extra['1']);
  978. break;
  979. }
  980. }
  981. if (empty($user_data[$extra['1']])) {
  982. $row_key = '-1';
  983. $name = '-';
  984. } else {
  985. $row_key = $user_data[$extra['1']];
  986. $name = $user_data[$extra['1']];
  987. }
  988. $users[$row_key]['extra_'.$extra['1']] = $name;
  989. $users[$row_key]['training_hours'] += Tracking::get_time_spent_on_the_course($user['user_id'], $courseId, 0);
  990. $users[$row_key]['count_users'] += $counter;
  991. $registered_users_with_extra_field = 0;
  992. if (!empty($name) && $name != '-') {
  993. $name = Database::escape_string($name);
  994. $sql = "SELECT count(user_id) as count FROM $table_user_field_value WHERE field_value = '$name'";
  995. $result_count = Database::query($sql);
  996. if (Database::num_rows($result_count)) {
  997. $row_count = Database::fetch_array($result_count);
  998. $registered_users_with_extra_field = $row_count['count'];
  999. }
  1000. }
  1001. $users[$row_key]['count_users_registered'] = $registered_users_with_extra_field;
  1002. $users[$row_key]['average_hours_per_user'] = $users[$row_key]['training_hours'] / $users[$row_key]['count_users'];
  1003. $category = Category::load (null, null, $course_code);
  1004. if (!isset($users[$row_key]['count_certificates'])) {
  1005. $users[$row_key]['count_certificates'] = 0;
  1006. }
  1007. if (isset($category[0]) && $category[0]->is_certificate_available($user['user_id'])) {
  1008. $users[$row_key]['count_certificates']++;
  1009. }
  1010. } else {
  1011. $report_info['course'] = $user['title'];
  1012. $report_info['user'] = api_get_person_name($user['firstname'], $user['lastname']);
  1013. $report_info['time'] = api_time_to_hms(Tracking::get_time_spent_on_the_course($user['user_id'], $courseId, 0));
  1014. $category = Category :: load (null, null, $course_code);
  1015. $report_info['certificate'] = Display::label(get_lang('No'));
  1016. if (isset($category[0]) && $category[0]->is_certificate_available($user['user_id'])) {
  1017. $report_info['certificate'] = Display::label(get_lang('Yes'), 'success');
  1018. }
  1019. //$report_info['score'] = Tracking::get_avg_student_score($user['user_id'], $courseId, array(), 0);
  1020. $progress = intval(Tracking::get_avg_student_progress($user['user_id'], $courseId, array(), 0));
  1021. $report_info['progress_100'] = $progress == 100 ? Display::label(get_lang('Yes'), 'success') : Display::label(get_lang('No'));
  1022. $report_info['progress'] = $progress."%";
  1023. foreach ($extra_fields as $extra) {
  1024. $user_data = UserManager::get_extra_user_data_by_field($user['user_id'], $extra['1']);
  1025. $report_info[$extra['1']] = $user_data[$extra['1']];
  1026. }
  1027. $users[] = $report_info;
  1028. }
  1029. } else {
  1030. $users[$user['user_id']] = $user_info;
  1031. }
  1032. }
  1033. $counter++;
  1034. }
  1035. return $users;
  1036. }
  1037. static function get_count_user_list_from_course_code($resumed_report = false, $extra_field = null) {
  1038. return self::get_user_list_from_course_code(null, 0, null, null, null, true, false, $resumed_report, $extra_field);
  1039. }
  1040. /**
  1041. * Gets subscribed users in a course or in a course/session
  1042. *
  1043. * @param string $course_code
  1044. * @param int $session_id
  1045. * @return int
  1046. */
  1047. public static function get_users_count_in_course($course_code, $session_id = 0) {
  1048. // variable initialisation
  1049. $session_id = intval($session_id);
  1050. $course_code = Database::escape_string($course_code);
  1051. $courseInfo = api_get_course_info($course_code);
  1052. $courseId = $courseInfo['real_id'];
  1053. $sql = 'SELECT DISTINCT count(*) as count FROM '.Database::get_main_table(TABLE_MAIN_USER).' as user ';
  1054. $where = array();
  1055. if (!empty($session_id)) {
  1056. $sql .= ' LEFT JOIN '.Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER).' as session_course_user
  1057. ON user.user_id = session_course_user.id_user
  1058. AND session_course_user.c_id = "'.$courseId.'"
  1059. AND session_course_user.id_session = '.$session_id.'
  1060. INNER JOIN '.Database::get_main_table(TABLE_MAIN_SESSION_USER).' as su
  1061. ON ( su.id_session = session_course_user.id_session AND
  1062. user.user_id = su.id_user AND
  1063. su.moved_to = 0 AND
  1064. su.moved_status <> '.SessionManager::SESSION_CHANGE_USER_REASON_ENROLLMENT_ANNULATION.'
  1065. )';
  1066. $where[] = ' session_course_user.c_id IS NOT NULL ';
  1067. } else {
  1068. $sql .= ' LEFT JOIN '.Database::get_main_table(TABLE_MAIN_COURSE_USER).' as course_rel_user
  1069. ON user.user_id = course_rel_user.user_id AND course_rel_user.relation_type<>'.COURSE_RELATION_TYPE_RRHH.'
  1070. AND course_rel_user.c_id ="'.$courseId.'"';
  1071. $where[] = ' course_rel_user.c_id IS NOT NULL ';
  1072. }
  1073. $multiple_access_url = api_get_multiple_access_url();
  1074. if ($multiple_access_url) {
  1075. $sql .= ' LEFT JOIN '.Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER).' au ON (au.user_id = user.user_id) ';
  1076. }
  1077. $sql .= ' WHERE '.implode(' OR ', $where);
  1078. if ($multiple_access_url) {
  1079. $current_access_url_id = api_get_current_access_url_id();
  1080. $sql .= " AND (access_url_id = $current_access_url_id ) ";
  1081. }
  1082. $rs = Database::query($sql);
  1083. $count = 0;
  1084. if (Database::num_rows($rs)) {
  1085. $user = Database::fetch_array($rs);
  1086. $count = $user['count'];
  1087. }
  1088. return $count;
  1089. }
  1090. /**
  1091. * Get a list of coaches of a course and a session
  1092. * @param string Course code
  1093. * @param int Session ID
  1094. * @return array List of users
  1095. */
  1096. public static function get_coach_list_from_course_code($courseId, $session_id) {
  1097. if ($session_id != strval(intval($session_id))) {
  1098. return array();
  1099. }
  1100. $courseId = Database::escape_string($courseId);
  1101. $users = array();
  1102. // We get the coach for the given course in a given session.
  1103. $rs = Database::query('SELECT id_user FROM '.Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER).
  1104. ' WHERE id_session="'.$session_id.'" AND c_id="'.$courseId.'" AND status = 2');
  1105. while ($user = Database::fetch_array($rs)) {
  1106. $user_info = api_get_user_info($user['id_user']);
  1107. $user_info['status'] = $user['status'];
  1108. $user_info['role'] = $user['role'];
  1109. $user_info['tutor_id'] = $user['tutor_id'];
  1110. $user_info['email'] = $user['email'];
  1111. $users[$user['id_user']] = $user_info;
  1112. }
  1113. // We get the session coach.
  1114. $rs = Database::query('SELECT id_coach FROM '.Database::get_main_table(TABLE_MAIN_SESSION).' WHERE id="'.$session_id.'"');
  1115. $session_id_coach = Database::result($rs, 0, 'id_coach');
  1116. $user_info = api_get_user_info($session_id_coach);
  1117. $user_info['status'] = $user['status'];
  1118. $user_info['role'] = $user['role']; //Role field exists?
  1119. $user_info['tutor_id'] = $user['tutor_id'];
  1120. $user_info['email'] = $user['email'];
  1121. $users[$session_id_coach] = $user_info;
  1122. return $users;
  1123. }
  1124. /**
  1125. * Return user info array of all users registered in the specified real or virtual course
  1126. * This only returns the users that are registered in this actual course, not linked courses.
  1127. *
  1128. * @param string $course_code
  1129. * @param boolean $full list to true if we want sessions students too
  1130. * @return array with user id
  1131. */
  1132. public static function get_student_list_from_course_code($courseId, $with_session = false, $session_id = 0, $group_id = 0) {
  1133. $session_id = intval($session_id);
  1134. $courseId = Database::escape_string($courseId);
  1135. $students = array();
  1136. if ($session_id == 0) {
  1137. if (empty($group_id)) {
  1138. // students directly subscribed to the course
  1139. $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  1140. WHERE c_id = ".$courseId." AND status = ".STUDENT;
  1141. $rs = Database::query($sql);
  1142. while ($student = Database::fetch_array($rs)) {
  1143. $students[$student['user_id']] = $student;
  1144. }
  1145. } else {
  1146. $students = GroupManager::get_users($group_id, false, $courseId);
  1147. $students = array_flip($students);
  1148. }
  1149. }
  1150. // students subscribed to the course through a session
  1151. if ($with_session) {
  1152. $sql_query = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)."
  1153. WHERE c_id = '$courseId' AND status <> 2";
  1154. if ($session_id != 0) {
  1155. $sql_query .= ' AND id_session = '.$session_id;
  1156. }
  1157. $rs = Database::query($sql_query);
  1158. while($student = Database::fetch_array($rs)) {
  1159. $students[$student['id_user']] = $student;
  1160. }
  1161. }
  1162. return $students;
  1163. }
  1164. /**
  1165. * Return user info array of all teacher-users registered in the specified real or virtual course
  1166. * This only returns the users that are registered in this actual course, not linked courses.
  1167. *
  1168. * @param int $courseId
  1169. * @return array with user id
  1170. */
  1171. public static function get_teacher_list_from_course_code($courseId)
  1172. {
  1173. $courseId = Database::escape_string($courseId);
  1174. $teachers = array();
  1175. $sql = "SELECT DISTINCT u.user_id, u.lastname, u.firstname, u.email, u.username, u.status
  1176. FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)." cu INNER JOIN ".Database::get_main_table(TABLE_MAIN_USER)." u
  1177. ON (cu.user_id = u.user_id)
  1178. WHERE cu.c_id = '$courseId' AND
  1179. cu.status = 1 ";
  1180. $rs = Database::query($sql);
  1181. while ($teacher = Database::fetch_array($rs)) {
  1182. $teachers[$teacher['user_id']] = $teacher;
  1183. }
  1184. return $teachers;
  1185. }
  1186. /**
  1187. * @param $courseId
  1188. * @param string $separator
  1189. * @param bool $add_link_to_profile
  1190. * @return string
  1191. */
  1192. public static function get_teacher_list_from_course_code_to_string($courseId, $separator = null, $add_link_to_profile = false)
  1193. {
  1194. $teacher_list = self::get_teacher_list_from_course_code($courseId);
  1195. return self::formatUserListToString($teacher_list, $separator, $add_link_to_profile);
  1196. }
  1197. public static function formatUserListToString($userList, $separator = null, $add_link_to_profile = false)
  1198. {
  1199. if (empty($separator)) {
  1200. $separator = self::USER_SEPARATOR;
  1201. }
  1202. $teacher_string = '';
  1203. $list = array();
  1204. if (!empty($userList)) {
  1205. foreach($userList as $teacher) {
  1206. $teacher_name = api_get_person_name($teacher['firstname'], $teacher['lastname']);
  1207. if ($add_link_to_profile) {
  1208. $url = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?a=get_user_popup&resizable=0&height=300&user_id='.$teacher['user_id'];
  1209. $teacher_name = Display::url($teacher_name, $url, array('class' => 'ajax'));
  1210. }
  1211. $list[]= $teacher_name;
  1212. }
  1213. if (!empty($list)) {
  1214. $teacher_string = ArrayClass::array_to_string($list, $separator);
  1215. }
  1216. }
  1217. return $teacher_string;
  1218. }
  1219. /**
  1220. * This function returns information about coachs from a course in session
  1221. * @param int - optional, session id
  1222. * @param string - optional, course code
  1223. * @return array - array containing user_id, lastname, firstname, username
  1224. *
  1225. */
  1226. public static function get_coachs_from_course($session_id = 0, $courseId = null) {
  1227. if (!empty($session_id)) {
  1228. $session_id = intval($session_id);
  1229. } else {
  1230. $session_id = api_get_session_id();
  1231. }
  1232. if (!empty($courseId)) {
  1233. $courseId = Database::escape_string($courseId);
  1234. } else {
  1235. $courseId = api_get_course_int_id();
  1236. }
  1237. $tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
  1238. $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1239. $coaches = array();
  1240. $sql = "SELECT DISTINCT u.user_id, u.lastname, u.firstname, u.username
  1241. FROM $tbl_user u, $tbl_session_course_user scu
  1242. WHERE u.user_id = scu.id_user AND scu.id_session = '$session_id' AND scu.c_id = $courseId AND scu.status = 2";
  1243. $rs = Database::query($sql);
  1244. if (Database::num_rows($rs) > 0) {
  1245. while ($row = Database::fetch_array($rs)) {
  1246. $coaches[] = $row;
  1247. }
  1248. return $coaches;
  1249. } else {
  1250. return false;
  1251. }
  1252. }
  1253. public static function get_coachs_from_course_to_string($session_id = 0, $courseId = null, $separator = self::USER_SEPARATOR, $add_link_to_profile = false) {
  1254. $coachs_course = self::get_coachs_from_course($session_id, $courseId);
  1255. $course_coachs = array();
  1256. if (is_array($coachs_course)) {
  1257. foreach ($coachs_course as $coach_course) {
  1258. $coach_name = api_get_person_name($coach_course['firstname'], $coach_course['lastname']);
  1259. if ($add_link_to_profile) {
  1260. $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'];
  1261. $coach_name = Display::url($coach_name, $url, array('class' => 'ajax'));
  1262. }
  1263. $course_coachs[] = $coach_name;
  1264. }
  1265. }
  1266. $coaches_to_string = null;
  1267. if (is_array($course_coachs) && count($course_coachs)> 0 ) {
  1268. $coaches_to_string = ArrayClass::array_to_string($course_coachs, $separator);
  1269. }
  1270. return $coaches_to_string;
  1271. }
  1272. public static function get_coach_list_from_course_code_to_string($courseId, $session_id) {
  1273. $tutor_data = '';
  1274. if ($session_id != 0) {
  1275. $coaches = self::get_email_of_tutor_to_session($session_id, $courseId);
  1276. $coach_list = array();
  1277. foreach ($coaches as $coach) {
  1278. $coach_list[] = $coach['complete_name'];
  1279. }
  1280. if (!empty($coach_list)) {
  1281. $tutor_data = implode(self::USER_SEPARATOR, $coach_list);
  1282. }
  1283. }
  1284. return $tutor_data;
  1285. }
  1286. /**
  1287. * Return user info array of all users registered in the specified course
  1288. * this includes the users of the course itsel and the users of all linked courses.
  1289. *
  1290. * @param array $course_info
  1291. * @return array with user info
  1292. */
  1293. public static function get_real_and_linked_user_list($course_code, $with_sessions = true, $session_id = 0, $order_by = null) {
  1294. $complete_user_list = array();
  1295. //get users from real course
  1296. $user_list = self::get_user_list_from_course_code($course_code, $session_id, null, $order_by);
  1297. foreach ($user_list as $this_user) {
  1298. $complete_user_list[] = $this_user;
  1299. }
  1300. return $complete_user_list;
  1301. }
  1302. /*
  1303. GROUP FUNCTIONS
  1304. */
  1305. /**
  1306. * Get the list of groups from the course
  1307. * @param string Course code
  1308. * @param int Session ID (optional)
  1309. * @param boolean get empty groups (optional)
  1310. * @return array List of groups info
  1311. */
  1312. public static function get_group_list_of_course($course_code, $session_id = 0, $in_get_empty_group = 0) {
  1313. $course_info = api_get_course_info($course_code);
  1314. $course_id = $course_info['real_id'];
  1315. $group_list = array();
  1316. $session_id != 0 ? $session_condition = ' WHERE g.session_id IN(1,'.intval($session_id).')' : $session_condition = ' WHERE g.session_id = 0';
  1317. if ($in_get_empty_group == 0) {
  1318. // get only groups that are not empty
  1319. $sql = "SELECT DISTINCT g.id, g.name
  1320. FROM ".Database::get_course_table(TABLE_GROUP)." AS g
  1321. INNER JOIN ".Database::get_course_table(TABLE_GROUP_USER)." gu
  1322. ON (g.id = gu.group_id AND g.c_id = $course_id AND gu.c_id = $course_id)
  1323. $session_condition
  1324. ORDER BY g.name";
  1325. } else {
  1326. // get all groups even if they are empty
  1327. $sql = "SELECT g.id, g.name
  1328. FROM ".Database::get_course_table(TABLE_GROUP)." AS g
  1329. $session_condition
  1330. AND c_id = $course_id";
  1331. }
  1332. $result = Database::query($sql);
  1333. while ($group_data = Database::fetch_array($result)) {
  1334. $group_data['userNb'] = GroupManager::number_of_students($group_data['id'], $course_id);
  1335. $group_list[$group_data['id']] = $group_data;
  1336. }
  1337. return $group_list;
  1338. }
  1339. /**
  1340. * Delete a course
  1341. * This function deletes a whole course-area from the platform. When the
  1342. * given course is a virtual course, the database and directory will not be
  1343. * deleted.
  1344. * When the given course is a real course, also all virtual courses refering
  1345. * to the given course will be deleted.
  1346. * Considering the fact that we remove all traces of the course in the main
  1347. * database, it makes sense to remove all tracking as well (if stats databases exist)
  1348. * so that a new course created with this code would not use the remains of an older
  1349. * course.
  1350. *
  1351. * @param string The code of the course to delete
  1352. * course from the groups in the real course if they are not subscribed in
  1353. * that real course.
  1354. */
  1355. public static function delete_course($code)
  1356. {
  1357. $table_course = Database::get_main_table(TABLE_MAIN_COURSE);
  1358. $table_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  1359. $table_course_class = Database::get_main_table(TABLE_MAIN_COURSE_CLASS);
  1360. $table_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  1361. $table_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1362. $table_course_survey = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY);
  1363. $table_course_survey_question = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
  1364. $table_course_survey_question_option= Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
  1365. $table_stats_hotpots = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
  1366. $table_stats_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  1367. $table_stats_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  1368. $table_stats_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
  1369. $table_stats_lastaccess = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
  1370. $table_stats_course_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  1371. $table_stats_online = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
  1372. $table_stats_default = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DEFAULT);
  1373. $table_stats_downloads = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DOWNLOADS);
  1374. $table_stats_links = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LINKS);
  1375. $table_stats_uploads = Database::get_main_table(TABLE_STATISTIC_TRACK_E_UPLOADS);
  1376. $courseInfo = api_get_course_info($code);
  1377. if (empty($courseInfo)) {
  1378. return false;
  1379. }
  1380. self::create_database_dump($courseInfo);
  1381. $code = Database::escape_string($code);
  1382. $courseId = $courseInfo['real_id'];
  1383. $course_tables = self::get_course_tables();
  1384. // Cleaning c_x tables
  1385. if (!empty($courseInfo['id'])) {
  1386. foreach ($course_tables as $table) {
  1387. $table = Database::get_course_table($table);
  1388. $sql = "DELETE FROM $table WHERE c_id = $courseId ";
  1389. Database::query($sql);
  1390. }
  1391. }
  1392. if (!empty($courseInfo['directory'])) {
  1393. $course_dir = api_get_path(SYS_COURSE_PATH).$courseInfo['directory'];
  1394. $archive_dir = api_get_path(SYS_ARCHIVE_PATH).$courseInfo['directory'].'_'.time();
  1395. if (is_dir($course_dir)) {
  1396. rename($course_dir, $archive_dir);
  1397. }
  1398. }
  1399. // Unsubscribe all classes from the course
  1400. $sql = "DELETE FROM $table_course_class WHERE course_code='".$code."'";
  1401. Database::query($sql);
  1402. // Unsubscribe all users from the course
  1403. $sql = "DELETE FROM $table_course_user WHERE c_id ='".$courseId."'";
  1404. Database::query($sql);
  1405. // Delete the course from the sessions tables
  1406. $sql = "DELETE FROM $table_session_course WHERE c_id='".$courseId."'";
  1407. Database::query($sql);
  1408. $sql = "DELETE FROM $table_session_course_user WHERE c_id='".$courseId."'";
  1409. Database::query($sql);
  1410. $sql = 'SELECT survey_id FROM '.$table_course_survey.' WHERE course_code="'.$code.'"';
  1411. $result_surveys = Database::query($sql);
  1412. while($surveys = Database::fetch_array($result_surveys)) {
  1413. $survey_id = $surveys[0];
  1414. $sql = 'DELETE FROM '.$table_course_survey_question.' WHERE survey_id="'.$survey_id.'"';
  1415. Database::query($sql);
  1416. $sql = 'DELETE FROM '.$table_course_survey_question_option.' WHERE survey_id="'.$survey_id.'"';
  1417. Database::query($sql);
  1418. $sql = 'DELETE FROM '.$table_course_survey.' WHERE survey_id="'.$survey_id.'"';
  1419. Database::query($sql);
  1420. }
  1421. // Delete the course from the stats tables
  1422. $sql = "DELETE FROM $table_stats_hotpots WHERE c_id = '".$courseId."'";
  1423. Database::query($sql);
  1424. $sql = "DELETE FROM $table_stats_attempt WHERE c_id = '".$courseId."'";
  1425. Database::query($sql);
  1426. $sql = "DELETE FROM $table_stats_exercises WHERE c_id = '".$courseId."'";
  1427. Database::query($sql);
  1428. $sql = "DELETE FROM $table_stats_access WHERE c_id = '".$courseId."'";
  1429. Database::query($sql);
  1430. $sql = "DELETE FROM $table_stats_lastaccess WHERE c_id = '".$courseId."'";
  1431. Database::query($sql);
  1432. $sql = "DELETE FROM $table_stats_course_access WHERE c_id = '".$courseId."'";
  1433. Database::query($sql);
  1434. $sql = "DELETE FROM $table_stats_online WHERE course = '".$code."'";
  1435. Database::query($sql);
  1436. $sql = "DELETE FROM $table_stats_default WHERE default_cours_code = '".$code."'";
  1437. Database::query($sql);
  1438. $sql = "DELETE FROM $table_stats_downloads WHERE c_id = '".$courseId."'";
  1439. Database::query($sql);
  1440. $sql = "DELETE FROM $table_stats_links WHERE c_id = '".$courseId."'";
  1441. Database::query($sql);
  1442. $sql = "DELETE FROM $table_stats_uploads WHERE upload_cours_id = '".$code."'";
  1443. Database::query($sql);
  1444. if (api_is_multiple_url_enabled()) {
  1445. $url_id = 1;
  1446. if (api_get_current_access_url_id() != -1) {
  1447. $url_id = api_get_current_access_url_id();
  1448. }
  1449. UrlManager::delete_url_rel_course($courseId, $url_id);
  1450. }
  1451. // Delete the course from the database
  1452. $sql = "DELETE FROM $table_course WHERE id = '".$courseId."'";
  1453. Database::query($sql);
  1454. // delete extra course fields
  1455. $t_cf = Database::get_main_table(TABLE_MAIN_COURSE_FIELD);
  1456. $t_cfv = Database::get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
  1457. $sql = "SELECT distinct field_id FROM $t_cfv WHERE course_code = '$code'";
  1458. $res_field_ids = @Database::query($sql);
  1459. $field_ids = array();
  1460. while($row_field_id = Database::fetch_row($res_field_ids)){
  1461. $field_ids[] = $row_field_id[0];
  1462. }
  1463. // Delete from table_course_field_value from a given course_code
  1464. $sql_course_field_value = "DELETE FROM $t_cfv WHERE course_code = '$code'";
  1465. @Database::query($sql_course_field_value);
  1466. $sql = "SELECT distinct field_id FROM $t_cfv";
  1467. $res_field_all_ids = @Database::query($sql);
  1468. $field_all_ids = array();
  1469. while($row_field_all_id = Database::fetch_row($res_field_all_ids)){
  1470. $field_all_ids[] = $row_field_all_id[0];
  1471. }
  1472. if (isset($field_ids) && is_array($field_ids) && count($field_ids) > 0) {
  1473. foreach ($field_ids as $field_id) {
  1474. // check if field id is used into table field value
  1475. if (!empty($field_all_ids) && is_array($field_all_ids)) {
  1476. if (in_array($field_id, $field_all_ids)) {
  1477. continue;
  1478. } else {
  1479. $sql_course_field = "DELETE FROM $t_cf WHERE id = '$field_id'";
  1480. Database::query($sql_course_field);
  1481. }
  1482. }
  1483. }
  1484. }
  1485. // Add event to system log
  1486. $user_id = api_get_user_id();
  1487. event_system(LOG_COURSE_DELETE, LOG_COURSE_CODE, $code, api_get_utc_datetime(), $user_id, $code);
  1488. }
  1489. /**
  1490. * Creates a file called mysql_dump.sql in the course folder
  1491. * @param array course info
  1492. * @return
  1493. */
  1494. public static function create_database_dump($courseInfo)
  1495. {
  1496. $sql_dump = null;
  1497. if (empty($courseInfo)) {
  1498. return null;
  1499. }
  1500. $course_tables = self::get_course_tables();
  1501. if (!empty($courseInfo['real_id'])) {
  1502. // Cleaning c_x tables
  1503. foreach ($course_tables as $table) {
  1504. $table = Database::get_course_table($table);
  1505. $sql = "SELECT * FROM $table WHERE c_id = {$courseInfo['real_id']} ";
  1506. $res_table = Database::query($sql);
  1507. while ($row = Database::fetch_array($res_table, 'ASSOC')) {
  1508. $row_to_save = array();
  1509. foreach ($row as $key => $value) {
  1510. $row_to_save[$key] = $key."='".Database::escape_string($row[$key])."'";
  1511. }
  1512. $sql_dump .= "INSERT INTO $table SET ".implode(', ', $row_to_save).';';
  1513. }
  1514. }
  1515. }
  1516. if (is_dir(api_get_path(SYS_COURSE_PATH).$courseInfo['directory'])) {
  1517. $file_name = api_get_path(SYS_COURSE_PATH).$courseInfo['directory'].'/mysql_dump.sql';
  1518. $handle = fopen($file_name, 'a+');
  1519. if ($handle !== false) {
  1520. fwrite($handle, $sql_dump);
  1521. fclose($handle);
  1522. }
  1523. }
  1524. }
  1525. /**
  1526. * Sort courses for a specific user ??
  1527. * @param int User ID
  1528. * @param string Course code
  1529. * @return int Minimum course order
  1530. * @todo Review documentation
  1531. */
  1532. public static function userCourseSort($user_id, $courseId) {
  1533. if ($user_id != strval(intval($user_id))) {
  1534. return false;
  1535. }
  1536. $courseId = Database::escape_string($courseId);
  1537. $TABLECOURSE = Database::get_main_table(TABLE_MAIN_COURSE);
  1538. $TABLECOURSUSER = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  1539. $course_title = Database::result(Database::query('SELECT title FROM '.$TABLECOURSE.' WHERE id = "'.$courseId.'"'), 0, 0);
  1540. $sql = 'SELECT course.code as code, course.title as title, cu.sort as sort
  1541. FROM '.$TABLECOURSUSER.' as cu, '.$TABLECOURSE.' as course
  1542. WHERE course.id = cu.c_id AND
  1543. user_id = "'.$user_id.'" AND
  1544. cu.relation_type<>'.COURSE_RELATION_TYPE_RRHH.' AND
  1545. user_course_cat = 0
  1546. ORDER BY cu.sort';
  1547. $result = Database::query($sql);
  1548. $course_title_precedent = '';
  1549. $counter = 0;
  1550. $course_found = false;
  1551. $course_sort = 1;
  1552. if (Database::num_rows($result) > 0) {
  1553. while ($courses = Database::fetch_array($result)) {
  1554. if ($course_title_precedent == '') {
  1555. $course_title_precedent = $courses['title'];
  1556. }
  1557. if (api_strcasecmp($course_title_precedent, $course_title) < 0) {
  1558. $course_found = true;
  1559. $course_sort = $courses['sort'];
  1560. if ($counter == 0) {
  1561. $sql = 'UPDATE '.$TABLECOURSUSER.' SET sort = sort+1 WHERE user_id = "'.$user_id.'" AND relation_type<>'.COURSE_RELATION_TYPE_RRHH.' AND user_course_cat="0" AND sort > "'.$course_sort.'"';
  1562. $course_sort++;
  1563. } else {
  1564. $sql = 'UPDATE '.$TABLECOURSUSER.' SET sort = sort+1 WHERE user_id = "'.$user_id.'" AND relation_type<>'.COURSE_RELATION_TYPE_RRHH.' AND user_course_cat="0" AND sort >= "'.$course_sort.'"';
  1565. }
  1566. Database::query($sql);
  1567. break;
  1568. } else {
  1569. $course_title_precedent = $courses['title'];
  1570. }
  1571. $counter++;
  1572. }
  1573. // We must register the course in the beginning of the list
  1574. if (!$course_found) {
  1575. $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);
  1576. Database::query('UPDATE '.$TABLECOURSUSER.' SET sort = sort+1 WHERE user_id= "'.$user_id.'" AND user_course_cat="0"');
  1577. }
  1578. }
  1579. return $course_sort;
  1580. }
  1581. /**
  1582. * create recursively all categories as option of the select passed in paramater.
  1583. *
  1584. * @param object $select_element the quickform select where the options will be added
  1585. * @param string $category_selected_code the option value to select by default (used mainly for edition of courses)
  1586. * @param string $parent_code the parent category of the categories added (default=null for root category)
  1587. * @param string $padding the indent param (you shouldn't indicate something here)
  1588. */
  1589. public static function select_and_sort_categories($select_element, $category_selected_code = '', $parent_code = null , $padding = '') {
  1590. $sql = "SELECT code, name, auth_course_child, auth_cat_child
  1591. FROM ".Database::get_main_table(TABLE_MAIN_CATEGORY)."
  1592. WHERE parent_id ".(is_null($parent_code) ? "IS NULL" : "='".Database::escape_string($parent_code)."'")."
  1593. ORDER BY code";
  1594. $res = Database::query($sql);
  1595. while ($cat = Database::fetch_array($res)) {
  1596. $params = $cat['auth_course_child'] == 'TRUE' ? '' : 'disabled';
  1597. $params .= ($cat['code'] == $category_selected_code) ? ' selected' : '';
  1598. $select_element->addOption($padding.'('.$cat['code'].') '.$cat['name'], $cat['code'], $params);
  1599. if ($cat['auth_cat_child']) {
  1600. self::select_and_sort_categories($select_element, $category_selected_code, $cat['code'], $padding.' - ');
  1601. }
  1602. }
  1603. }
  1604. /**
  1605. * check if course exists
  1606. * @param string course_code
  1607. * @param string whether to accept virtual course codes or not
  1608. * @return true if exists, false else
  1609. */
  1610. public static function course_exists($course_code, $accept_virtual = false) {
  1611. if ($accept_virtual === true) {
  1612. $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).'"';
  1613. } else {
  1614. $sql = 'SELECT 1 FROM '.Database::get_main_table(TABLE_MAIN_COURSE).' WHERE code="'.Database::escape_string($course_code).'"';
  1615. }
  1616. return Database::num_rows(Database::query($sql));
  1617. }
  1618. /**
  1619. * Send an email to tutor after the auth-suscription of a student in your course
  1620. * @author Carlos Vargas <carlos.vargas@dokeos.com>, Dokeos Latino
  1621. * @param int $user_id the id of the user
  1622. * @param string $course_code the course code
  1623. * @param string $send_to_tutor_also
  1624. * @return string we return the message that is displayed when the action is succesfull
  1625. */
  1626. public static function email_to_tutor($user_id, $course_code, $send_to_tutor_also = false)
  1627. {
  1628. if ($user_id != strval(intval($user_id))) {
  1629. return false;
  1630. }
  1631. $course_code = Database::escape_string($course_code);
  1632. $student = Database::fetch_array(Database::query("SELECT * FROM ".Database::get_main_table(TABLE_MAIN_USER)."
  1633. WHERE user_id='".$user_id."'"));
  1634. $courseInfo = api_get_course_info($course_code);
  1635. $name_course = $courseInfo['title'];
  1636. $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)." WHERE c_id = '".$courseInfo['real_id']."'";
  1637. // TODO: Ivan: This is a mistake, please, have a look at it. Intention here is diffcult to be guessed.
  1638. //if ($send_to_tutor_also = true)
  1639. // Proposed change:
  1640. if ($send_to_tutor_also) {
  1641. //
  1642. $sql .= " AND tutor_id=1";
  1643. } else {
  1644. $sql .= " AND status=1";
  1645. }
  1646. $result = Database::query($sql);
  1647. while ($row = Database::fetch_array($result)) {
  1648. $tutor = Database::fetch_array(Database::query("SELECT * FROM ".Database::get_main_table(TABLE_MAIN_USER)."
  1649. WHERE user_id='".$row['user_id']."'"));
  1650. $emailto = $tutor['email'];
  1651. $emailsubject = get_lang('NewUserInTheCourse').': '.$name_course;
  1652. $emailbody = get_lang('Dear').': '. api_get_person_name($tutor['firstname'], $tutor['lastname'])."\n";
  1653. $emailbody .= get_lang('MessageNewUserInTheCourse').': '.$name_course."\n";
  1654. $emailbody .= get_lang('UserName').': '.$student['username']."\n";
  1655. if (api_is_western_name_order()) {
  1656. $emailbody .= get_lang('FirstName').': '.$student['firstname']."\n";
  1657. $emailbody .= get_lang('LastName').': '.$student['lastname']."\n";
  1658. } else {
  1659. $emailbody .= get_lang('LastName').': '.$student['lastname']."\n";
  1660. $emailbody .= get_lang('FirstName').': '.$student['firstname']."\n";
  1661. }
  1662. $emailbody .= get_lang('Email').': '.$student['email']."\n\n";
  1663. $recipient_name = api_get_person_name($tutor['firstname'], $tutor['lastname'], null, PERSON_NAME_EMAIL_ADDRESS);
  1664. $sender_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
  1665. $email_admin = api_get_setting('emailAdministrator');
  1666. @api_mail($recipient_name, $emailto, $emailsubject, $emailbody, $sender_name,$email_admin);
  1667. }
  1668. }
  1669. /**
  1670. * @return array
  1671. */
  1672. public static function get_special_course_list()
  1673. {
  1674. $tbl_course = Database :: get_main_table(TABLE_MAIN_COURSE);
  1675. $tbl_course_field = Database :: get_main_table(TABLE_MAIN_COURSE_FIELD);
  1676. $tbl_course_field_value = Database :: get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
  1677. //we filter the courses from the URL
  1678. $join_access_url = $where_access_url='';
  1679. if (api_get_multiple_access_url()) {
  1680. $access_url_id = api_get_current_access_url_id();
  1681. if ($access_url_id != -1) {
  1682. $tbl_url_course = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  1683. $join_access_url= " INNER JOIN $tbl_course course ON (course.code = tcfv.course_code)
  1684. INNER JOIN $tbl_url_course url_rel_course
  1685. ON url_rel_course.c_id = course.id ";
  1686. $where_access_url =" AND access_url_id = $access_url_id ";
  1687. }
  1688. }
  1689. // get course list auto-register
  1690. $sql = "SELECT DISTINCT(tcfv.course_code) FROM $tbl_course_field_value tcfv INNER JOIN $tbl_course_field tcf
  1691. ON tcfv.field_id = tcf.id $join_access_url
  1692. WHERE tcf.field_variable = 'special_course' AND tcfv.field_value = 1 $where_access_url";
  1693. $special_course_result = Database::query($sql);
  1694. $special_course_list = array();
  1695. if (Database::num_rows($special_course_result)>0) {
  1696. $special_course_list = array();
  1697. while ($result_row = Database::fetch_array($special_course_result)) {
  1698. $special_course_list[] = $result_row['course_code'];
  1699. }
  1700. }
  1701. return $special_course_list;
  1702. }
  1703. /**
  1704. * Get list of courses for a given user
  1705. * @param int user ID
  1706. * @param boolean Whether to include courses from session or not
  1707. * @return array List of codes and db names
  1708. * @author isaac flores paz
  1709. */
  1710. public static function get_courses_list_by_user_id($user_id, $include_sessions = false) {
  1711. $user_id = intval($user_id);
  1712. $course_list = array();
  1713. $codes = array();
  1714. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  1715. $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  1716. $tbl_user_course_category = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
  1717. $special_course_list = self::get_special_course_list();
  1718. $with_special_courses = $without_special_courses = '';
  1719. if (!empty($special_course_list)) {
  1720. $sc_string = '"'.implode('","',$special_course_list).'"';
  1721. $with_special_courses = ' course.code IN ('.$sc_string.')';
  1722. $without_special_courses = ' AND course.code NOT IN ('.$sc_string.')';
  1723. }
  1724. if (!empty($with_special_courses)) {
  1725. $sql = "SELECT DISTINCT(course.code), course.id as real_id
  1726. FROM ".$tbl_course_user." course_rel_user
  1727. LEFT JOIN ".$tbl_course." course
  1728. ON course.id = course_rel_user.c_id
  1729. LEFT JOIN ".$tbl_user_course_category." user_course_category
  1730. ON course_rel_user.user_course_cat = user_course_category.id
  1731. WHERE $with_special_courses
  1732. GROUP BY course.code
  1733. ORDER BY user_course_category.sort,course.title,course_rel_user.sort ASC";
  1734. $rs_special_course = Database::query($sql);
  1735. if (Database::num_rows($rs_special_course) > 0) {
  1736. while ($result_row = Database::fetch_array($rs_special_course)) {
  1737. $result_row['special_course'] = 1;
  1738. $course_list[] = $result_row;
  1739. $codes[] = $result_row['real_id'];
  1740. }
  1741. }
  1742. }
  1743. // get course list not auto-register. Use Distinct to avoid multiple
  1744. // entries when a course is assigned to a HRD (DRH) as watcher
  1745. $sql = "SELECT DISTINCT(course.code), course.id as real_id
  1746. FROM $tbl_course course
  1747. INNER JOIN $tbl_course_user cru ON course.id = cru.c_id
  1748. WHERE cru.user_id='$user_id' $without_special_courses";
  1749. $result = Database::query($sql);
  1750. if (Database::num_rows($result)) {
  1751. while ($row = Database::fetch_array($result, 'ASSOC')) {
  1752. $course_list[] = $row;
  1753. $codes[] = $row['real_id'];
  1754. }
  1755. }
  1756. if ($include_sessions === true) {
  1757. $sql = "SELECT DISTINCT(c.code), c.id as real_id
  1758. FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)." s, ".Database::get_main_table(TABLE_MAIN_COURSE)." c
  1759. WHERE id_user = $user_id AND s.c_id =c.id";
  1760. $r = Database::query($sql);
  1761. while ($row = Database::fetch_array($r, 'ASSOC')) {
  1762. if (!in_array($row['real_id'], $codes)) {
  1763. $course_list[] = $row;
  1764. }
  1765. }
  1766. }
  1767. return $course_list;
  1768. }
  1769. /**
  1770. * Get course ID from a given course directory name
  1771. * @param string Course directory (without any slash)
  1772. * @return string Course code, or false if not found
  1773. */
  1774. public static function get_course_id_from_path($path) {
  1775. $path = Database::escape_string(str_replace('.', '', str_replace('/', '', $path)));
  1776. $res = Database::query("SELECT code FROM ".Database::get_main_table(TABLE_MAIN_COURSE)."
  1777. WHERE directory LIKE BINARY '$path'");
  1778. if ($res === false) {
  1779. return false;
  1780. }
  1781. if (Database::num_rows($res) != 1) {
  1782. return false;
  1783. }
  1784. $row = Database::fetch_array($res);
  1785. return $row['code'];
  1786. }
  1787. /**
  1788. * Get course code(s) from visual code
  1789. * @param string Visual code
  1790. * @return array List of codes for the given visual code
  1791. */
  1792. public static function get_courses_info_from_visual_code($code) {
  1793. $result = array();
  1794. $sql_result = Database::query("SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE)."
  1795. WHERE visual_code = '".Database::escape_string($code)."'");
  1796. while ($virtual_course = Database::fetch_array($sql_result)) {
  1797. $result[] = $virtual_course;
  1798. }
  1799. return $result;
  1800. }
  1801. /**
  1802. * Get coachs' emails by session
  1803. * @param int session id
  1804. * @param int course id
  1805. * @return array array(email => name_tutor) by coach
  1806. * @author Carlos Vargas <carlos.vargas@dokeos.com>
  1807. */
  1808. public static function get_email_of_tutor_to_session($session_id, $courseId) {
  1809. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1810. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  1811. $coachs_emails = array();
  1812. $courseId = Database::escape_string($courseId);
  1813. $session_id = intval($session_id);
  1814. $sql = "SELECT id_user FROM $tbl_session_course_user WHERE id_session='$session_id' AND c_id ='$courseId' AND status =2";
  1815. $rs = Database::query($sql);
  1816. if (Database::num_rows($rs) > 0) {
  1817. $user_ids = array();
  1818. while ($row = Database::fetch_array($rs)) {
  1819. $user_ids[] = $row['id_user'];
  1820. }
  1821. $sql = "SELECT firstname, lastname, email FROM $tbl_user WHERE user_id IN (".implode(",",$user_ids).")";
  1822. $rs_user = Database::query($sql);
  1823. while ($row_emails = Database::fetch_array($rs_user)) {
  1824. $mail_tutor = array('email' => $row_emails['email'], 'complete_name' => api_get_person_name($row_emails['firstname'], $row_emails['lastname']));
  1825. $coachs_emails[] = $mail_tutor;
  1826. }
  1827. }
  1828. return $coachs_emails;
  1829. }
  1830. /**
  1831. * Creates a new extra field for a given course
  1832. * @param string Field's internal variable name
  1833. * @param int Field's type
  1834. * @param string Field's language var name
  1835. * @return int new extra field id
  1836. */
  1837. public static function create_course_extra_field($fieldvarname, $fieldtype, $fieldtitle) {
  1838. // database table definition
  1839. $t_cfv = Database::get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
  1840. $t_cf = Database::get_main_table(TABLE_MAIN_COURSE_FIELD);
  1841. $fieldvarname = Database::escape_string($fieldvarname);
  1842. $fieldtitle = Database::escape_string($fieldtitle);
  1843. $fieldtype = (int)$fieldtype;
  1844. $time = time();
  1845. $sql_field = "SELECT id FROM $t_cf WHERE field_variable = '$fieldvarname'";
  1846. $res_field = Database::query($sql_field);
  1847. $r_field = Database::fetch_row($res_field);
  1848. if (Database::num_rows($res_field) > 0) {
  1849. return $r_field[0];
  1850. }
  1851. // save new fieldlabel into course_field table
  1852. $sql = "SELECT MAX(field_order) FROM $t_cf";
  1853. $res = Database::query($sql);
  1854. $order = 0;
  1855. if (Database::num_rows($res) > 0) {
  1856. $row = Database::fetch_row($res);
  1857. $order = $row[0] + 1;
  1858. }
  1859. $sql = "INSERT INTO $t_cf
  1860. SET field_type = '$fieldtype',
  1861. field_variable = '$fieldvarname',
  1862. field_display_text = '$fieldtitle',
  1863. field_order = '$order',
  1864. tms = FROM_UNIXTIME($time)";
  1865. Database::query($sql);
  1866. return Database::insert_id();
  1867. }
  1868. /**
  1869. * Updates course attribute. Note that you need to check that your attribute is valid before you use this function
  1870. *
  1871. * @param int Course id
  1872. * @param string Attribute name
  1873. * @param string Attribute value
  1874. * @return bool True if attribute was successfully updated, false if course was not found or attribute name is invalid
  1875. */
  1876. public static function update_attribute($id, $name, $value) {
  1877. $id = (int)$id;
  1878. $table = Database::get_main_table(TABLE_MAIN_COURSE);
  1879. $sql = "UPDATE $table SET $name = '".Database::escape_string($value)."' WHERE id = '$id';";
  1880. return Database::query($sql);
  1881. }
  1882. /**
  1883. * Update course attributes. Will only update attributes with a non-empty value. Note that you NEED to check that your attributes are valid before using this function
  1884. *
  1885. * @param int Course id
  1886. * @param array Associative array with field names as keys and field values as values
  1887. * @return bool True if update was successful, false otherwise
  1888. */
  1889. public static function update_attributes($id, $attributes) {
  1890. $id = (int)$id;
  1891. $table = Database::get_main_table(TABLE_MAIN_COURSE);
  1892. $sql = "UPDATE $table SET ";
  1893. $i = 0;
  1894. foreach($attributes as $name => $value) {
  1895. if($value != '') {
  1896. if($i > 0) {
  1897. $sql .= ", ";
  1898. }
  1899. $sql .= " $name = '".Database::escape_string($value)."'";
  1900. $i++;
  1901. }
  1902. }
  1903. $sql .= " WHERE id = '$id';";
  1904. return Database::query($sql);
  1905. }
  1906. /**
  1907. * Update an extra field value for a given course
  1908. * @param integer Course ID
  1909. * @param string Field variable name
  1910. * @param string Field value
  1911. * @return boolean true if field updated, false otherwise
  1912. */
  1913. public static function update_course_extra_field_value($course_code, $fname, $fvalue = '') {
  1914. $t_cfv = Database::get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
  1915. $t_cf = Database::get_main_table(TABLE_MAIN_COURSE_FIELD);
  1916. $fname = Database::escape_string($fname);
  1917. $course_code = Database::escape_string($course_code);
  1918. $fvalues = '';
  1919. if (is_array($fvalue)) {
  1920. foreach ($fvalue as $val) {
  1921. $fvalues .= Database::escape_string($val).';';
  1922. }
  1923. if (!empty($fvalues)) {
  1924. $fvalues = substr($fvalues, 0, -1);
  1925. }
  1926. } else {
  1927. $fvalues = Database::escape_string($fvalue);
  1928. }
  1929. $sqlcf = "SELECT * FROM $t_cf WHERE field_variable='$fname'";
  1930. $rescf = Database::query($sqlcf);
  1931. if (Database::num_rows($rescf) == 1) {
  1932. // Ok, the field exists
  1933. // Check if enumerated field, if the option is available
  1934. $rowcf = Database::fetch_array($rescf);
  1935. $tms = time();
  1936. $sqlcfv = "SELECT * FROM $t_cfv WHERE course_code = '$course_code' AND field_id = '".$rowcf['id']."' ORDER BY id";
  1937. $rescfv = Database::query($sqlcfv);
  1938. $n = Database::num_rows($rescfv);
  1939. if ($n > 1) {
  1940. //problem, we already have to values for this field and user combination - keep last one
  1941. while ($rowcfv = Database::fetch_array($rescfv)) { // See the TODO note below.
  1942. if ($n > 1) {
  1943. $sqld = "DELETE FROM $t_cfv WHERE id = ".$rowcfv['id'];
  1944. $resd = Database::query($sqld);
  1945. $n--;
  1946. }
  1947. $rowcfv = Database::fetch_array($rescfv);
  1948. if ($rowcfv['field_value'] != $fvalues) {
  1949. $sqlu = "UPDATE $t_cfv SET field_value = '$fvalues', tms = FROM_UNIXTIME($tms) WHERE id = ".$rowcfv['id'];
  1950. $resu = Database::query($sqlu);
  1951. return ($resu ? true : false);
  1952. }
  1953. return true; // TODO: Sure exit from the function occures in this "while" cycle. Logic should checked. Maybe "if" instead of "while"? It is not clear...
  1954. }
  1955. } elseif ($n == 1) {
  1956. //we need to update the current record
  1957. $rowcfv = Database::fetch_array($rescfv);
  1958. if ($rowcfv['field_value'] != $fvalues) {
  1959. $sqlu = "UPDATE $t_cfv SET field_value = '$fvalues', tms = FROM_UNIXTIME($tms) WHERE id = ".$rowcfv['id'];
  1960. $resu = Database::query($sqlu);
  1961. return ($resu ? true : false);
  1962. }
  1963. return true;
  1964. } else {
  1965. $sqli = "INSERT INTO $t_cfv (course_code,field_id,field_value,tms) " .
  1966. "VALUES ('$course_code',".$rowcf['id'].",'$fvalues',FROM_UNIXTIME($tms))";
  1967. $resi = Database::query($sqli);
  1968. return ($resi ? true : false);
  1969. }
  1970. } else {
  1971. return false; //field not found
  1972. }
  1973. }
  1974. /**
  1975. * Get the course id of an course by the database name
  1976. * @param string The database name
  1977. * @return string The course id
  1978. */
  1979. public static function get_course_id_by_database_name($db_name) {
  1980. return Database::result(Database::query('SELECT code FROM '.Database::get_main_table(TABLE_MAIN_COURSE).
  1981. ' WHERE db_name="'.Database::escape_string($db_name).'"'), 0, 'code');
  1982. }
  1983. public static function get_session_category_id_by_session_id($session_id) {
  1984. return Database::result(Database::query('SELECT sc.id session_category
  1985. FROM '.Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY).' sc
  1986. INNER JOIN '.Database::get_main_table(TABLE_MAIN_SESSION).' s
  1987. ON sc.id=s.session_category_id WHERE s.id="'.Database::escape_string($session_id).'"'),
  1988. 0, 'session_category');
  1989. }
  1990. /**
  1991. * Get the course id of an course by the database name
  1992. * @param string The database name
  1993. * @return string The course id
  1994. */
  1995. public static function get_course_extra_field_list($code) {
  1996. $tbl_course_field = Database::get_main_table(TABLE_MAIN_COURSE_FIELD);
  1997. $tbl_course_field_value = Database::get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
  1998. $sql_field = "SELECT id, field_type, field_variable, field_display_text, field_default_value
  1999. FROM $tbl_course_field WHERE field_visible = '1' ";
  2000. $res_field = Database::query($sql_field);
  2001. $extra_fields = array();
  2002. while($rowcf = Database::fetch_array($res_field)) {
  2003. $extra_field_id = $rowcf['id'];
  2004. $sql_field_value = "SELECT field_value FROM $tbl_course_field_value WHERE course_code = '$code' AND field_id = '$extra_field_id' ";
  2005. $res_field_value = Database::query($sql_field_value);
  2006. if(Database::num_rows($res_field_value) > 0 ) {
  2007. $r_field_value = Database::fetch_row($res_field_value);
  2008. $rowcf['extra_field_value'] = $r_field_value[0];
  2009. }
  2010. $extra_fields[] = $rowcf;
  2011. }
  2012. return $extra_fields;
  2013. }
  2014. /**
  2015. * Gets the value of a course extra field. Returns null if it was not found
  2016. *
  2017. * @param string Name of the extra field
  2018. * @param string Course code
  2019. * @return string Value
  2020. */
  2021. public static function get_course_extra_field_value($field_name, $code) {
  2022. $tbl_course_field = Database::get_main_table(TABLE_MAIN_COURSE_FIELD);
  2023. $tbl_course_field_value = Database::get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
  2024. $sql = "SELECT id FROM $tbl_course_field WHERE field_visible = '1' AND field_variable = '$field_name';";
  2025. $res = Database::query($sql);
  2026. $row = Database::fetch_object($res);
  2027. if(!$row) {
  2028. return null;
  2029. } else {
  2030. $sql_field_value = "SELECT field_value FROM $tbl_course_field_value WHERE course_code = '$code' AND field_id = '{$row->id}';";
  2031. $res_field_value = Database::query($sql_field_value);
  2032. $row_field_value = Database::fetch_object($res_field_value);
  2033. if(!$row_field_value) {
  2034. return null;
  2035. } else {
  2036. return $row_field_value['field_value'];
  2037. }
  2038. }
  2039. }
  2040. /**
  2041. * Get the database name of a course by the code
  2042. * @param string The course code
  2043. * @return string The database name
  2044. */
  2045. public static function get_name_database_course($course_code) {
  2046. return Database::result(Database::query('SELECT db_name FROM '.Database::get_main_table(TABLE_MAIN_COURSE).
  2047. ' WHERE code="'.Database::escape_string($course_code).'"'), 0, 'db_name');
  2048. }
  2049. /**
  2050. * Lists details of the course description
  2051. * @param array The course description
  2052. * @param string The encoding
  2053. * @param bool If true is displayed if false is hidden
  2054. * @return string The course description in html
  2055. */
  2056. public static function get_details_course_description_html($descriptions, $charset, $action_show = true) {
  2057. if (isset($descriptions) && count($descriptions) > 0) {
  2058. $data = '';
  2059. foreach ($descriptions as $id => $description) {
  2060. $data .= '<div class="sectiontitle">';
  2061. if (api_is_allowed_to_edit() && $action_show) {
  2062. //delete
  2063. $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;">';
  2064. $data .= Display::return_icon('delete.gif', get_lang('Delete'), array('style' => 'vertical-align:middle;float:right;'));
  2065. $data .= '</a> ';
  2066. //edit
  2067. $data .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&amp;description_id='.$description->id.'">';
  2068. $data .= Display::return_icon('edit.png', get_lang('Edit'), array('style' => 'vertical-align:middle;float:right; padding-right:4px;'), ICON_SIZE_SMALL);
  2069. $data .= '</a> ';
  2070. }
  2071. $data .= $description->title;
  2072. $data .= '</div>';
  2073. $data .= '<div class="sectioncomment">';
  2074. $data .= $description->content;
  2075. $data .= '</div>';
  2076. }
  2077. } else {
  2078. $data .= '<em>'.get_lang('ThisCourseDescriptionIsEmpty').'</em>';
  2079. }
  2080. return $data;
  2081. }
  2082. /**
  2083. * Returns the details of a course category
  2084. *
  2085. * @param string Category code
  2086. * @return array Course category
  2087. */
  2088. public static function get_course_category($code) {
  2089. $table_categories = Database::get_main_table(TABLE_MAIN_CATEGORY);
  2090. $sql = "SELECT * FROM $table_categories WHERE code = '$code';";
  2091. return Database::fetch_array(Database::query($sql));
  2092. }
  2093. /**
  2094. * Get count rows of a table inside a course database
  2095. * @param string The table of which the rows should be counted
  2096. * @param int optionally count rows by session id
  2097. * @return int The number of rows in the given table.
  2098. */
  2099. public static function count_rows_course_table($table, $session_id = '', $course_id = null) {
  2100. $condition_session = '';
  2101. if ($session_id !== '') {
  2102. $session_id = intval($session_id);
  2103. $condition_session = " AND session_id = '$session_id' ";
  2104. }
  2105. if (!empty($course_id)) {
  2106. $course_id = intval($course_id);
  2107. } else {
  2108. $course_id = api_get_course_int_id();
  2109. }
  2110. $condition_session .= " AND c_id = '$course_id' ";
  2111. $sql = "SELECT COUNT(*) AS n FROM $table WHERE 1=1 $condition_session ";
  2112. $rs = Database::query($sql);
  2113. $row = Database::fetch_row($rs);
  2114. return $row[0];
  2115. }
  2116. /**
  2117. * Subscribes courses to human resource manager (Dashboard feature)
  2118. * @param int Human Resource Manager id
  2119. * @param array Courses code
  2120. * @param int Relation type
  2121. **/
  2122. public static function suscribe_courses_to_hr_manager($hr_manager_id, $courses_list) {
  2123. // Database Table Definitions
  2124. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  2125. $tbl_course_rel_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  2126. $tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  2127. $hr_manager_id = intval($hr_manager_id);
  2128. $affected_rows = 0;
  2129. //Deleting assigned courses to hrm_id
  2130. if (api_is_multiple_url_enabled()) {
  2131. $sql = "SELECT s.c_id FROM $tbl_course_rel_user s INNER JOIN $tbl_course_rel_access_url a ON (a.c_id = s.c_id)
  2132. WHERE user_id = $hr_manager_id AND relation_type=".COURSE_RELATION_TYPE_RRHH." AND access_url_id = ".api_get_current_access_url_id()."";
  2133. } else {
  2134. $sql = "SELECT c_id FROM $tbl_course_rel_user
  2135. WHERE user_id = $hr_manager_id AND relation_type=".COURSE_RELATION_TYPE_RRHH." ";
  2136. }
  2137. $result = Database::query($sql);
  2138. if (Database::num_rows($result) > 0) {
  2139. while ($row = Database::fetch_array($result)) {
  2140. $sql = "DELETE FROM $tbl_course_rel_user WHERE c_id = '{$row['c_id']}' AND user_id = $hr_manager_id AND relation_type=".COURSE_RELATION_TYPE_RRHH." ";
  2141. Database::query($sql);
  2142. }
  2143. }
  2144. // inserting new courses list
  2145. if (is_array($courses_list)) {
  2146. foreach ($courses_list as $courseId) {
  2147. $courseId = Database::escape_string($courseId);
  2148. $insert_sql = "INSERT IGNORE INTO $tbl_course_rel_user(c_id, user_id, status, relation_type) VALUES('$courseId', $hr_manager_id, '".DRH."', '".COURSE_RELATION_TYPE_RRHH."')";
  2149. $result = Database::query($insert_sql);
  2150. if (Database::affected_rows($result)) {
  2151. $affected_rows++;
  2152. }
  2153. }
  2154. }
  2155. return $affected_rows;
  2156. }
  2157. /**
  2158. * get courses followed by human resources manager
  2159. * @param int human resources manager id
  2160. * @return array courses
  2161. */
  2162. public static function get_courses_followed_by_drh($user_id) {
  2163. // Database Table Definitions
  2164. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  2165. $tbl_course_rel_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  2166. $tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  2167. $user_id = intval($user_id);
  2168. $assigned_courses_to_hrm = array();
  2169. if (api_get_multiple_access_url()) {
  2170. $sql = "SELECT *, id as real_id FROM $tbl_course c
  2171. INNER JOIN $tbl_course_rel_user cru ON (cru.c_id = c.id)
  2172. LEFT JOIN $tbl_course_rel_access_url a ON (a.c_id = c.id)
  2173. WHERE cru.user_id = '$user_id' AND status = ".DRH." AND relation_type = '".COURSE_RELATION_TYPE_RRHH."' AND access_url_id = ".api_get_current_access_url_id()."";
  2174. } else {
  2175. $sql = "SELECT *, id as real_id FROM $tbl_course c
  2176. INNER JOIN $tbl_course_rel_user cru ON cru.c_id = c.c_id AND cru.user_id = '$user_id' AND status = ".DRH." AND relation_type = '".COURSE_RELATION_TYPE_RRHH."' ";
  2177. }
  2178. $rs_assigned_courses = Database::query($sql);
  2179. if (Database::num_rows($rs_assigned_courses) > 0) {
  2180. while ($row_assigned_courses = Database::fetch_array($rs_assigned_courses)) {
  2181. $assigned_courses_to_hrm[$row_assigned_courses['code']] = $row_assigned_courses;
  2182. }
  2183. }
  2184. return $assigned_courses_to_hrm;
  2185. }
  2186. /**
  2187. * check if a course is special (autoregister)
  2188. * @param string course code
  2189. */
  2190. public static function is_special_course($course_code){
  2191. $tbl_course_field_value = Database::get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
  2192. $tbl_course_field = Database::get_main_table(TABLE_MAIN_COURSE_FIELD);
  2193. $is_special = false;
  2194. $sql = "SELECT course_code FROM $tbl_course_field_value tcfv INNER JOIN $tbl_course_field tcf ON " .
  2195. " tcfv.field_id = tcf.id WHERE tcf.field_variable = 'special_course' AND tcfv.field_value = 1 AND course_code='$course_code'";
  2196. $result = Database::query($sql);
  2197. $num_rows = Database::num_rows($result);
  2198. if ($num_rows > 0){
  2199. $is_special = true;
  2200. }
  2201. return $is_special;
  2202. }
  2203. /**
  2204. * Update course picture
  2205. * @param string Course code
  2206. * @param string File name
  2207. * @param string The full system name of the image from which course picture will be created.
  2208. * @return bool Returns the resulting. In case of internal error or negative validation returns FALSE.
  2209. */
  2210. public static function update_course_picture($course_code, $filename, $source_file = null) {
  2211. $course_info = api_get_course_info($course_code);
  2212. $store_path = api_get_path(SYS_COURSE_PATH).$course_info['path']; // course path
  2213. $course_image = $store_path.'/course-pic.png'; // image name for courses
  2214. $course_medium_image = $store_path.'/course-pic85x85.png';
  2215. //$extension = strtolower(substr(strrchr($filename, '.'), 1));
  2216. if (file_exists($course_image)) {
  2217. @unlink($course_image);
  2218. }
  2219. if (file_exists($course_medium_image)) {
  2220. @unlink($course_medium_image);
  2221. }
  2222. $my_course_image = new Image($source_file);
  2223. $result = $my_course_image->send_image($course_image, -1, 'png');
  2224. //Redimension image to 100x85
  2225. if ($result) {
  2226. $medium = new Image($course_image);
  2227. //$picture_infos = $medium->get_image_size();
  2228. $medium->resize(100, 85, 0, false);
  2229. $medium->send_image($store_path.'/course-pic85x85.png', -1, 'png');
  2230. }
  2231. return $result;
  2232. }
  2233. /**
  2234. * Builds the course block in user_portal.php
  2235. * @todo use Twig
  2236. */
  2237. public static function course_item_html($params, $is_sub_content = false) {
  2238. global $app;
  2239. if ($app['full_width']) {
  2240. $rowDiv = '<div class="row-fluid">';
  2241. } else {
  2242. $rowDiv = '<div class="row">';
  2243. }
  2244. $html = '';
  2245. $class = "well course-box";
  2246. if ($is_sub_content) {
  2247. $class = "course_item";
  2248. }
  2249. if (!empty($params['is_session'])) {
  2250. $class .= " session-item";
  2251. }
  2252. $html .= '<div class="'.$class.'">';
  2253. $html .= $rowDiv;
  2254. $html .= '<div class="span7">';
  2255. $html .= $rowDiv;
  2256. $html .= '<div class="span1 course-box-thumbnail-box">';
  2257. if (!empty($params['link'])) {
  2258. $html .= '<a class="thumbnail" href="'.$params['link'].'">';
  2259. $html .= $params['icon'];
  2260. $html .= '</a>';
  2261. } else {
  2262. $html .= '<div class="thumbnail">';
  2263. $html .= $params['icon'];
  2264. $html .= '</div>';
  2265. }
  2266. $html .= '</div>';
  2267. $notifications = isset($params['notifications']) ? $params['notifications'] : null;
  2268. $param_class = isset($params['class']) ? $params['class'] : '';
  2269. if (!empty($params['is_session'])) {
  2270. $param_class .= ' session-box-text';
  2271. } else {
  2272. $param_class .= ' course-box-text';
  2273. }
  2274. $html .= '<div class="span6 '.$param_class.'">';
  2275. $html .='<h3>'.$params['title'].$notifications.'</h3> ';
  2276. if (!empty($params['subtitle'])) {
  2277. $html .= '<small>'.$params['subtitle'].'</small>';
  2278. }
  2279. if (!empty($params['teachers'])) {
  2280. $html .= '<h5>'.Display::return_icon('teacher.png', get_lang('Teacher'), array(), ICON_SIZE_TINY).$params['teachers'].'</h5>';
  2281. }
  2282. if (!empty($params['coaches'])) {
  2283. $html .= '<h5>'.Display::return_icon('teacher.png', get_lang('Coach'), array(), ICON_SIZE_TINY).$params['coaches'].'</h5>';
  2284. }
  2285. $html .= '</div>';
  2286. $html .= '</div>';
  2287. $html .= '</div>';
  2288. $params['right_actions'] = isset($params['right_actions']) ? $params['right_actions'] : null;
  2289. $html .= '<div class="span1 pull-right course-box-actions">'.$params['right_actions'].'</div>';
  2290. $html .= '</div>';
  2291. $html .= '</div>';
  2292. return $html;
  2293. }
  2294. public static function course_item_parent($main_content, $sub_content, $sub_sub_content = null) {
  2295. return '<div class="well">'.$main_content.$sub_content.$sub_sub_content.'</div>';
  2296. }
  2297. /**
  2298. * Display special courses (and only these) as several HTML divs of class userportal-course-item
  2299. *
  2300. * Special courses are courses that stick on top of the list and are "auto-registerable"
  2301. * in the sense that any user clicking them is registered as a student
  2302. * @param int User id
  2303. * @param bool Whether to show the document quick-loader or not
  2304. * @return void
  2305. */
  2306. public static function displaySpecialCourses($user_id, $filter, $load_dirs, $getCount, $start = null, $maxPerPage = null) {
  2307. $user_id = intval($user_id);
  2308. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  2309. $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  2310. $special_course_list = self::get_special_course_list();
  2311. $html = null;
  2312. if (!empty($special_course_list)) {
  2313. $with_special_courses = ' course.code IN ("'.implode('","',$special_course_list).'")';
  2314. } else {
  2315. return null;
  2316. }
  2317. $select = " course.id,
  2318. course.code,
  2319. course.subscribe subscr,
  2320. course.unsubscribe unsubscr,
  2321. course_rel_user.status status,
  2322. course_rel_user.sort sort,
  2323. course_rel_user.user_course_cat user_course_cat,
  2324. course_rel_user.user_id";
  2325. if ($getCount) {
  2326. $select = "COUNT(course.id) as total";
  2327. }
  2328. $sql = "SELECT $select
  2329. FROM $tbl_course course
  2330. LEFT JOIN $tbl_course_user course_rel_user
  2331. ON course.id = course_rel_user.c_id AND course_rel_user.user_id = '$user_id'
  2332. WHERE $with_special_courses ";
  2333. if ($getCount) {
  2334. $result = Database::query($sql);
  2335. $row = Database::fetch_array($result);
  2336. return $row['total'];
  2337. }
  2338. $group = " GROUP BY course.code ";
  2339. $sql .= $group;
  2340. $rs_special_course = Database::query($sql);
  2341. $number_of_courses = Database::num_rows($rs_special_course);
  2342. $key = 0;
  2343. if ($number_of_courses > 0) {
  2344. while ($course = Database::fetch_array($rs_special_course)) {
  2345. $course_info = api_get_course_info($course['code']);
  2346. $params = array();
  2347. $course_info['id_session'] = null;
  2348. $course_info['status'] = $course['status'];
  2349. $show_notification = Display::show_notification($course_info);
  2350. if (empty($course['user_id'])) {
  2351. $course['status'] = STUDENT;
  2352. }
  2353. $params['icon'] = Display::return_icon('blackboard.png', $course_info['title'], array(), ICON_SIZE_LARGE);
  2354. $params['right_actions'] = '';
  2355. if (api_is_platform_admin()) {
  2356. if ($load_dirs) {
  2357. $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>';
  2358. $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>';
  2359. $params['right_actions'] .= Display::div('', array('id' => 'document_result_'.$course['real_id'].'_0', 'class'=>'document_preview_container'));
  2360. } else {
  2361. $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>';
  2362. }
  2363. if ($course['status'] == COURSEMANAGER) {
  2364. //echo Display::return_icon('teachers.gif', get_lang('Status').': '.get_lang('Teacher'), array('style'=>'width: 11px; height: 11px;'));
  2365. }
  2366. } else {
  2367. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED) {
  2368. if ($load_dirs) {
  2369. $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>';
  2370. $params['right_actions'] .= Display::div('', array('id' => 'document_result_'.$course['real_id'].'_0', 'class'=>'document_preview_container'));
  2371. }
  2372. }
  2373. }
  2374. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED || $course['status'] == COURSEMANAGER) {
  2375. $course_title = '<a href="'.api_get_path(WEB_COURSE_PATH).$course_info['path'].'/index.php?id_session=0&amp;autoreg=1">'.$course_info['title'].'</a>';
  2376. } else {
  2377. $course_title = $course_info['title']." ".Display::tag('span',get_lang('CourseClosed'), array('class'=>'item_closed'));
  2378. }
  2379. if (api_get_setting('display_coursecode_in_courselist') == 'true') {
  2380. $course_title .= ' ('.$course_info['visual_code'].') ';
  2381. }
  2382. if (api_get_setting('display_teacher_in_courselist') == 'true') {
  2383. $params['teachers'] = CourseManager::get_teacher_list_from_course_code_to_string($course['real_id'], self::USER_SEPARATOR, true);
  2384. }
  2385. $course_title .= '&nbsp;';
  2386. $course_title .= Display::return_icon('klipper.png', get_lang('CourseAutoRegister'));
  2387. $params['title'] = $course_title;
  2388. $params['link'] = api_get_path(WEB_COURSE_PATH).$course_info['path'].'/index.php?id_session=0&amp;autoreg=1';
  2389. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED) {
  2390. $params['notifications'] = $show_notification;
  2391. }
  2392. $html .= self::course_item_html($params, false);
  2393. $key++;
  2394. }
  2395. }
  2396. return $html;
  2397. }
  2398. public static function displayPersonalCourseCategories($user_id, $filter, $load_dirs, $getCount, $start = null, $maxPerPage = null) {
  2399. $tableUserCourseCategory = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
  2400. // Table definitions
  2401. $TABLECOURS = Database :: get_main_table(TABLE_MAIN_COURSE);
  2402. $TABLECOURSUSER = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  2403. $TABLE_ACCESS_URL_REL_COURSE = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  2404. $current_url_id = api_get_current_access_url_id();
  2405. $sql = "SELECT * FROM $tableUserCourseCategory
  2406. WHERE user_id = $user_id";
  2407. if ($getCount) {
  2408. $sql = "SELECT COUNT(id) as total FROM $tableUserCourseCategory WHERE user_id = $user_id";
  2409. $result = Database::query($sql);
  2410. $row = Database::fetch_array($result);
  2411. return $row['total'];
  2412. }
  2413. $order = " ORDER BY sort";
  2414. $sql .= $order;
  2415. if (isset($start) && isset($maxPerPage)) {
  2416. $start = intval($start);
  2417. $maxPerPage = intval($maxPerPage);
  2418. $limitCondition = " LIMIT $start, $maxPerPage";
  2419. $sql .= $limitCondition;
  2420. }
  2421. $result = Database::query($sql);
  2422. $html = null;
  2423. if (Database::num_rows($result)) {
  2424. while ($category = Database::fetch_array($result)) {
  2425. $categoryId = $category['id'];
  2426. $select = " SELECT DISTINCT
  2427. course.id,
  2428. course.title,
  2429. course.code,
  2430. course.subscribe subscr,
  2431. course.unsubscribe unsubscr,
  2432. course_rel_user.status status,
  2433. course_rel_user.sort sort,
  2434. course_rel_user.user_course_cat user_course_cat";
  2435. $from = "$TABLECOURS course, $TABLECOURSUSER course_rel_user, $TABLE_ACCESS_URL_REL_COURSE url, $tableUserCourseCategory user_cat";
  2436. $where = " course.id = course_rel_user.c_id AND
  2437. url.c_id = course.id AND
  2438. user_cat.user_id = $user_id AND
  2439. course_rel_user.user_id = $user_id AND
  2440. course_rel_user.user_course_cat = $categoryId ";
  2441. // Use user's classification for courses (if any).
  2442. $order = " ORDER BY user_cat.sort ASC";
  2443. $sql = "$select FROM $from WHERE $where ";
  2444. // corresponding to the current URL.
  2445. if (api_get_multiple_access_url() && $current_url_id != -1) {
  2446. $sql .= " AND url.course_code=course.code AND access_url_id='".$current_url_id."'";
  2447. }
  2448. $sql .= $order;
  2449. $resultCourse = Database::query($sql);
  2450. $course_list = array();
  2451. $courseHTML = null;
  2452. // Browse through all courses.
  2453. while ($course = Database::fetch_array($resultCourse)) {
  2454. $course_info = api_get_course_info($course['code']);
  2455. //$course['id_session'] = null;
  2456. $course_info['id_session'] = null;
  2457. $course_info['status'] = $course['status'];
  2458. //In order to avoid doubles
  2459. if (in_array($course_info['real_id'], $course_list)) {
  2460. continue;
  2461. } else {
  2462. $course_list[] = $course_info['real_id'];
  2463. }
  2464. // For each course, get if there is any notification icon to show
  2465. // (something that would have changed since the user's last visit).
  2466. $show_notification = Display :: show_notification($course_info);
  2467. // New code displaying the user's status in respect to this course.
  2468. $status_icon = Display::return_icon('blackboard.png', $course_info['title'], array(), ICON_SIZE_LARGE);
  2469. $params = array();
  2470. $params['right_actions'] = '';
  2471. if (api_is_platform_admin()) {
  2472. if ($load_dirs) {
  2473. $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>';
  2474. $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>';
  2475. $params['right_actions'] .= Display::div('', array('id' => 'document_result_'.$course_info['real_id'].'_0', 'class'=>'document_preview_container'));
  2476. } else {
  2477. $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>';
  2478. }
  2479. if ($course_info['status'] == COURSEMANAGER) {
  2480. //echo Display::return_icon('teachers.gif', get_lang('Status').': '.get_lang('Teacher'), array('style'=>'width: 11px; height: 11px;'));
  2481. }
  2482. } else {
  2483. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED) {
  2484. if ($load_dirs) {
  2485. $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>';
  2486. $params['right_actions'] .= Display::div('', array('id' => 'document_result_'.$course_info['real_id'].'_0', 'class'=>'document_preview_container'));
  2487. } else {
  2488. if ($course_info['status'] == COURSEMANAGER) {
  2489. $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>';
  2490. }
  2491. }
  2492. }
  2493. }
  2494. $course_title_url = '';
  2495. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED || $course['status'] == COURSEMANAGER) {
  2496. $course_title_url = api_get_path(WEB_COURSE_PATH).$course_info['path'].'/index.php?id_session=0';
  2497. $course_title = Display::url($course_info['title'], $course_title_url);
  2498. } else {
  2499. $course_title = $course_info['title']." ".Display::tag('span',get_lang('CourseClosed'), array('class'=>'item_closed'));
  2500. }
  2501. // Start displaying the course block itself
  2502. if (api_get_setting('display_coursecode_in_courselist') == 'true') {
  2503. $course_title .= ' ('.$course_info['visual_code'].') ';
  2504. }
  2505. if (api_get_setting('display_teacher_in_courselist') == 'true') {
  2506. $teachers = CourseManager::get_teacher_list_from_course_code_to_string($course['real_id'], self::USER_SEPARATOR, true);
  2507. }
  2508. $params['link'] = $course_title_url;
  2509. $params['icon'] = $status_icon;
  2510. $params['title'] = $course_title;
  2511. $params['teachers'] = $teachers;
  2512. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED) {
  2513. $params['notifications'] = $show_notification;
  2514. }
  2515. $courseHTML .= self::course_item_html($params, true);
  2516. }
  2517. $params = array();
  2518. $params['icon'] = Display::return_icon('folder_yellow.png', $category['title'], array(), ICON_SIZE_LARGE);
  2519. $params['title'] = $category['title'];
  2520. $params['class'] = 'table_user_course_category';
  2521. $html .= self::course_item_parent(self::course_item_html($params, true), $courseHTML);
  2522. }
  2523. }
  2524. return $html;
  2525. }
  2526. /**
  2527. * @param int $user_id
  2528. * @param $filter
  2529. * @param bool $load_dirs
  2530. * @param int $getCount
  2531. * @param int $start
  2532. * @param null $maxPerPage
  2533. * @return null|string
  2534. */
  2535. static function displayCourses($user_id, $filter, $load_dirs, $getCount, $start = null, $maxPerPage = null)
  2536. {
  2537. // Table definitions
  2538. $TABLECOURS = Database :: get_main_table(TABLE_MAIN_COURSE);
  2539. $TABLECOURSUSER = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  2540. $TABLE_ACCESS_URL_REL_COURSE = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  2541. $current_url_id = api_get_current_access_url_id();
  2542. // Get course list auto-register
  2543. $special_course_list = self::get_special_course_list();
  2544. $without_special_courses = '';
  2545. if (!empty($special_course_list)) {
  2546. //$without_special_courses = ' AND course.code NOT IN ("'.implode('","',$special_course_list).'")';
  2547. }
  2548. $select = " SELECT DISTINCT course.id,
  2549. course.title,
  2550. course.code,
  2551. course.subscribe subscr,
  2552. course.unsubscribe unsubscr,
  2553. course_rel_user.status status,
  2554. course_rel_user.sort sort,
  2555. course_rel_user.user_course_cat user_course_cat,
  2556. course.id as real_id
  2557. ";
  2558. $from = "$TABLECOURS course, $TABLECOURSUSER course_rel_user, $TABLE_ACCESS_URL_REL_COURSE url ";
  2559. $where = " course.id = course_rel_user.c_id AND
  2560. url.c_id = course.id AND
  2561. course_rel_user.user_id = '".$user_id."' AND
  2562. course_rel_user.user_course_cat = 0
  2563. ";
  2564. $order = " ORDER BY course_rel_user.user_course_cat, course_rel_user.sort ASC";
  2565. if ($getCount) {
  2566. $select = "SELECT count(course.id) as total";
  2567. }
  2568. $sql = "$select FROM $from WHERE $where $without_special_courses ";
  2569. // corresponding to the current URL.
  2570. if (api_get_multiple_access_url() && $current_url_id != -1) {
  2571. $sql .= " AND url.c_id = course.id AND access_url_id='".$current_url_id."'";
  2572. }
  2573. $sql .= $order;
  2574. if (isset($start) && isset($maxPerPage)) {
  2575. $start = intval($start);
  2576. $maxPerPage = intval($maxPerPage);
  2577. $limitCondition = " LIMIT $start, $maxPerPage";
  2578. $sql .= $limitCondition;
  2579. }
  2580. if ($getCount) {
  2581. $result = Database::query($sql);
  2582. $row = Database::fetch_array($result);
  2583. return $row['total'];
  2584. }
  2585. $result = Database::query($sql);
  2586. $html = null;
  2587. $course_list = array();
  2588. // Browse through all courses.
  2589. while ($course = Database::fetch_array($result)) {
  2590. $course_info = api_get_course_info($course['code']);
  2591. //$course['id_session'] = null;
  2592. $course_info['id_session'] = null;
  2593. $course_info['status'] = $course['status'];
  2594. //In order to avoid doubles
  2595. if (in_array($course_info['real_id'], $course_list)) {
  2596. continue;
  2597. } else {
  2598. $course_list[] = $course_info['real_id'];
  2599. }
  2600. // For each course, get if there is any notification icon to show
  2601. // (something that would have changed since the user's last visit).
  2602. $show_notification = Display :: show_notification($course_info);
  2603. // New code displaying the user's status in respect to this course.
  2604. $status_icon = Display::return_icon('blackboard.png', $course_info['title'], array(), ICON_SIZE_LARGE);
  2605. $params = array();
  2606. $params['right_actions'] = '';
  2607. if (api_is_platform_admin()) {
  2608. if ($load_dirs) {
  2609. $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>';
  2610. $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>';
  2611. $params['right_actions'] .= Display::div('', array('id' => 'document_result_'.$course_info['real_id'].'_0', 'class'=>'document_preview_container'));
  2612. } else {
  2613. $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>';
  2614. }
  2615. if ($course_info['status'] == COURSEMANAGER) {
  2616. //echo Display::return_icon('teachers.gif', get_lang('Status').': '.get_lang('Teacher'), array('style'=>'width: 11px; height: 11px;'));
  2617. }
  2618. } else {
  2619. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED) {
  2620. if ($load_dirs) {
  2621. $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>';
  2622. $params['right_actions'] .= Display::div('', array('id' => 'document_result_'.$course_info['real_id'].'_0', 'class'=>'document_preview_container'));
  2623. } else {
  2624. if ($course_info['status'] == COURSEMANAGER) {
  2625. $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>';
  2626. }
  2627. }
  2628. }
  2629. }
  2630. $course_title = $course_info['title'];
  2631. $course_title_url = '';
  2632. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED || $course['status'] == COURSEMANAGER) {
  2633. $course_title_url = api_get_path(WEB_COURSE_PATH).$course_info['path'].'/index.php?id_session=0';
  2634. $course_title = Display::url($course_info['title'], $course_title_url);
  2635. } else {
  2636. $course_title = $course_info['title']." ".Display::tag('span',get_lang('CourseClosed'), array('class'=>'item_closed'));
  2637. }
  2638. // Start displaying the course block itself
  2639. if (api_get_setting('display_coursecode_in_courselist') == 'true') {
  2640. $course_title .= ' ('.$course_info['visual_code'].') ';
  2641. }
  2642. $teachers = null;
  2643. if (api_get_setting('display_teacher_in_courselist') == 'true') {
  2644. $teachers = $course_info['teacher_list_formatted'];
  2645. }
  2646. $params['link'] = $course_title_url;
  2647. $params['icon'] = $status_icon;
  2648. $params['title'] = $course_title;
  2649. $params['teachers'] = $teachers;
  2650. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED) {
  2651. $params['notifications'] = $show_notification;
  2652. }
  2653. $is_subcontent = true;
  2654. if (empty($user_category_id)) {
  2655. $is_subcontent = false;
  2656. }
  2657. $html .= self::course_item_html($params, $is_subcontent);
  2658. }
  2659. return $html;
  2660. }
  2661. /**
  2662. * Display courses (without special courses) as several HTML divs
  2663. * of course categories, as class userportal-catalog-item.
  2664. * @uses display_courses_in_category() to display the courses themselves
  2665. * @param int user id
  2666. * @param bool Whether to show the document quick-loader or not
  2667. * @return void
  2668. */
  2669. public static function display_courses($user_id, $load_dirs = false) {
  2670. $user_id = intval($user_id);
  2671. if (empty($user_id)) {
  2672. $user_id = api_get_user_id();
  2673. }
  2674. $html = null;
  2675. // Step 1: We get all the categories of the user
  2676. $tucc = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
  2677. $sql = "SELECT id, title FROM $tucc WHERE user_id='".$user_id."' ORDER BY sort ASC";
  2678. $result = Database::query($sql);
  2679. while ($row = Database::fetch_array($result)) {
  2680. $params = array();
  2681. // We simply display the title of the category.
  2682. $params['icon'] = Display::return_icon('folder_yellow.png', $row['title'], array(), ICON_SIZE_LARGE);
  2683. $params['title'] = $row['title'];
  2684. $params['class'] = 'table_user_course_category';
  2685. $html .= self::course_item_parent(self::course_item_html($params, true), self :: display_courses_in_category($row['id'], $load_dirs));
  2686. }
  2687. // Step 2: We display the course without a user category.
  2688. $html .= self :: display_courses_in_category(0, $load_dirs);
  2689. return $html;
  2690. }
  2691. /**
  2692. * Display courses inside a category (without special courses) as HTML dics of
  2693. * class userportal-course-item.
  2694. * @param int User category id
  2695. * @param bool Whether to show the document quick-loader or not
  2696. * @return void
  2697. */
  2698. public static function display_courses_in_category($user_category_id, $load_dirs = false)
  2699. {
  2700. $user_id = api_get_user_id();
  2701. // Table definitions
  2702. $TABLECOURS = Database :: get_main_table(TABLE_MAIN_COURSE);
  2703. $TABLECOURSUSER = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  2704. $TABLE_ACCESS_URL_REL_COURSE = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  2705. $current_url_id = api_get_current_access_url_id();
  2706. // Get course list auto-register
  2707. $special_course_list = self::get_special_course_list();
  2708. $without_special_courses = '';
  2709. if (!empty($special_course_list)) {
  2710. $without_special_courses = ' AND course.code NOT IN ("'.implode('","',$special_course_list).'")';
  2711. }
  2712. //AND course_rel_user.relation_type<>".COURSE_RELATION_TYPE_RRHH."
  2713. $sql = "SELECT course.id,
  2714. course.title,
  2715. course.code,
  2716. course.subscribe subscr,
  2717. course.unsubscribe unsubscr,
  2718. course_rel_user.status status,
  2719. course_rel_user.sort sort,
  2720. course_rel_user.user_course_cat user_course_cat
  2721. FROM $TABLECOURS course,
  2722. $TABLECOURSUSER course_rel_user, ".$TABLE_ACCESS_URL_REL_COURSE." url
  2723. WHERE course.code = course_rel_user.course_code AND
  2724. url.c_id = course.id AND
  2725. course_rel_user.user_id = '".$user_id."' AND
  2726. course_rel_user.user_course_cat='".$user_category_id."' $without_special_courses ";
  2727. // If multiple URL access mode is enabled, only fetch courses
  2728. // corresponding to the current URL.
  2729. if (api_get_multiple_access_url() && $current_url_id != -1) {
  2730. $sql .= " AND url.course_code=course.code AND access_url_id='".$current_url_id."'";
  2731. }
  2732. // Use user's classification for courses (if any).
  2733. $sql .= " ORDER BY course_rel_user.user_course_cat, course_rel_user.sort ASC";
  2734. $result = Database::query($sql);
  2735. $status_icon = '';
  2736. $html = '';
  2737. $course_list = array();
  2738. // Browse through all courses.
  2739. while ($course = Database::fetch_array($result)) {
  2740. $course_info = api_get_course_info($course['code']);
  2741. //$course['id_session'] = null;
  2742. $course_info['id_session'] = null;
  2743. $course_info['status'] = $course['status'];
  2744. //In order to avoid doubles
  2745. if (in_array($course_info['real_id'], $course_list)) {
  2746. continue;
  2747. } else {
  2748. $course_list[] = $course_info['real_id'];
  2749. }
  2750. // For each course, get if there is any notification icon to show
  2751. // (something that would have changed since the user's last visit).
  2752. $show_notification = Display :: show_notification($course_info);
  2753. // New code displaying the user's status in respect to this course.
  2754. $status_icon = Display::return_icon('blackboard.png', $course_info['title'], array(), ICON_SIZE_LARGE);
  2755. $params = array();
  2756. $params['right_actions'] = '';
  2757. if (api_is_platform_admin()) {
  2758. if ($load_dirs) {
  2759. $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>';
  2760. $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>';
  2761. $params['right_actions'] .= Display::div('', array('id' => 'document_result_'.$course_info['real_id'].'_0', 'class'=>'document_preview_container'));
  2762. } else {
  2763. $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>';
  2764. }
  2765. if ($course_info['status'] == COURSEMANAGER) {
  2766. //echo Display::return_icon('teachers.gif', get_lang('Status').': '.get_lang('Teacher'), array('style'=>'width: 11px; height: 11px;'));
  2767. }
  2768. } else {
  2769. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED) {
  2770. if ($load_dirs) {
  2771. $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>';
  2772. $params['right_actions'] .= Display::div('', array('id' => 'document_result_'.$course_info['real_id'].'_0', 'class'=>'document_preview_container'));
  2773. } else {
  2774. if ($course_info['status'] == COURSEMANAGER) {
  2775. $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>';
  2776. }
  2777. }
  2778. }
  2779. }
  2780. $course_title = $course_info['title'];
  2781. $course_title_url = '';
  2782. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED || $course['status'] == COURSEMANAGER) {
  2783. $course_title_url = api_get_path(WEB_COURSE_PATH).$course_info['path'].'/index.php?id_session=0';
  2784. $course_title = Display::url($course_info['title'], $course_title_url);
  2785. } else {
  2786. $course_title = $course_info['title']." ".Display::tag('span',get_lang('CourseClosed'), array('class'=>'item_closed'));
  2787. }
  2788. // Start displaying the course block itself
  2789. if (api_get_setting('display_coursecode_in_courselist') == 'true') {
  2790. $course_title .= ' ('.$course_info['visual_code'].') ';
  2791. }
  2792. if (api_get_setting('display_teacher_in_courselist') == 'true') {
  2793. $teachers = CourseManager::get_teacher_list_from_course_code_to_string($course['real_id'], self::USER_SEPARATOR, true);
  2794. }
  2795. $params['link'] = $course_title_url;
  2796. $params['icon'] = $status_icon;
  2797. $params['title'] = $course_title;
  2798. $params['teachers'] = $teachers;
  2799. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED) {
  2800. $params['notifications'] = $show_notification;
  2801. }
  2802. $is_subcontent = true;
  2803. if (empty($user_category_id)) {
  2804. $is_subcontent = false;
  2805. }
  2806. $html .= self::course_item_html($params, $is_subcontent);
  2807. }
  2808. return $html;
  2809. }
  2810. /**
  2811. * Retrieves the user defined course categories
  2812. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2813. * @return array containing all the titles of the user defined courses with the id as key of the array
  2814. */
  2815. function get_user_course_categories()
  2816. {
  2817. $output = array();
  2818. $table_category = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
  2819. $sql = "SELECT * FROM ".$table_category." WHERE user_id='".Database::escape_string(api_get_user_id())."'";
  2820. $result = Database::query($sql);
  2821. while ($row = Database::fetch_array($result)) {
  2822. $output[$row['id']] = $row['title'];
  2823. }
  2824. return $output;
  2825. }
  2826. /**
  2827. * Get the course id based on the original id and field name in the extra fields. Returns 0 if course was not found
  2828. *
  2829. * @param string Original course id
  2830. * @param string Original field name
  2831. * @return int Course id
  2832. */
  2833. public static function get_course_id_from_original_id($original_course_id_value, $original_course_id_name)
  2834. {
  2835. $t_cfv = Database::get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
  2836. $table_field = Database::get_main_table(TABLE_MAIN_COURSE_FIELD);
  2837. $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
  2838. $sql_course = "SELECT c.id FROM $table_field cf INNER JOIN $t_cfv cfv ON cfv.field_id = cf.id
  2839. INNER JOIN $courseTable as c on c.code = cfv.course_code
  2840. WHERE field_variable='$original_course_id_name' AND field_value='$original_course_id_value'";
  2841. $res = Database::query($sql_course);
  2842. $row = Database::fetch_object($res);
  2843. if ($row != false) {
  2844. return $row->id;
  2845. } else {
  2846. return 0;
  2847. }
  2848. }
  2849. /**
  2850. * Display code for one specific course a logged in user is subscribed to.
  2851. * Shows a link to the course, what's new icons...
  2852. *
  2853. * $my_course['d'] - course directory
  2854. * $my_course['i'] - course title
  2855. * $my_course['c'] - visual course code
  2856. * $my_course['k'] - system course code
  2857. *
  2858. * @param array Course details
  2859. * @param integer Session ID
  2860. * @param string CSS class to apply to course entry
  2861. * @param boolean Whether the session is supposedly accessible now (not in the case it has passed and is in invisible/unaccessible mode)
  2862. * @param bool Whether to show the document quick-loader or not
  2863. * @return string The HTML to be printed for the course entry
  2864. *
  2865. * @version 1.0.3
  2866. * @todo refactor into different functions for database calls | logic | display
  2867. * @todo replace single-character $my_course['d'] indices
  2868. * @todo move code for what's new icons to a separate function to clear things up
  2869. * @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.
  2870. */
  2871. public static function get_logged_user_course_html($course, $session_id = 0, $load_dirs = false)
  2872. {
  2873. $course_info = api_get_course_info_by_id($course['id']);
  2874. $course_info['id_session'] = $session_id;
  2875. // Display course entry.
  2876. // Show a link to the course, unless the course is closed and user is not course admin.
  2877. $session_url = '';
  2878. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED || $course_info['user_status_in_course'] == COURSEMANAGER) {
  2879. $session_url = api_get_path(WEB_COURSE_PATH).$course_info['path'].'/index.php?id_session='.$course_info['id_session'];
  2880. $session_title = '<a href="'.api_get_path(WEB_COURSE_PATH).$course_info['path'].'/index.php?id_session='.$course_info['id_session'].'">'.$course_info['name'].'</a>';
  2881. } else {
  2882. $session_title = $course_info['name'].' '.Display::tag('span',get_lang('CourseClosed'), array('class'=>'item_closed'));
  2883. }
  2884. $params = array();
  2885. $params['icon'] = Display::return_icon('blackboard_blue.png', $course_info['name'], array(), ICON_SIZE_LARGE);
  2886. $params['link'] = $session_url;
  2887. $params['title'] = $session_title;
  2888. $params['right_actions'] = '';
  2889. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED) {
  2890. if ($load_dirs) {
  2891. $params['right_actions'] .= '<a id="document_preview_'.$course_info['real_id'].'_'.$course_info['id_session'].'" class="document_preview" href="javascript:void(0);">'.
  2892. Display::return_icon('folder.png', get_lang('Documents'), array('align' => 'absmiddle'),ICON_SIZE_SMALL).'</a>';
  2893. $params['right_actions'] .= Display::div('', array('id' => 'document_result_'.$course_info['real_id'].'_'.$course_info['id_session'], 'class'=>'document_preview_container'));
  2894. }
  2895. }
  2896. if (api_get_setting('display_coursecode_in_courselist') == 'true') {
  2897. $session_title .= ' ('.$course_info['visual_code'].') ';
  2898. }
  2899. if (api_get_setting('display_teacher_in_courselist') == 'true') {
  2900. $teacher_list = CourseManager::get_teacher_list_from_course_code_to_string($course_info['real_id'], self::USER_SEPARATOR, true);
  2901. $course_coachs = CourseManager::get_coachs_from_course_to_string($course_info['id_session'], $course_info['real_id'], self::USER_SEPARATOR, true);
  2902. $params['teachers'] = $teacher_list;
  2903. $params['coaches'] = $course_coachs;
  2904. }
  2905. $session_title .= isset($course['special_course']) ? ' '.Display::return_icon('klipper.png', get_lang('CourseAutoRegister')) : '';
  2906. // Display the "what's new" icons
  2907. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED) {
  2908. $session_title .= Display :: show_notification($course_info);
  2909. }
  2910. $params['title'] = $session_title;
  2911. $params['extra'] = '';
  2912. $html = self::course_item_html($params, true);
  2913. return $html;
  2914. }
  2915. /**
  2916. *
  2917. * @param string source course code
  2918. * @param int source session id
  2919. * @param string destination course code
  2920. * @param int destination session id
  2921. * @return bool
  2922. */
  2923. public static function copy_course($source_course_code, $source_session_id, $destination_course_code, $destination_session_id, $params = array()) {
  2924. require_once api_get_path(SYS_CODE_PATH).'coursecopy/classes/CourseBuilder.class.php';
  2925. require_once api_get_path(SYS_CODE_PATH).'coursecopy/classes/CourseRestorer.class.php';
  2926. require_once api_get_path(SYS_CODE_PATH).'coursecopy/classes/CourseSelectForm.class.php';
  2927. $course_info = api_get_course_info($source_course_code);
  2928. if (!empty($course_info)) {
  2929. $cb = new CourseBuilder('', $course_info);
  2930. $course = $cb->build($source_session_id, $source_course_code, true);
  2931. $course_restorer = new CourseRestorer($course);
  2932. $course_restorer->skip_content = $params;
  2933. $course_restorer->restore($destination_course_code, $destination_session_id, true, true);
  2934. return true;
  2935. }
  2936. return false;
  2937. }
  2938. /**
  2939. * A simpler version of the copy_course, the function creates an empty course with an autogenerated course code
  2940. *
  2941. * @param string new course title
  2942. * @param string source course code
  2943. * @param int source session id
  2944. * @param int destination session id
  2945. * @param bool new copied tools (Exercises and LPs)will be set to invisible by default?
  2946. *
  2947. * @return array
  2948. */
  2949. public static function copy_course_simple($new_title, $source_course_code, $source_session_id = 0, $destination_session_id = 0, $params = array())
  2950. {
  2951. $source_course_info = api_get_course_info($source_course_code);
  2952. if (!empty($source_course_info)) {
  2953. $new_course_code = self::generate_nice_next_course_code($source_course_code);
  2954. if ($new_course_code) {
  2955. $new_course_info = self::create_course($new_title, $new_course_code, false);
  2956. if (!empty($new_course_info['code'])) {
  2957. $result = self::copy_course($source_course_code, $source_session_id, $new_course_info['code'], $destination_session_id, $params);
  2958. if ($result) {
  2959. return $new_course_info;
  2960. }
  2961. }
  2962. }
  2963. }
  2964. return false;
  2965. }
  2966. /**
  2967. * Creates a new course code based in a given code
  2968. *
  2969. * @param string wanted code
  2970. * <code> $wanted_code = 'curse' if there are in the DB codes like curse1 curse2 the function will return: course3</code>
  2971. * if the course code doest not exist in the DB the same course code will be returned
  2972. * @return string wanted unused code
  2973. */
  2974. public static function generate_nice_next_course_code($wanted_code)
  2975. {
  2976. $course_code_ok = !self::course_code_exists($wanted_code);
  2977. if (!$course_code_ok) {
  2978. $wanted_code = self::generate_course_code($wanted_code);
  2979. $table = Database::get_main_table(TABLE_MAIN_COURSE);
  2980. $wanted_code = Database::escape_string($wanted_code);
  2981. $sql = "SELECT count(*) as count FROM $table WHERE code LIKE '$wanted_code%'";
  2982. $result = Database::query($sql);
  2983. if (Database::num_rows($result) > 0 ) {
  2984. $row = Database::fetch_array($result);
  2985. $count = $row['count'] + 1;
  2986. $wanted_code = $wanted_code.'_'.$count;
  2987. $result = api_get_course_info($wanted_code);
  2988. if (empty($result)) {
  2989. return $wanted_code;
  2990. }
  2991. }
  2992. return false;
  2993. }
  2994. return $wanted_code;
  2995. }
  2996. /**
  2997. * Gets the status of the users agreement in a course course-session
  2998. *
  2999. * @param int user id
  3000. * @param string course code
  3001. * @param int session id
  3002. * @return boolean
  3003. */
  3004. public static function is_user_accepted_legal($user_id, $courseInfo, $session_id = null)
  3005. {
  3006. $user_id = intval($user_id);
  3007. $course_code = $courseInfo['code'];
  3008. $course_id = $courseInfo['real_id'];
  3009. $course_code = Database::escape_string($course_code);
  3010. $session_id = intval($session_id);
  3011. if (empty($session_id)) {
  3012. $table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  3013. $sql = "SELECT legal_agreement FROM $table
  3014. WHERE user_id = $user_id AND c_id = '$course_id' ";
  3015. $result = Database::query($sql);
  3016. if (Database::num_rows($result) > 0 ) {
  3017. $result = Database::fetch_array($result);
  3018. if ($result['legal_agreement'] == 1 ) {
  3019. return true;
  3020. }
  3021. }
  3022. return false;
  3023. } else {
  3024. $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3025. $sql = "SELECT legal_agreement FROM $table
  3026. WHERE id_user = $user_id AND c_id ='$course_id' AND id_session = $session_id";
  3027. $result = Database::query($sql);
  3028. if (Database::num_rows($result) > 0 ) {
  3029. $result = Database::fetch_array($result);
  3030. if ($result['legal_agreement'] == 1 ) {
  3031. return true;
  3032. }
  3033. }
  3034. return false;
  3035. }
  3036. return false;
  3037. }
  3038. /**
  3039. * Saves the user-course legal agreement
  3040. * @param int user id
  3041. * @param string course code
  3042. * @param int session id
  3043. */
  3044. function save_user_legal($user_id, $courseInfo, $session_id = null)
  3045. {
  3046. $user_id = intval($user_id);
  3047. $course_code = $courseInfo['code'];
  3048. $course_id = $courseInfo['real_id'];
  3049. $course_code = Database::escape_string($course_code);
  3050. $session_id = intval($session_id);
  3051. if (empty($session_id)) {
  3052. $table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  3053. $sql = "UPDATE $table SET legal_agreement = '1'
  3054. WHERE user_id = $user_id AND c_id ='$course_id' ";
  3055. $result = Database::query($sql);
  3056. } else {
  3057. $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3058. $sql = "UPDATE $table SET legal_agreement = '1'
  3059. WHERE id_user = $user_id AND c_id = '$course_id' AND id_session = $session_id";
  3060. $result = Database::query($sql);
  3061. }
  3062. }
  3063. public static function get_user_course_vote($user_id, $course_id, $session_id = null, $url_id = null) {
  3064. $table_user_course_vote = Database::get_main_table(TABLE_MAIN_USER_REL_COURSE_VOTE);
  3065. $session_id = !isset($session_id) ? api_get_session_id() : intval($session_id);
  3066. $url_id = empty($url_id) ? api_get_current_access_url_id() : intval($url_id);
  3067. $user_id = intval($user_id);
  3068. if (empty($user_id)) {
  3069. return false;
  3070. }
  3071. $params = array(
  3072. 'user_id' => $user_id,
  3073. 'c_id' => $course_id,
  3074. 'session_id' => $session_id,
  3075. 'url_id' => $url_id
  3076. );
  3077. $result = Database::select('vote', $table_user_course_vote, array('where' => array('user_id = ? AND c_id = ? AND session_id = ? AND url_id = ?' => $params)), 'first');
  3078. if (!empty($result)) {
  3079. return $result['vote'];
  3080. }
  3081. return false;
  3082. }
  3083. public static function get_course_ranking($course_id, $session_id = null, $url_id = null) {
  3084. $table_course_ranking = Database::get_main_table(TABLE_STATISTIC_TRACK_COURSE_RANKING);
  3085. $session_id = !isset($session_id) ? api_get_session_id() : intval($session_id);
  3086. $url_id = empty($url_id) ? api_get_current_access_url_id() : intval($url_id);
  3087. $params = array(
  3088. 'c_id' => $course_id,
  3089. 'session_id' => $session_id,
  3090. 'url_id' => $url_id
  3091. );
  3092. $result = Database::select('c_id, accesses, total_score, users', $table_course_ranking, array('where' => array('c_id = ? AND session_id = ? AND url_id = ?' => $params)), 'first');
  3093. $point_average_in_percentage = 0;
  3094. $point_average_in_star = 0;
  3095. $users_who_voted = 0;
  3096. if (!empty($result['users'])) {
  3097. $users_who_voted = $result['users'];
  3098. $point_average_in_percentage = round($result['total_score']/$result['users'] * 100 / 5, 2);
  3099. $point_average_in_star = round($result['total_score']/$result['users'], 1);
  3100. }
  3101. $result['user_vote'] = false;
  3102. if (!api_is_anonymous()) {
  3103. $result['user_vote'] = self::get_user_course_vote(api_get_user_id(), $course_id, $session_id,$url_id);
  3104. }
  3105. $result['point_average'] = $point_average_in_percentage;
  3106. $result['point_average_star'] = $point_average_in_star;
  3107. $result['users_who_voted'] = $users_who_voted;
  3108. return $result;
  3109. }
  3110. /**
  3111. *
  3112. * Updates the course ranking
  3113. * @param int course id
  3114. * @param int session id
  3115. * @param id url id
  3116. *
  3117. **/
  3118. public static function update_course_ranking($course_id = null, $session_id = null, $url_id = null, $points_to_add = null, $add_access = true, $add_user = true)
  3119. {
  3120. //Course catalog stats modifications see #4191
  3121. $table_course_ranking = Database::get_main_table(TABLE_STATISTIC_TRACK_COURSE_RANKING);
  3122. $now = api_get_utc_datetime();
  3123. $course_id = empty($course_id) ? api_get_course_int_id() : intval($course_id);
  3124. $session_id = !isset($session_id) ? api_get_session_id() : intval($session_id);
  3125. $url_id = empty($url_id) ? api_get_current_access_url_id() : intval($url_id);
  3126. $params = array(
  3127. 'c_id' => $course_id,
  3128. 'session_id' => $session_id,
  3129. 'url_id' => $url_id,
  3130. 'creation_date' => $now,
  3131. );
  3132. $result = Database::select('id, accesses, total_score, users', $table_course_ranking, array('where' => array('c_id = ? AND session_id = ? AND url_id = ?' => $params)), 'first');
  3133. // Problem here every thime we load the courses/XXXX/index.php course home page we update the access
  3134. if (empty($result)) {
  3135. if ($add_access) {
  3136. $params['accesses'] = 1;
  3137. }
  3138. //The votes and users are empty
  3139. if (isset($points_to_add) && !empty($points_to_add)) {
  3140. $params['total_score'] = intval($points_to_add);
  3141. }
  3142. if ($add_user) {
  3143. $params['users'] = 1;
  3144. }
  3145. $result = Database::insert($table_course_ranking, $params);
  3146. } else {
  3147. $my_params = array();
  3148. if ($add_access) {
  3149. $my_params['accesses'] = intval($result['accesses']) + 1;
  3150. }
  3151. if (isset($points_to_add) && !empty($points_to_add)) {
  3152. $my_params['total_score'] = $result['total_score'] + $points_to_add;
  3153. }
  3154. if ($add_user) {
  3155. $my_params['users'] = $result['users'] + 1;
  3156. }
  3157. if (!empty($my_params)) {
  3158. $result = Database::update($table_course_ranking, $my_params, array('c_id = ? AND session_id = ? AND url_id = ?' => $params));
  3159. }
  3160. }
  3161. return $result;
  3162. }
  3163. /**
  3164. * Add user vote to a course
  3165. *
  3166. * @param int user id
  3167. * @param int vote [1..5]
  3168. * @param int course id
  3169. * @param int session id
  3170. * @param int url id (access_url_id)
  3171. * @return mixed 'added', 'updated' or 'nothing'
  3172. *
  3173. */
  3174. public static function add_course_vote($user_id, $vote, $course_id, $session_id = null, $url_id = null)
  3175. {
  3176. $table_user_course_vote = Database::get_main_table(TABLE_MAIN_USER_REL_COURSE_VOTE);
  3177. $course_id = empty($course_id) ? api_get_course_int_id() : intval($course_id);
  3178. if (empty($course_id) || empty($user_id)) {
  3179. return false;
  3180. }
  3181. if (!in_array($vote, array(1,2,3,4,5))) {
  3182. return false;
  3183. }
  3184. $session_id = !isset($session_id) ? api_get_session_id() : intval($session_id);
  3185. $url_id = empty($url_id) ? api_get_current_access_url_id() : intval($url_id);
  3186. $vote = intval($vote);
  3187. $params = array(
  3188. 'user_id' => intval($user_id),
  3189. 'c_id' => $course_id,
  3190. 'session_id' => $session_id,
  3191. 'url_id' => $url_id,
  3192. 'vote' => $vote
  3193. );
  3194. $action_done = 'nothing';
  3195. $result = Database::select('id, vote', $table_user_course_vote, array('where' => array('user_id = ? AND c_id = ? AND session_id = ? AND url_id = ?' => $params)), 'first');
  3196. if (empty($result)) {
  3197. $result = Database::insert($table_user_course_vote, $params);
  3198. $points_to_add = $vote;
  3199. $add_user = true;
  3200. $action_done = 'added';
  3201. } else {
  3202. $my_params = array('vote' => $vote);
  3203. $points_to_add = $vote - $result['vote'];
  3204. $add_user = false;
  3205. $result = Database::update($table_user_course_vote, $my_params, array('user_id = ? AND c_id = ? AND session_id = ? AND url_id = ?' => $params));
  3206. $action_done = 'updated';
  3207. }
  3208. //Current points
  3209. if (!empty($points_to_add)) {
  3210. self::update_course_ranking($course_id, $session_id, $url_id, $points_to_add, false, $add_user);
  3211. }
  3212. return $action_done;
  3213. }
  3214. /**
  3215. * Remove course ranking + user votes
  3216. *
  3217. * @param int course id
  3218. * @param int session id
  3219. * @param int url id
  3220. *
  3221. */
  3222. public function remove_course_ranking($course_id, $session_id, $url_id = null) {
  3223. $table_course_ranking = Database::get_main_table(TABLE_STATISTIC_TRACK_COURSE_RANKING);
  3224. $table_user_course_vote = Database::get_main_table(TABLE_MAIN_USER_REL_COURSE_VOTE);
  3225. if (!empty($course_id) && isset($session_id)) {
  3226. $url_id = empty($url_id) ? api_get_current_access_url_id() : intval($url_id);
  3227. $params = array(
  3228. 'c_id' => $course_id,
  3229. 'session_id' => $session_id,
  3230. 'url_id' => $url_id,
  3231. );
  3232. Database::delete($table_course_ranking, array('c_id = ? AND session_id = ? AND url_id = ?' => $params));
  3233. Database::delete($table_user_course_vote, array('c_id = ? AND session_id = ? AND url_id = ?' => $params));
  3234. }
  3235. }
  3236. /**
  3237. * Returns an array with the hottest courses
  3238. * @param int number of days
  3239. * @param int number of hottest courses
  3240. */
  3241. public static function return_hot_courses($days = 30, $limit = 5)
  3242. {
  3243. $urlId = api_get_current_access_url_id();
  3244. $limit = intval($limit);
  3245. //Getting my courses
  3246. $my_course_list = CourseManager::get_courses_list_by_user_id(api_get_user_id());
  3247. $my_course_code_list = array();
  3248. foreach ($my_course_list as $course) {
  3249. $my_course_code_list[$course['real_id']] = $course['real_id'];
  3250. }
  3251. if (api_is_drh()) {
  3252. $courses = CourseManager::get_courses_followed_by_drh(api_get_user_id());
  3253. foreach ($courses as $course) {
  3254. $my_course_code_list[$course['real_id']] = $course['real_id'];
  3255. }
  3256. }
  3257. $table_course_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  3258. $table_course = Database::get_main_table(TABLE_MAIN_COURSE);
  3259. $table_course_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  3260. //@todo all dates in the tracking_course_access, last_access are in the DB time (NOW) not UTC
  3261. /*
  3262. $today = api_get_utc_datetime();
  3263. $today_diff = time() -intval($days)*24*60*60;
  3264. $today_diff = api_get_utc_datetime($today_diff);
  3265. * */
  3266. $sql = "SELECT COUNT(course_access_id) course_count, a.c_id, visibility ".
  3267. "FROM $table_course c INNER JOIN $table_course_access a ".
  3268. " ON (c.id = a.c_id) INNER JOIN $table_course_url u ON u.c_id = c.id ".
  3269. " WHERE u.access_url_id = ".$urlId." AND".
  3270. " login_course_date <= now() AND ".
  3271. " login_course_date > DATE_SUB(now(), INTERVAL $days DAY) AND".
  3272. " visibility <> '".COURSE_VISIBILITY_CLOSED."'".
  3273. " GROUP BY a.c_id".
  3274. " ORDER BY course_count DESC".
  3275. " LIMIT $limit";
  3276. $result = Database::query($sql);
  3277. $courses = array();
  3278. if (Database::num_rows($result)) {
  3279. $courses = Database::store_result($result, 'ASSOC');
  3280. $courses = self::process_hot_course_item($courses, $my_course_code_list);
  3281. }
  3282. return $courses;
  3283. }
  3284. public static function process_hot_course_item($courses, $my_course_code_list = array()) {
  3285. $ajax_url = api_get_path(WEB_AJAX_PATH).'course.ajax.php?a=add_course_vote';
  3286. foreach ($courses as &$my_course) {
  3287. $course_info = api_get_course_info_by_id($my_course['c_id']);
  3288. $my_course['extra_info'] = $course_info;
  3289. $my_course['extra_info']['go_to_course_button'] = '';
  3290. $my_course['extra_info']['register_button'] = '';
  3291. $access_link = self::get_access_link_by_user(api_get_user_id(), $course_info, $my_course_code_list);
  3292. //Course visibility
  3293. if ($access_link && in_array('register', $access_link)) {
  3294. $stok = Security::get_token();
  3295. $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'));
  3296. }
  3297. if ($access_link && in_array('enter', $access_link)) {
  3298. $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'));
  3299. }
  3300. //Description
  3301. $my_course['extra_info']['description_button'] = '';
  3302. if ($course_info['visibility'] == COURSE_VISIBILITY_OPEN_WORLD || in_array($course_info['real_id'], $my_course_code_list) ) {
  3303. $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'));
  3304. }
  3305. $my_course['extra_info']['teachers'] = CourseManager::get_teacher_list_from_course_code_to_string($course_info['real_id']);
  3306. $point_info = self::get_course_ranking($course_info['real_id'], 0);
  3307. $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);
  3308. }
  3309. return $courses;
  3310. }
  3311. public static function return_most_accessed_courses($limit = 5) {
  3312. $table_course_ranking = Database::get_main_table(TABLE_STATISTIC_TRACK_COURSE_RANKING);
  3313. $params['url_id'] = api_get_current_access_url_id();
  3314. $result = Database::select('c_id, accesses, total_score, users', $table_course_ranking, array('where' => array('url_id = ?' => $params), 'order' => 'accesses DESC', 'limit' => $limit), 'all', true);
  3315. return $result;
  3316. }
  3317. /**
  3318. *
  3319. * @return ResultSet
  3320. */
  3321. static function list_inactive_courses($ceiling, $visibility_level = COURSE_VISIBILITY_REGISTERED) {
  3322. $ceiling = is_numeric($ceiling) ? (int) $ceiling : strtotime($ceiling);
  3323. $ceiling = date('Y-m-d H:i:s', $ceiling);
  3324. $visibility_level = $visibility_level ? $visibility_level : '0';
  3325. $table_course = Database::get_main_table(TABLE_MAIN_COURSE);
  3326. $table_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
  3327. $sql = "SELECT
  3328. c.*,
  3329. cat.name AS category
  3330. FROM
  3331. $table_course AS c
  3332. LEFT JOIN
  3333. $table_category AS cat
  3334. ON
  3335. c.category_code = cat.code
  3336. WHERE
  3337. c.visibility >= $visibility_level AND
  3338. c.last_visit<='$ceiling'
  3339. ";
  3340. return ResultSet::create($sql);
  3341. }
  3342. /**
  3343. * Get courses count
  3344. * @param int Access URL ID (optional)
  3345. * @return int Number of courses
  3346. */
  3347. public static function count_courses($access_url_id = null)
  3348. {
  3349. $table_course = Database::get_main_table(TABLE_MAIN_COURSE);
  3350. $table_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  3351. $sql = "SELECT count(id) FROM $table_course c";
  3352. if (!empty($access_url_id) && $access_url_id == intval($access_url_id)) {
  3353. $sql .= ", $table_course_rel_access_url u WHERE c.id = u.c_id AND u.access_url_id = $access_url_id";
  3354. }
  3355. $res = Database::query($sql);
  3356. $row = Database::fetch_row($res);
  3357. return $row[0];
  3358. }
  3359. /**
  3360. * Return a link to go to the course, validating the visibility of the
  3361. * course and the user status
  3362. * @param int User ID
  3363. * @param array Course details array
  3364. * @param array List of courses to which the user is subscribed (if not provided, will be generated)
  3365. * @return mixed 'enter' for a link to go to the course or 'register' for a link to subscribe, or false if no access
  3366. */
  3367. static function get_access_link_by_user($uid, $course, $user_courses = array())
  3368. {
  3369. if (empty($uid) or empty($course)) { return false; }
  3370. if (empty($user_courses)) {
  3371. // get the array of courses to which the user is subscribed
  3372. $user_courses = CourseManager::get_courses_list_by_user_id($uid);
  3373. foreach ($user_courses as $k => $v) {
  3374. $user_courses[$k] = $v['real_id'];
  3375. }
  3376. }
  3377. if (!isset($course['real_id']) && empty($course['real_id'])) {
  3378. $course = api_get_course_info($course['code']);
  3379. }
  3380. $is_admin = api_is_platform_admin_by_id($uid);
  3381. $options = array();
  3382. // Register button
  3383. if (!api_is_anonymous($uid) &&
  3384. !$is_admin &&
  3385. (
  3386. ($course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD || $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM) ||
  3387. $course['visibility'] == COURSE_VISIBILITY_REGISTERED && $course['subscribe'] == SUBSCRIBE_ALLOWED
  3388. ) &&
  3389. $course['subscribe'] == SUBSCRIBE_ALLOWED &&
  3390. (!in_array($course['real_id'], $user_courses) || empty($user_courses))
  3391. ) {
  3392. $options[]= 'register';
  3393. }
  3394. // Go To Course button (only if admin, if course public or if student already subscribed)
  3395. if ($is_admin ||
  3396. $course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD && empty($course['registration_code']) ||
  3397. (api_user_is_login($uid) && $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM && empty($course['registration_code']) ) ||
  3398. (in_array($course['real_id'], $user_courses) && $course['visibility'] != COURSE_VISIBILITY_CLOSED)
  3399. ) {
  3400. $options[]= 'enter';
  3401. }
  3402. return $options;
  3403. }
  3404. // TODO: Such a function might be useful in other places too. It might be moved in the CourseManager class.
  3405. // Also, the function might be upgraded for avoiding code duplications.
  3406. static function generate_course_code($course_title, $encoding = null) {
  3407. if (empty($encoding)) {
  3408. $encoding = api_get_system_encoding();
  3409. }
  3410. return substr(preg_replace('/[^A-Z0-9]/', '', strtoupper(api_transliterate($course_title, 'X', $encoding))), 0, CourseManager::MAX_COURSE_LENGTH_CODE);
  3411. }
  3412. /**
  3413. * Defines the four needed keys to create a course based on several parameters.
  3414. * @param string The code you want for this course
  3415. * @param string Prefix added for ALL keys
  3416. * @param string Prefix added for databases only
  3417. * @param string Prefix added for paths only
  3418. * @param bool Add unique prefix
  3419. * @param bool Use code-independent keys
  3420. * @return array An array with the needed keys ['currentCourseCode'], ['currentCourseId'], ['currentCourseDbName'], ['currentCourseRepository']
  3421. * @todo Eliminate the global variables.
  3422. */
  3423. static function define_course_keys($wanted_code, $prefix_for_all = '', $prefix_for_base_name = '', $prefix_for_path = '', $add_unique_prefix = false, $use_code_indepedent_keys = true)
  3424. {
  3425. global $prefixAntiNumber, $_configuration;
  3426. $course_table = Database :: get_main_table(TABLE_MAIN_COURSE);
  3427. $wanted_code = self::generate_course_code($wanted_code);
  3428. $keys_course_code = $wanted_code;
  3429. if (!$use_code_indepedent_keys) {
  3430. $wanted_code = '';
  3431. }
  3432. if ($add_unique_prefix) {
  3433. $unique_prefix = substr(md5(uniqid(rand())), 0, 10);
  3434. } else {
  3435. $unique_prefix = '';
  3436. }
  3437. $keys = array();
  3438. $final_suffix = array('CourseId' => '', 'CourseDb' => '', 'CourseDir' => '');
  3439. $limit_numb_try = 100;
  3440. $keys_are_unique = false;
  3441. $try_new_fsc_id = $try_new_fsc_db = $try_new_fsc_dir = 0;
  3442. while (!$keys_are_unique) {
  3443. $keys_course_id = $prefix_for_all . $unique_prefix . $wanted_code . $final_suffix['CourseId'];
  3444. //$keys_course_db_name = $prefix_for_base_name . $unique_prefix . strtoupper($keys_course_id) . $final_suffix['CourseDb'];
  3445. $keys_course_repository = $prefix_for_path . $unique_prefix . $wanted_code . $final_suffix['CourseDir'];
  3446. $keys_are_unique = true;
  3447. // Check whether they are unique.
  3448. $query = "SELECT 1 FROM ".$course_table." WHERE code='".$keys_course_id."' LIMIT 0,1";
  3449. $result = Database::query($query);
  3450. //if ($keys_course_id == DEFAULT_COURSE || Database::num_rows($result)) {
  3451. if (Database::num_rows($result)) {
  3452. $keys_are_unique = false;
  3453. $try_new_fsc_id ++;
  3454. $final_suffix['CourseId'] = substr(md5(uniqid(rand())), 0, 4);
  3455. }
  3456. if (file_exists(api_get_path(SYS_COURSE_PATH).$keys_course_repository)) {
  3457. $keys_are_unique = false;
  3458. $try_new_fsc_dir ++;
  3459. $final_suffix['CourseDir'] = substr(md5(uniqid(rand())), 0, 4);
  3460. }
  3461. if (($try_new_fsc_id + $try_new_fsc_db + $try_new_fsc_dir) > $limit_numb_try) {
  3462. return $keys;
  3463. }
  3464. }
  3465. $keys['currentCourseCode'] = $keys_course_code;
  3466. $keys['currentCourseId'] = $keys_course_id;
  3467. $keys['currentCourseRepository'] = $keys_course_repository;
  3468. return $keys;
  3469. }
  3470. /**
  3471. * Initializes a file repository for a newly created course.
  3472. */
  3473. static function prepare_course_repository($course_repository, $course_code)
  3474. {
  3475. $perm = api_get_permissions_for_new_directories();
  3476. $perm_file = api_get_permissions_for_new_files();
  3477. $htmlpage = "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <title>Not authorized</title>\n </head>\n <body>\n </body>\n</html>";
  3478. $cp = api_get_path(SYS_COURSE_PATH).$course_repository;
  3479. //Creating document folder
  3480. mkdir($cp, $perm);
  3481. mkdir($cp . '/document', $perm);
  3482. $cpt = $cp.'/document/index.html';
  3483. $fd = fopen($cpt, 'w');
  3484. fwrite($fd, $htmlpage);
  3485. fclose($fd);
  3486. /*
  3487. @chmod($cpt, $perm_file);
  3488. @copy($cpt, $cp . '/document/index.html');
  3489. mkdir($cp . '/document/images', $perm);
  3490. @copy($cpt, $cp . '/document/images/index.html');
  3491. mkdir($cp . '/document/images/gallery/', $perm);
  3492. @copy($cpt, $cp . '/document/images/gallery/index.html');
  3493. mkdir($cp . '/document/shared_folder/', $perm);
  3494. @copy($cpt, $cp . '/document/shared_folder/index.html');
  3495. mkdir($cp . '/document/audio', $perm);
  3496. @copy($cpt, $cp . '/document/audio/index.html');
  3497. mkdir($cp . '/document/flash', $perm);
  3498. @copy($cpt, $cp . '/document/flash/index.html');
  3499. mkdir($cp . '/document/video', $perm);
  3500. @copy($cpt, $cp . '/document/video/index.html'); */
  3501. // Creating dropbox folder
  3502. mkdir($cp . '/dropbox', $perm);
  3503. $cpt = $cp.'/dropbox/index.html';
  3504. $fd = fopen($cpt, 'w');
  3505. fwrite($fd, $htmlpage);
  3506. fclose($fd);
  3507. @chmod($cpt, $perm_file);
  3508. mkdir($cp . '/group', $perm);
  3509. @copy($cpt, $cp . '/group/index.html');
  3510. mkdir($cp . '/page', $perm);
  3511. @copy($cpt, $cp . '/page/index.html');
  3512. mkdir($cp . '/scorm', $perm);
  3513. @copy($cpt, $cp . '/scorm/index.html');
  3514. mkdir($cp . '/upload', $perm);
  3515. @copy($cpt, $cp . '/upload/index.html');
  3516. mkdir($cp . '/upload/forum', $perm);
  3517. @copy($cpt, $cp . '/upload/forum/index.html');
  3518. mkdir($cp . '/upload/forum/images', $perm);
  3519. @copy($cpt, $cp . '/upload/forum/images/index.html');
  3520. mkdir($cp . '/upload/test', $perm);
  3521. @copy($cpt, $cp . '/upload/test/index.html');
  3522. mkdir($cp . '/upload/blog', $perm);
  3523. @copy($cpt, $cp . '/upload/blog/index.html');
  3524. mkdir($cp . '/upload/learning_path', $perm);
  3525. @copy($cpt, $cp . '/upload/learning_path/index.html');
  3526. mkdir($cp . '/upload/learning_path/images', $perm);
  3527. @copy($cpt, $cp . '/upload/learning_path/images/index.html');
  3528. mkdir($cp . '/upload/calendar', $perm);
  3529. @copy($cpt, $cp . '/upload/calendar/index.html');
  3530. mkdir($cp . '/upload/calendar/images', $perm);
  3531. @copy($cpt, $cp . '/upload/calendar/images/index.html');
  3532. mkdir($cp . '/work', $perm);
  3533. @copy($cpt, $cp . '/work/index.html');
  3534. mkdir($cp . '/upload/announcements', $perm);
  3535. @copy($cpt, $cp . '/upload/announcements/index.html');
  3536. mkdir($cp . '/upload/announcements/images', $perm);
  3537. @copy($cpt, $cp . '/upload/announcements/images/index.html');
  3538. //Oral expression question type
  3539. mkdir($cp . '/exercises', $perm);
  3540. @copy($cpt, $cp . '/exercises/index.html');
  3541. // Create .htaccess in the dropbox directory.
  3542. $fp = fopen($cp . '/dropbox/.htaccess', 'w');
  3543. fwrite($fp, "AuthName AllowLocalAccess
  3544. AuthType Basic
  3545. order deny,allow
  3546. deny from all
  3547. php_flag zlib.output_compression off");
  3548. fclose($fp);
  3549. return 0;
  3550. }
  3551. /**
  3552. * Get current courses
  3553. * */
  3554. static function get_course_tables()
  3555. {
  3556. $tables = array();
  3557. $tables[]= 'tool';
  3558. $tables[]= 'tool_intro';
  3559. $tables[]= 'group_info';
  3560. $tables[]= 'group_category';
  3561. $tables[]= 'group_rel_user';
  3562. $tables[]= 'group_rel_tutor';
  3563. $tables[]= 'item_property';
  3564. $tables[]= 'userinfo_content';
  3565. $tables[]= 'userinfo_def';
  3566. $tables[]= 'course_description';
  3567. $tables[]= 'calendar_event';
  3568. $tables[]= 'calendar_event_repeat';
  3569. $tables[]= 'calendar_event_repeat_not';
  3570. $tables[]= 'calendar_event_attachment';
  3571. $tables[]= 'announcement';
  3572. $tables[]= 'announcement_attachment';
  3573. $tables[]= 'resource';
  3574. $tables[]= 'student_publication';
  3575. $tables[]= 'student_publication_assignment';
  3576. $tables[]= 'document';
  3577. $tables[]= 'forum_category';
  3578. $tables[]= 'forum_forum';
  3579. $tables[]= 'forum_thread';
  3580. $tables[]= 'forum_post';
  3581. $tables[]= 'forum_mailcue';
  3582. $tables[]= 'forum_attachment';
  3583. $tables[]= 'forum_notification';
  3584. $tables[]= 'forum_thread_qualify';
  3585. $tables[]= 'forum_thread_qualify_log';
  3586. $tables[]= 'link';
  3587. $tables[]= 'link_category';
  3588. $tables[]= 'online_connected';
  3589. $tables[]= 'online_link';
  3590. $tables[]= 'chat_connected';
  3591. $tables[]= 'quiz';
  3592. $tables[]= 'quiz_rel_question';
  3593. $tables[]= 'quiz_question';
  3594. $tables[]= 'quiz_answer';
  3595. $tables[]= 'quiz_question_option';
  3596. $tables[]= 'quiz_category';
  3597. $tables[]= 'quiz_question_rel_category';
  3598. $tables[]= 'dropbox_post';
  3599. $tables[]= 'dropbox_file';
  3600. $tables[]= 'dropbox_person';
  3601. $tables[]= 'dropbox_category';
  3602. $tables[]= 'dropbox_feedback';
  3603. $tables[]= 'lp';
  3604. $tables[]= 'lp_item';
  3605. $tables[]= 'lp_view';
  3606. $tables[]= 'lp_item_view';
  3607. $tables[]= 'lp_iv_interaction';
  3608. $tables[]= 'lp_iv_objective';
  3609. $tables[]= 'blog';
  3610. $tables[]= 'blog_comment';
  3611. $tables[]= 'blog_post';
  3612. $tables[]= 'blog_rating';
  3613. $tables[]= 'blog_rel_user';
  3614. $tables[]= 'blog_task';
  3615. $tables[]= 'blog_task_rel_user';
  3616. $tables[]= 'blog_attachment';
  3617. $tables[]= 'permission_group';
  3618. $tables[]= 'permission_user';
  3619. $tables[]= 'permission_task';
  3620. $tables[]= 'role';
  3621. $tables[]= 'role_group';
  3622. $tables[]= 'role_permissions';
  3623. $tables[]= 'role_user';
  3624. $tables[]= 'survey';
  3625. $tables[]= 'survey_question';
  3626. $tables[]= 'survey_question_option';
  3627. $tables[]= 'survey_invitation';
  3628. $tables[]= 'survey_answer';
  3629. $tables[]= 'survey_group';
  3630. $tables[]= 'wiki';
  3631. $tables[]= 'wiki_conf';
  3632. $tables[]= 'wiki_discuss';
  3633. $tables[]= 'wiki_mailcue';
  3634. $tables[]= 'course_setting';
  3635. $tables[]= 'glossary';
  3636. $tables[]= 'notebook';
  3637. $tables[]= 'attendance';
  3638. $tables[]= 'attendance_sheet';
  3639. $tables[]= 'attendance_calendar';
  3640. $tables[]= 'attendance_result';
  3641. $tables[]= 'attendance_sheet_log';
  3642. $tables[]= 'thematic';
  3643. $tables[]= 'thematic_plan';
  3644. $tables[]= 'thematic_advance';
  3645. $tables[]= 'metadata';
  3646. return $tables;
  3647. }
  3648. static function browse_folders($path, $files, $media)
  3649. {
  3650. $defaultCourseDocumentPath = api_get_path(SYS_DEFAULT_COURSE_DOCUMENT_PATH);
  3651. if ($media == 'images') {
  3652. $code_path = $defaultCourseDocumentPath.'images/';
  3653. }
  3654. if ($media == 'audio') {
  3655. $code_path = $defaultCourseDocumentPath.'audio/';
  3656. }
  3657. if ($media == 'flash') {
  3658. $code_path = $defaultCourseDocumentPath.'flash/';
  3659. }
  3660. if ($media == 'video') {
  3661. $code_path = $defaultCourseDocumentPath.'video/';
  3662. }
  3663. if ($media == 'certificates') {
  3664. $code_path = $defaultCourseDocumentPath.'certificates/';
  3665. }
  3666. if (is_dir($path)) {
  3667. $handle = opendir($path);
  3668. while (false !== ($file = readdir($handle))) {
  3669. if (is_dir($path.$file) && strpos($file, '.') !== 0) {
  3670. $files[]['dir'] = str_replace($code_path, '', $path.$file.'/');
  3671. $files = self::browse_folders($path.$file.'/', $files, $media);
  3672. } elseif (is_file($path.$file) && strpos($file, '.') !== 0) {
  3673. $files[]['file'] = str_replace($code_path, '', $path.$file);
  3674. }
  3675. }
  3676. }
  3677. return $files;
  3678. }
  3679. /**
  3680. * @param $files
  3681. * @param $type
  3682. * @return array
  3683. */
  3684. static function sort_pictures($files, $type)
  3685. {
  3686. $pictures = array();
  3687. foreach ($files as $key => $value){
  3688. if (isset($value[$type]) && !empty($value[$type])) {
  3689. $pictures[][$type] = $value[$type];
  3690. }
  3691. }
  3692. return $pictures;
  3693. }
  3694. /**
  3695. * Fills the course database with some required content and example content.
  3696. * @version 1.2
  3697. */
  3698. static function fill_db_course($course_id, $course_repository, $language, $fill_with_exemplary_content = null)
  3699. {
  3700. if (is_null($fill_with_exemplary_content)) {
  3701. $fill_with_exemplary_content = api_get_setting('example_material_course_creation') != 'false';
  3702. }
  3703. $course_id = intval($course_id);
  3704. if (empty($course_id)) {
  3705. return false;
  3706. }
  3707. $now = api_get_utc_datetime(time());
  3708. $tbl_course_homepage = Database::get_course_table(TABLE_TOOL_LIST);
  3709. $TABLEINTROS = Database::get_course_table(TABLE_TOOL_INTRO);
  3710. $TABLEGROUPCATEGORIES = Database::get_course_table(TABLE_GROUP_CATEGORY);
  3711. $TABLEITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
  3712. $TABLETOOLAGENDA = Database::get_course_table(TABLE_AGENDA);
  3713. $TABLETOOLANNOUNCEMENTS = Database::get_course_table(TABLE_ANNOUNCEMENT);
  3714. $TABLETOOLDOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  3715. $TABLETOOLLINK = Database::get_course_table(TABLE_LINK);
  3716. $TABLEQUIZ = Database::get_course_table(TABLE_QUIZ_TEST);
  3717. $TABLEQUIZQUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  3718. $TABLEQUIZQUESTIONLIST = Database::get_course_table(TABLE_QUIZ_QUESTION);
  3719. $TABLEQUIZANSWERSLIST = Database::get_course_table(TABLE_QUIZ_ANSWER);
  3720. $TABLESETTING = Database::get_course_table(TABLE_COURSE_SETTING);
  3721. $TABLEFORUMCATEGORIES = Database::get_course_table(TABLE_FORUM_CATEGORY);
  3722. $TABLEFORUMS = Database::get_course_table(TABLE_FORUM);
  3723. $TABLEFORUMTHREADS = Database::get_course_table(TABLE_FORUM_THREAD);
  3724. $TABLEFORUMPOSTS = Database::get_course_table(TABLE_FORUM_POST);
  3725. $TABLEGRADEBOOK = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  3726. $TABLEGRADEBOOKLINK = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
  3727. $TABLEGRADEBOOKCERT = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
  3728. include api_get_path(SYS_CODE_PATH).'lang/english/create_course.inc.php';
  3729. $file_to_include = api_get_path(SYS_CODE_PATH).'lang/'.$language.'/create_course.inc.php';
  3730. if (file_exists($file_to_include)) {
  3731. include $file_to_include;
  3732. }
  3733. $visible_for_all = 1;
  3734. $visible_for_course_admin = 0;
  3735. $visible_for_platform_admin = 2;
  3736. /* Course tools */
  3737. Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_COURSE_DESCRIPTION . "','course_description/','info.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'course_description')) . "','0','squaregrey.gif','NO','_self','authoring','0')");
  3738. Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_CALENDAR_EVENT . "','calendar/agenda.php','agenda.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'agenda')) . "','0','squaregrey.gif','NO','_self','interaction','0')");
  3739. Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_DOCUMENT . "','document/document.php','folder_document.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'documents')) . "','0','squaregrey.gif','NO','_self','authoring','0')");
  3740. Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_LEARNPATH . "','newscorm/lp_controller.php','scorms.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'learning_path')) . "','0','squaregrey.gif','NO','_self','authoring','0')");
  3741. Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_LINK . "','link/link.php','links.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'links')) . "','0','squaregrey.gif','NO','_self','authoring','0')");
  3742. Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_QUIZ . "','exercice/exercice.php','quiz.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'quiz')) . "','0','squaregrey.gif','NO','_self','authoring','0')");
  3743. Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_ANNOUNCEMENT . "','announcements/announcements.php','valves.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'announcements')) . "','0','squaregrey.gif','NO','_self','authoring','0')");
  3744. Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_FORUM . "','forum/index.php','forum.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'forums')) . "','0','squaregrey.gif','NO','_self','interaction','0')");
  3745. Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_DROPBOX . "','dropbox/index.php','dropbox.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'dropbox')) . "','0','squaregrey.gif','NO','_self','interaction','0')");
  3746. Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_USER . "','user/user.php','members.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'users')) . "','0','squaregrey.gif','NO','_self','interaction','0')");
  3747. Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_GROUP . "','group/group.php','group.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'groups')) . "','0','squaregrey.gif','NO','_self','interaction','0')");
  3748. Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_CHAT . "','chat/chat.php','chat.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'chat')) . "','0','squaregrey.gif','NO','_self','interaction','0')");
  3749. Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_STUDENTPUBLICATION . "','work/work.php','works.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'student_publications')) . "','0','squaregrey.gif','NO','_self','interaction','0')");
  3750. Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_SURVEY."','survey/survey_list.php','survey.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'survey')) . "','0','squaregrey.gif','NO','_self','interaction','0')");
  3751. Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_WIKI ."','wiki/index.php','wiki.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'wiki')) . "','0','squaregrey.gif','NO','_self','interaction','0')");
  3752. Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_GRADEBOOK."','gradebook/index.php','gradebook.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'gradebook')). "','0','squaregrey.gif','NO','_self','authoring','0')");
  3753. Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_GLOSSARY."','glossary/index.php','glossary.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'glossary')). "','0','squaregrey.gif','NO','_self','authoring','0')");
  3754. Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_NOTEBOOK."','notebook/index.php','notebook.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'notebook'))."','0','squaregrey.gif','NO','_self','interaction','0')");
  3755. Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_ATTENDANCE."','attendance/index.php','attendance.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'attendances'))."','0','squaregrey.gif','NO','_self','authoring','0')");
  3756. Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_COURSE_PROGRESS."','course_progress/index.php','course_progress.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'course_progress'))."','0','squaregrey.gif','NO','_self','authoring','0')");
  3757. Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_CURRICULUM."','curriculum','cv.png','".Text::string2binary(api_get_setting('course_create_active_tools', 'curriculum'))."','0','squaregrey.gif','NO','_self','authoring','0')");
  3758. if (api_get_setting('service_visio', 'active') == 'true') {
  3759. $mycheck = api_get_setting('service_visio', 'visio_host');
  3760. if (!empty($mycheck)) {
  3761. Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_VISIO_CONFERENCE . "','conference/index.php?type=conference','visio_meeting.gif','1','0','squaregrey.gif','NO','_self','interaction','0')");
  3762. Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_VISIO_CLASSROOM . "','conference/index.php?type=classroom','visio.gif','1','0','squaregrey.gif','NO','_self','authoring','0')");
  3763. }
  3764. }
  3765. if (api_get_setting('search_enabled') == 'true') {
  3766. Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_SEARCH. "','search/','info.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'enable_search')) . "','0','search.gif','NO','_self','authoring','0')");
  3767. }
  3768. // Blogs (Kevin Van Den Haute :: kevin@develop-it.be)
  3769. $sql = "INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL,'" . TOOL_BLOGS . "','blog/blog_admin.php','blog_admin.gif','" . Text::string2binary(api_get_setting('course_create_active_tools', 'blogs')) . "','1','squaregrey.gif','NO','_self','admin','0')";
  3770. Database::query($sql);
  3771. /* Course homepage tools for course admin only */
  3772. Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '".TOOL_TRACKING . "','tracking/courseLog.php','statistics.gif','$visible_for_course_admin','1','', 'NO','_self','admin','0')");
  3773. Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '".TOOL_COURSE_SETTING . "','course_info/infocours.php','reference.gif','$visible_for_course_admin','1','', 'NO','_self','admin','0')");
  3774. Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '".TOOL_COURSE_MAINTENANCE."','course_info/maintenance.php','backup.gif','$visible_for_course_admin','1','','NO','_self', 'admin','0')");
  3775. /* Course_setting table (courseinfo tool) */
  3776. Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'email_alert_manager_on_new_doc',0,'work')");
  3777. Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'email_alert_on_new_doc_dropbox',0,'dropbox')");
  3778. Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'allow_user_edit_agenda',0,'agenda')");
  3779. Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'allow_user_edit_announcement',0,'announcement')");
  3780. Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'email_alert_manager_on_new_quiz',1,'quiz')");
  3781. Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'allow_user_image_forum',1,'forum')");
  3782. Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'course_theme','','theme')");
  3783. Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'allow_learning_path_theme','1','theme')");
  3784. Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'allow_open_chat_window',1,'chat')");
  3785. Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'email_alert_to_teacher_on_new_user_in_course',0,'registration')");
  3786. Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'allow_user_view_user_list',1,'user')");
  3787. Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'display_info_advance_inside_homecourse',1,'thematic_advance')");
  3788. Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'email_alert_students_on_new_homework',0,'work')");
  3789. Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'enable_lp_auto_launch',0,'learning_path')");
  3790. Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'pdf_export_watermark_text','','learning_path')");
  3791. Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'allow_public_certificates','','certificates')");
  3792. Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'allow_fast_exercise_edition', 0 ,'exercise')");
  3793. Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'enable_exercise_auto_launch', 0 ,'exercise')");
  3794. /* Course homepage tools for platform admin only */
  3795. /* Group tool */
  3796. Database::query("INSERT INTO $TABLEGROUPCATEGORIES (c_id, id , title , description , max_student , self_reg_allowed , self_unreg_allowed , groups_per_user , display_order )
  3797. VALUES ($course_id, '2', '".Database::escape_string(get_lang('DefaultGroupCategory')) . "', '', '8', '0', '0', '0', '0');");
  3798. /* Example Material */
  3799. global $language_interface;
  3800. $language_interface = !empty($language_interface) ? $language_interface : api_get_setting('platformLanguage');
  3801. // Example material should be in the same language as the course is.
  3802. $language_interface_original = $language_interface;
  3803. $language_interface = $language;
  3804. //Share folder
  3805. Database::query("INSERT INTO $TABLETOOLDOCUMENT (c_id, path,title,filetype,size) VALUES ($course_id,'/shared_folder','".get_lang('UserFolders')."','folder','0')");
  3806. $example_doc_id = Database :: insert_id();
  3807. Database::query("INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id,'document',1,NOW(),NOW(),$example_doc_id,'DocumentAdded',1,0,NULL,0)");
  3808. //Chat folder
  3809. Database::query("INSERT INTO $TABLETOOLDOCUMENT (c_id, path,title,filetype,size) VALUES ($course_id,'/chat_files','".get_lang('ChatFiles')."','folder','0')");
  3810. $example_doc_id = Database :: insert_id();
  3811. Database::query("INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id,'document',1,NOW(),NOW(),$example_doc_id,'DocumentAdded',1,0,NULL,0)");
  3812. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  3813. $perm = api_get_permissions_for_new_directories();
  3814. $perm_file = api_get_permissions_for_new_files();
  3815. $chat_path = $sys_course_path.$course_repository.'/document/chat_files';
  3816. if (!is_dir($chat_path)) {
  3817. @mkdir($chat_path, api_get_permissions_for_new_directories());
  3818. }
  3819. /* Documents */
  3820. if ($fill_with_exemplary_content) {
  3821. Database::query("INSERT INTO $TABLETOOLDOCUMENT (c_id,path,title,filetype,size) VALUES ($course_id,'/images','".get_lang('Images')."','folder','0')");
  3822. $example_doc_id = Database :: insert_id();
  3823. Database::query("INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id,'document',1,NOW(),NOW(),$example_doc_id,'DocumentAdded',1,0,NULL,0)");
  3824. Database::query("INSERT INTO $TABLETOOLDOCUMENT (c_id, path,title,filetype,size) VALUES ($course_id,'/images/gallery','".get_lang('DefaultCourseImages')."','folder','0')");
  3825. $example_doc_id = Database :: insert_id();
  3826. Database::query("INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id,'document',1,NOW(),NOW(),$example_doc_id,'DocumentAdded',1,0,NULL,0)");
  3827. Database::query("INSERT INTO $TABLETOOLDOCUMENT (c_id, path,title,filetype,size) VALUES ($course_id,'/audio','".get_lang('Audio')."','folder','0')");
  3828. $example_doc_id = Database :: insert_id();
  3829. Database::query("INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id,'document',1,NOW(),NOW(),$example_doc_id,'DocumentAdded',1,0,NULL,0)");
  3830. Database::query("INSERT INTO $TABLETOOLDOCUMENT (c_id, path,title,filetype,size) VALUES ($course_id,'/flash','".get_lang('Flash')."','folder','0')");
  3831. $example_doc_id = Database :: insert_id();
  3832. Database::query("INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id,'document',1,NOW(),NOW(),$example_doc_id,'DocumentAdded',1,0,NULL,0)");
  3833. Database::query("INSERT INTO $TABLETOOLDOCUMENT (c_id, path,title,filetype,size) VALUES ($course_id,'/video','".get_lang('Video')."','folder','0')");
  3834. $example_doc_id = Database :: insert_id();
  3835. Database::query("INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id,'document',1,NOW(),NOW(),$example_doc_id,'DocumentAdded',1,0,NULL,0)");
  3836. Database::query("INSERT INTO $TABLETOOLDOCUMENT (c_id, path,title,filetype,size) VALUES ($course_id,'/certificates','".get_lang('Certificates')."','folder','0')");
  3837. $example_doc_id = Database :: insert_id();
  3838. Database::query("INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id,'document',1,NOW(),NOW(),$example_doc_id,'DocumentAdded',1,0,NULL,0)");
  3839. // FILL THE COURSE DOCUMENT WITH DEFAULT COURSE PICTURES
  3840. $folders_to_copy_from_default_course = array(
  3841. 'images',
  3842. 'audio',
  3843. 'flash',
  3844. 'video',
  3845. 'certificates',
  3846. );
  3847. $default_course_path = api_get_path(SYS_DEFAULT_COURSE_DOCUMENT_PATH);
  3848. $default_document_array = array();
  3849. foreach ($folders_to_copy_from_default_course as $folder) {
  3850. $default_course_folder_path = $default_course_path.$folder.'/';
  3851. $files = self::browse_folders($default_course_folder_path, array(), $folder);
  3852. $sorted_array = self::sort_pictures($files, 'dir');
  3853. $sorted_array = array_merge($sorted_array, self::sort_pictures($files, 'file'));
  3854. $default_document_array[$folder] = $sorted_array;
  3855. }
  3856. //Light protection (adding index.html in every document folder)
  3857. $htmlpage = "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <title>Not authorized</title>\n </head>\n <body>\n </body>\n</html>";
  3858. $example_cert_id = 0;
  3859. if (is_array($default_document_array) && count($default_document_array) > 0) {
  3860. foreach ($default_document_array as $media_type => $array_media) {
  3861. $path_documents = "/$media_type/";
  3862. //hack until feature #5242 is implemented
  3863. if ($media_type == 'images') {
  3864. $media_type = 'images/gallery';
  3865. $images_folder = $sys_course_path.$course_repository."/document/images/";
  3866. if (!is_dir($images_folder)) {
  3867. //Creating index.html
  3868. mkdir($images_folder, $perm);
  3869. $fd = fopen($images_folder.'index.html', 'w');
  3870. fwrite($fd, $htmlpage);
  3871. @chmod($images_folder.'index.html', $perm_file);
  3872. }
  3873. }
  3874. $course_documents_folder = $sys_course_path.$course_repository."/document/$media_type/";
  3875. $default_course_path = api_get_path(SYS_DEFAULT_COURSE_DOCUMENT_PATH).$path_documents;
  3876. //echo 'try '.$course_documents_folder; echo '<br />';
  3877. if (!is_dir($course_documents_folder)) {
  3878. //Creating index.html
  3879. mkdir($course_documents_folder, $perm);
  3880. $fd = fopen($course_documents_folder.'index.html', 'w');
  3881. fwrite($fd, $htmlpage);
  3882. @chmod($course_documents_folder.'index.html', $perm_file);
  3883. }
  3884. if (is_array($array_media) && count($array_media)>0) {
  3885. foreach ($array_media as $key => $value) {
  3886. if (isset($value['dir']) && !empty($value['dir'])) {
  3887. if (!is_dir($course_documents_folder.$value['dir'])) {
  3888. //Creating folder
  3889. mkdir($course_documents_folder.$value['dir'], $perm);
  3890. //Creating index.html (for light protection)
  3891. $index_html = $course_documents_folder.$value['dir'].'/index.html';
  3892. $fd = fopen($index_html, 'w');
  3893. fwrite($fd, $htmlpage);
  3894. @chmod($index_html, $perm_file);
  3895. //Inserting folder in the DB
  3896. $folder_path = substr($value['dir'], 0, strlen($value['dir']) - 1);
  3897. $temp = explode('/', $folder_path);
  3898. $title = $temp[count($temp)-1];
  3899. //hack until feature #5242 is implemented
  3900. if ($title == 'gallery') {
  3901. $title = get_lang('DefaultCourseImages');
  3902. }
  3903. if ($media_type == 'images/gallery') {
  3904. $folder_path = 'gallery/'.$folder_path;
  3905. }
  3906. Database::query("INSERT INTO $TABLETOOLDOCUMENT (c_id, path,title,filetype,size) VALUES ($course_id,'$path_documents".$folder_path."','".$title."','folder','0')");
  3907. $image_id = Database :: insert_id();
  3908. Database::query("INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id,'document',1,NOW(),NOW(),$image_id,'DocumentAdded',1,0,NULL,0)");
  3909. }
  3910. }
  3911. if (isset($value['file']) && !empty($value['file'])) {
  3912. if (!file_exists($course_documents_folder.$value['file'])) {
  3913. //Copying file
  3914. copy($default_course_path.$value['file'], $course_documents_folder.$value['file']);
  3915. chmod($course_documents_folder.$value['file'], $perm_file);
  3916. //echo $default_course_path.$value['file']; echo ' - '; echo $course_documents_folder.$value['file']; echo '<br />';
  3917. $temp = explode('/', $value['file']);
  3918. $file_size = filesize($course_documents_folder.$value['file']);
  3919. //hack until feature #5242 is implemented
  3920. if ($media_type == 'images/gallery') {
  3921. $value["file"] = 'gallery/'.$value["file"];
  3922. }
  3923. //Inserting file in the DB
  3924. Database::query("INSERT INTO $TABLETOOLDOCUMENT (c_id, path,title,filetype,size) VALUES ($course_id,'$path_documents".$value["file"]."','".$temp[count($temp)-1]."','file','$file_size')");
  3925. $image_id = Database :: insert_id();
  3926. if ($path_documents.$value['file'] == '/certificates/default.html') {
  3927. $example_cert_id = $image_id;
  3928. }
  3929. Database::query("INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id,'document',1,NOW(),NOW(),$image_id,'DocumentAdded',1,0,NULL,1)");
  3930. }
  3931. }
  3932. }
  3933. }
  3934. }
  3935. }
  3936. /* Agenda tool */
  3937. Database::query("INSERT INTO $TABLETOOLAGENDA VALUES ($course_id, NULL, '".Database::escape_string(get_lang('AgendaCreationTitle')) . "', '".Database::escape_string(get_lang('AgendaCreationContenu')) . "', now(), now(), NULL, 0, 0)");
  3938. // We need to add the item properties too!
  3939. $insert_id = Database :: insert_id();
  3940. $sql = "INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id, '" . TOOL_CALENDAR_EVENT . "',1,NOW(),NOW(),$insert_id,'AgendaAdded',1,0,NULL,1)";
  3941. Database::query($sql);
  3942. /* Links tool */
  3943. $add_google_link_sql = "INSERT INTO $TABLETOOLLINK (c_id, url, title, description, category_id, display_order, on_homepage, target)
  3944. VALUES ($course_id, 'http://www.google.com','Google','".Database::escape_string(get_lang('Google')) . "','0','0','0','_self')";
  3945. Database::query($add_google_link_sql);
  3946. // We need to add the item properties too!
  3947. $insert_id = Database :: insert_id();
  3948. $sql = "INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility)
  3949. VALUES ($course_id, '" . TOOL_LINK . "',1,NOW(),NOW(),$insert_id,'LinkAdded',1,0,NULL,1)";
  3950. Database::query($sql);
  3951. $add_wikipedia_link_sql = "INSERT INTO $TABLETOOLLINK (c_id, url, title, description, category_id, display_order, on_homepage, target)
  3952. VALUES ($course_id, 'http://www.wikipedia.org','Wikipedia','".Database::escape_string(get_lang('Wikipedia')) . "','0','1','0','_self')";
  3953. Database::query($add_wikipedia_link_sql);
  3954. // We need to add the item properties too!
  3955. $insert_id = Database :: insert_id();
  3956. $sql = "INSERT INTO $TABLEITEMPROPERTY (tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ('" . TOOL_LINK . "',1,NOW(),NOW(),$insert_id,'LinkAdded',1,0,NULL,1)";
  3957. Database::query($sql);
  3958. /* Announcement tool */
  3959. $sql = "INSERT INTO $TABLETOOLANNOUNCEMENTS (c_id, title,content,end_date,display_order,email_sent)
  3960. VALUES ($course_id, '".Database::escape_string(get_lang('AnnouncementExampleTitle')) . "', '".Database::escape_string(get_lang('AnnouncementEx')) . "', NOW(), '1','0')";
  3961. Database::query($sql);
  3962. // We need to add the item properties too!
  3963. $insert_id = Database :: insert_id();
  3964. $sql = "INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility)
  3965. VALUES ($course_id, '" . TOOL_ANNOUNCEMENT . "',1,NOW(),NOW(),$insert_id,'AnnouncementAdded',1,0,NULL,1)";
  3966. Database::query($sql);
  3967. /* Introduction text */
  3968. $intro_text='<p style="text-align: center;">
  3969. <img src="'.api_get_path(REL_CODE_PATH).'img/mascot.png" alt="Mr. Chamilo" title="Mr. Chamilo" />
  3970. <h2>'.Database::escape_string(get_lang('IntroductionText')).'</h2>
  3971. </p>';
  3972. Database::query("INSERT INTO $TABLEINTROS VALUES ($course_id, '" . TOOL_COURSE_HOMEPAGE . "','".$intro_text."', 0)");
  3973. Database::query("INSERT INTO $TABLEINTROS VALUES ($course_id, '" . TOOL_STUDENTPUBLICATION . "','".Database::escape_string(get_lang('IntroductionTwo')) . "', 0)");
  3974. // Wiki intro
  3975. $intro_wiki='<table width="100%" border="0" cellpadding="0" cellspacing="0"><tr><td width="110" valign="top" align="left"></td><td valign="top" align="left">'.Database::escape_string(get_lang('IntroductionWiki')).'</td></tr></table>';
  3976. Database::query("INSERT INTO $TABLEINTROS VALUES ($course_id, '" . TOOL_WIKI . "','".$intro_wiki. "', 0)");
  3977. /* Exercise tool */
  3978. $html = Database::escape_string('<table width="100%" border="0" cellpadding="0" cellspacing="0">
  3979. <tr><td width="110" valign="top" align="left">
  3980. <img src="'.api_get_path(WEB_DEFAULT_COURSE_DOCUMENT_PATH).'images/mr_dokeos/thinking.jpg"></td><td valign="top" align="left">'.get_lang('Antique').'
  3981. </td></tr></table>');
  3982. // Insert exercise
  3983. Database::query('INSERT INTO '.$TABLEQUIZ .' (c_id, title, description, type, random, random_answers, active, results_disabled ) ' .
  3984. ' VALUES ('.$course_id.', "'.Database::escape_string(get_lang('ExerciceEx')) . '", "'.$html.'", "1", "0", "0", "1", "0")');
  3985. $exercise_id = Database :: insert_id();
  3986. // Insert question
  3987. Database::query("INSERT INTO $TABLEQUIZQUESTIONLIST (c_id, question, description, ponderation, position, type, picture, level)
  3988. VALUES ( '.$course_id.', '".Database::escape_string(get_lang('SocraticIrony')) . "', '".Database::escape_string(get_lang('ManyAnswers')) . "', '10', '1', '2','',1)");
  3989. $questionId = Database :: insert_id();
  3990. Database::query("INSERT INTO $TABLEQUIZQUESTION (c_id, question_id, exercice_id, question_order) VALUES ($course_id,$questionId , $exercise_id, 1)");
  3991. // Insert answers
  3992. Database::query("INSERT INTO $TABLEQUIZANSWERSLIST (c_id, question_id, answer, correct, comment, ponderation, position) VALUES ($course_id, '$questionId', '".Database::escape_string(get_lang('Ridiculise')) . "', '0', '".Database::escape_string(get_lang('NoPsychology')) . "', '-5', '1')");
  3993. Database::query("INSERT INTO $TABLEQUIZANSWERSLIST (c_id, question_id, answer, correct, comment, ponderation, position) VALUES ($course_id, '$questionId', '".Database::escape_string(get_lang('AdmitError')) . "', '0', '".Database::escape_string(get_lang('NoSeduction')) . "', '-5', '2')");
  3994. Database::query("INSERT INTO $TABLEQUIZANSWERSLIST (c_id, question_id, answer, correct, comment, ponderation, position) VALUES ($course_id, '$questionId', '".Database::escape_string(get_lang('Force')) . "', '1', '".Database::escape_string(get_lang('Indeed')) . "', '5', '3')");
  3995. Database::query("INSERT INTO $TABLEQUIZANSWERSLIST (c_id, question_id, answer, correct, comment, ponderation, position) VALUES ($course_id, '$questionId', '".Database::escape_string(get_lang('Contradiction')) . "', '1', '".Database::escape_string(get_lang('NotFalse')) . "', '5', '4')");
  3996. /* Forum tool */
  3997. Database::query("INSERT INTO $TABLEFORUMCATEGORIES VALUES ($course_id, 1,'".Database::escape_string(get_lang('ExampleForumCategory'))."', '', 1, 0, 0)");
  3998. $insert_id = Database :: insert_id();
  3999. Database::query("INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility)
  4000. VALUES ($course_id, 'forum_category',1,NOW(),NOW(),$insert_id,'ForumCategoryAdded',1,0,NULL,1)");
  4001. Database::query("INSERT INTO $TABLEFORUMS (c_id, forum_title, forum_comment, forum_threads,forum_posts,forum_last_post,forum_category, allow_anonymous, allow_edit,allow_attachments, allow_new_threads,default_view,forum_of_group,forum_group_public_private, forum_order,locked,session_id )
  4002. VALUES ($course_id, '".Database::escape_string(get_lang('ExampleForum'))."', '', 0, 0, 0, 1, 0, 1, '0', 1, 'flat','0', 'public', 1, 0,0)");
  4003. $insert_id = Database :: insert_id();
  4004. Database::query("INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility)
  4005. VALUES ($course_id, '".TOOL_FORUM."', 1,NOW(),NOW(),$insert_id,'ForumAdded',1,0,NULL,1)");
  4006. Database::query("INSERT INTO $TABLEFORUMTHREADS (c_id, thread_id, thread_title, forum_id, thread_replies, thread_poster_id, thread_poster_name, thread_views, thread_last_post, thread_date, locked, thread_qualify_max, session_id)
  4007. VALUES ($course_id, 1, '".Database::escape_string(get_lang('ExampleThread'))."', 1, 0, 1, '', 0, 1, NOW(), 0, 10, 0)");
  4008. $insert_id = Database :: insert_id();
  4009. Database::query("INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility)
  4010. VALUES ($course_id, 'forum_thread',1,NOW(),NOW(),$insert_id,'ForumThreadAdded',1,0,NULL,1)");
  4011. Database::query("INSERT INTO $TABLEFORUMPOSTS VALUES ($course_id, 1, '".Database::escape_string(get_lang('ExampleThread'))."', '".Database::escape_string(get_lang('ExampleThreadContent'))."', 1, 1, 1, '', NOW(), 0, 0, 1)");
  4012. /* Gradebook tool */
  4013. $course = api_get_course_info_by_id($course_id);
  4014. $course_code = $course['code'];
  4015. // father gradebook
  4016. Database::query("INSERT INTO $TABLEGRADEBOOK (name, description, user_id, course_code, parent_id, weight, visible, certif_min_score, session_id, document_id) VALUES ('$course_code','',1,'$course_code',0,100,0,NULL,NULL,$example_cert_id)");
  4017. $gbid = Database :: insert_id();
  4018. Database::query("INSERT INTO $TABLEGRADEBOOK (name, description, user_id, course_code, parent_id, weight, visible, certif_min_score, session_id, document_id) VALUES ('$course_code','',1,'$course_code',$gbid,100,1,75,NULL,$example_cert_id)");
  4019. $gbid = Database :: insert_id();
  4020. Database::query("INSERT INTO $TABLEGRADEBOOKLINK (type, ref_id, user_id, course_code, category_id, created_at, weight, visible, locked) VALUES (1,$exercise_id,1,'$course_code',$gbid,'$now',100,1,0)");
  4021. }
  4022. //Installing plugins in course
  4023. $app_plugin = new AppPlugin();
  4024. $app_plugin->install_course_plugins($course_id);
  4025. $language_interface = $language_interface_original;
  4026. return true;
  4027. }
  4028. /**
  4029. * function register_course to create a record in the course table of the main database
  4030. * @param string $course_sys_code
  4031. * @param string $course_screen_code
  4032. * @param string $course_repository
  4033. * @param string $course_db_name
  4034. * @param string $tutor_name
  4035. * @param string $category
  4036. * @param string $title complete name of course
  4037. * @param string $course_language lang for this course
  4038. * @param string $uid uid of owner
  4039. * @param integer Expiration date in unix time representation
  4040. * @param array Optional array of teachers' user ID
  4041. * @return int 0
  4042. * @todo use an array called $params instead of lots of params
  4043. */
  4044. static function register_course($params)
  4045. {
  4046. global $error_msg, $firstExpirationDelay;
  4047. $title = $params['title'];
  4048. $code = $params['code'];
  4049. $visual_code = $params['visual_code'];
  4050. $directory = isset($params['directory']) ? $params['directory'] : null;
  4051. $tutor_name = isset($params['tutor_name']) ? $params['tutor_name'] : null;
  4052. //$description = $params['description'];
  4053. $category_code = isset($params['category_code']) ? $params['category_code'] : null;
  4054. $course_language = isset($params['course_language']) && !empty($params['course_language']) ? $params['course_language'] : api_get_setting('platformLanguage');
  4055. $user_id = empty($params['user_id']) ? api_get_user_id() : intval($params['user_id']);
  4056. $department_name = isset($params['department_name']) ? $params['department_name'] : null;
  4057. $department_url = isset($params['department_url']) ? $params['department_url'] : null;
  4058. $disk_quota = isset($params['disk_quota']) ? $params['disk_quota'] : null;
  4059. if (!isset($params['visibility'])) {
  4060. $default_course_visibility = api_get_setting('courses_default_creation_visibility');
  4061. if (isset($default_course_visibility)) {
  4062. $visibility = $default_course_visibility;
  4063. } else {
  4064. $visibility = COURSE_VISIBILITY_OPEN_PLATFORM;
  4065. }
  4066. } else {
  4067. $visibility = $params['visibility'];
  4068. }
  4069. $subscribe = isset($params['subscribe']) ? intval($params['subscribe']) : ($visibility == COURSE_VISIBILITY_OPEN_PLATFORM ? 1 : 0);
  4070. $unsubscribe = isset($params['unsubscribe']) ? intval($params['unsubscribe']) : 0;
  4071. $expiration_date = isset($params['expiration_date']) ? $params['expiration_date'] : null;
  4072. $teachers = isset($params['teachers']) ? $params['teachers'] : null;
  4073. $status = isset($params['status']) ? $params['status'] : null;
  4074. $TABLECOURSE = Database :: get_main_table(TABLE_MAIN_COURSE);
  4075. $TABLECOURSUSER = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  4076. $ok_to_register_course = true;
  4077. // Check whether all the needed parameters are present.
  4078. if (empty($code)) {
  4079. $error_msg[] = 'courseSysCode is missing';
  4080. $ok_to_register_course = false;
  4081. }
  4082. if (empty($visual_code)) {
  4083. $error_msg[] = 'courseScreenCode is missing';
  4084. $ok_to_register_course = false;
  4085. }
  4086. if (empty($directory)) {
  4087. $error_msg[] = 'courseRepository is missing';
  4088. $ok_to_register_course = false;
  4089. }
  4090. if (empty($title)) {
  4091. $error_msg[] = 'title is missing';
  4092. $ok_to_register_course = false;
  4093. }
  4094. if (empty($expiration_date)) {
  4095. $expiration_date = api_get_utc_datetime(time() + $firstExpirationDelay);
  4096. } else {
  4097. $expiration_date = api_get_utc_datetime($expiration_date);
  4098. }
  4099. if ($visibility < 0 || $visibility > 3) {
  4100. $error_msg[] = 'visibility is invalid';
  4101. $ok_to_register_course = false;
  4102. }
  4103. if (empty($disk_quota)) {
  4104. $disk_quota = api_get_setting('default_document_quotum');
  4105. }
  4106. $time = api_get_utc_datetime();
  4107. if (stripos($department_url, 'http://') === false && stripos($department_url, 'https://') === false) {
  4108. $department_url = 'http://'.$department_url;
  4109. }
  4110. //just in case
  4111. if ($department_url == 'http://') {
  4112. $department_url = '';
  4113. }
  4114. $course_id = 0;
  4115. if ($ok_to_register_course) {
  4116. // Here we must add 2 fields.
  4117. $sql = "INSERT INTO ".$TABLECOURSE . " SET
  4118. code = '".Database :: escape_string($code) . "',
  4119. directory = '".Database :: escape_string($directory) . "',
  4120. course_language = '".Database :: escape_string($course_language) . "',
  4121. title = '".Database :: escape_string($title) . "',
  4122. description = '".Database::escape_string(get_lang('CourseDescription')) . "',
  4123. category_code = '".Database :: escape_string($category_code) . "',
  4124. visibility = '".$visibility . "',
  4125. show_score = '1',
  4126. disk_quota = '".intval($disk_quota) . "',
  4127. creation_date = '$time',
  4128. expiration_date = '".$expiration_date . "',
  4129. last_edit = '$time',
  4130. last_visit = NULL,
  4131. tutor_name = '".Database :: escape_string($tutor_name) . "',
  4132. department_name = '".Database :: escape_string($department_name) . "',
  4133. department_url = '".Database :: escape_string($department_url) . "',
  4134. subscribe = '".intval($subscribe) . "',
  4135. unsubscribe = '".intval($unsubscribe) . "',
  4136. visual_code = '".Database :: escape_string($visual_code) . "'";
  4137. Database::query($sql);
  4138. $course_id = Database::insert_id();
  4139. if ($course_id) {
  4140. $sort = api_max_sort_value('0', api_get_user_id());
  4141. $i_course_sort = CourseManager :: userCourseSort($user_id, $code);
  4142. if (!empty($user_id)) {
  4143. $sql = "INSERT INTO ".$TABLECOURSUSER . " SET
  4144. c_id = '".Database :: escape_string($course_id). "',
  4145. user_id = '".intval($user_id) . "',
  4146. status = '1',
  4147. role = '".Database::escape_string(get_lang('Professor')) . "',
  4148. tutor_id = '0',
  4149. sort = '". ($i_course_sort) . "',
  4150. user_course_cat = '0'";
  4151. Database::query($sql);
  4152. }
  4153. if (!empty($teachers)) {
  4154. if (!is_array($teachers)) {
  4155. $teachers = array($teachers);
  4156. }
  4157. foreach ($teachers as $key) {
  4158. //just in case
  4159. if ($key == $user_id) {
  4160. continue;
  4161. }
  4162. if (empty($key)) {
  4163. continue;
  4164. }
  4165. $sql = "INSERT INTO ".$TABLECOURSUSER . " SET
  4166. course_code = '".Database::escape_string($code) . "',
  4167. user_id = '".Database::escape_string($key) . "',
  4168. status = '1',
  4169. role = '',
  4170. tutor_id = '0',
  4171. sort = '". ($sort +1) . "',
  4172. user_course_cat = '0'";
  4173. Database::query($sql);
  4174. }
  4175. }
  4176. // Adding the course to an URL
  4177. if (api_is_multiple_url_enabled()) {
  4178. $url_id = 1;
  4179. if (api_get_current_access_url_id() != -1) {
  4180. $url_id = api_get_current_access_url_id();
  4181. }
  4182. UrlManager::add_course_to_url($course_id, $url_id);
  4183. } else {
  4184. UrlManager::add_course_to_url($course_id, 1);
  4185. }
  4186. // Add event to the system log.
  4187. $user_id = api_get_user_id();
  4188. event_system(LOG_COURSE_CREATE, LOG_COURSE_CODE, $code, api_get_utc_datetime(), $user_id, $code);
  4189. $send_mail_to_admin = api_get_setting('send_email_to_admin_when_create_course');
  4190. // @todo Improve code to send to all current portal administrators.
  4191. if ($send_mail_to_admin == 'true') {
  4192. $siteName = api_get_setting('siteName');
  4193. $recipient_email = api_get_setting('emailAdministrator');
  4194. $recipient_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'));
  4195. $iname = api_get_setting('Institution');
  4196. $subject = get_lang('NewCourseCreatedIn').' '.$siteName.' - '.$iname;
  4197. $message = get_lang('Dear').' '.$recipient_name.",\n\n".get_lang('MessageOfNewCourseToAdmin').' '.$siteName.' - '.$iname."\n";
  4198. $message .= get_lang('CourseName').' '.$title."\n";
  4199. $message .= get_lang('Category').' '.$category_code."\n";
  4200. $message .= get_lang('Tutor').' '.$tutor_name."\n";
  4201. $message .= get_lang('Language').' '.$course_language;
  4202. @api_mail_html($recipient_name, $recipient_email, $subject, $message, $siteName, $recipient_email);
  4203. }
  4204. }
  4205. }
  4206. return $course_id;
  4207. }
  4208. /**
  4209. * This function returns information about coachs from a course in session
  4210. * @param int - optional, session id
  4211. * @param string - optional, course code
  4212. * @return array - array containing user_id, lastname, firstname, username
  4213. */
  4214. public static function get_coaches_from_course($session_id=0, $courseId = null) {
  4215. if (!empty($session_id)) {
  4216. $session_id = intval($session_id);
  4217. } else {
  4218. $session_id = api_get_session_id();
  4219. }
  4220. if (!empty($courseId)) {
  4221. $courseId = Database::escape_string($courseId);
  4222. } else {
  4223. $courseId = api_get_course_int_id();
  4224. }
  4225. $tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
  4226. $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  4227. $coaches = array();
  4228. $sql = "SELECT u.user_id,u.lastname,u.firstname,u.username
  4229. FROM $tbl_user u,$tbl_session_course_user scu
  4230. WHERE u.user_id = scu.id_user AND scu.id_session = '$session_id' AND scu.c_id = '$courseId' AND scu.status = 2";
  4231. $rs = Database::query($sql);
  4232. if (Database::num_rows($rs) > 0) {
  4233. while ($row = Database::fetch_array($rs)) {
  4234. $coaches[] = $row;
  4235. }
  4236. return $coaches;
  4237. } else {
  4238. return false;
  4239. }
  4240. }
  4241. /**
  4242. * @return a list (array) of all courses.
  4243. * This function was originally in the Database class
  4244. */
  4245. public static function get_course_list()
  4246. {
  4247. $table = Database::get_main_table(TABLE_MAIN_COURSE);
  4248. return Database::store_result(Database::query("SELECT *, id as real_id FROM $table"));
  4249. }
  4250. /**
  4251. * Returns course code from a given gradebook category's id
  4252. * @param int Category ID
  4253. * @return string Course code
  4254. */
  4255. public static function get_course_by_category($category_id)
  4256. {
  4257. $category_id = intval($category_id);
  4258. $info = Database::fetch_array(
  4259. Database::query(
  4260. 'SELECT course_code FROM '.Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY).' WHERE id='.$category_id
  4261. ),
  4262. 'ASSOC'
  4263. );
  4264. return $info ? $info['course_code'] : false;
  4265. }
  4266. /**
  4267. * @param $courseId
  4268. * @return array
  4269. */
  4270. public static function getCourseSettings($courseId)
  4271. {
  4272. $settingTable = Database::get_course_table(TABLE_COURSE_SETTING);
  4273. $courseId = intval($courseId);
  4274. $sql = "SELECT * FROM $settingTable WHERE c_id = $courseId";
  4275. $result = Database::query($sql);
  4276. $settings = array();
  4277. if (Database::num_rows($result)) {
  4278. while ($row = Database::fetch_array($result, 'ASSOC')) {
  4279. $settings[$row['variable']] = $row;
  4280. }
  4281. }
  4282. return $settings;
  4283. }
  4284. function updateTeachers($course_code, $teachers)
  4285. {
  4286. if (empty($teachers)) {
  4287. return false;
  4288. }
  4289. if (!is_array($teachers)) {
  4290. $teachers = array($teachers);
  4291. }
  4292. $course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  4293. // Delete only teacher relations that doesn't match the selected teachers
  4294. $cond = null;
  4295. if (count($teachers)>0) {
  4296. foreach($teachers as $key) {
  4297. $cond.= " AND user_id <> '".$key."'";
  4298. }
  4299. }
  4300. $sql = 'DELETE FROM '.$course_user_table.' WHERE course_code="'.Database::escape_string($course_code).'" AND status="1"'.$cond;
  4301. Database::query($sql);
  4302. if (count($teachers) > 0) {
  4303. foreach ($teachers as $key) {
  4304. //We check if the teacher is already subscribed in this course
  4305. $sql_select_teacher = 'SELECT 1 FROM '.$course_user_table.' WHERE user_id = "'.$key.'" AND course_code = "'.$course_code.'" ';
  4306. $result = Database::query($sql_select_teacher);
  4307. if (Database::num_rows($result) == 1) {
  4308. $sql = 'UPDATE '.$course_user_table.' SET status = "1" WHERE course_code = "'.$course_code.'" AND user_id = "'.$key.'" ';
  4309. } else {
  4310. $sql = "INSERT INTO ".$course_user_table . " SET
  4311. course_code = '".Database::escape_string($course_code). "',
  4312. user_id = '".$key . "',
  4313. status = '1',
  4314. role = '',
  4315. tutor_id='0',
  4316. sort='0',
  4317. user_course_cat='0'";
  4318. }
  4319. Database::query($sql);
  4320. }
  4321. }
  4322. }
  4323. } //end class CourseManager