course.lib.php 225 KB

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