course.lib.php 241 KB

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