course.lib.php 246 KB

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