course.lib.php 241 KB

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