course.lib.php 234 KB

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