course.lib.php 230 KB

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