course.lib.php 241 KB

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