course.lib.php 236 KB

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