course.lib.php 237 KB

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