course.lib.php 204 KB

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