course.lib.php 223 KB

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