usermanager.lib.php 216 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CoreBundle\Entity\ExtraField as EntityExtraField;
  4. use Chamilo\UserBundle\Entity\User;
  5. use Chamilo\CoreBundle\Framework\Container;
  6. use Chamilo\CoreBundle\Entity\AccessUrlRelUser;
  7. use Symfony\Component\Security\Core\Encoder\BCryptPasswordEncoder;
  8. use Symfony\Component\Security\Core\Encoder\EncoderFactory;
  9. use Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder;
  10. use Symfony\Component\Security\Core\Encoder\PlaintextPasswordEncoder;
  11. /**
  12. *
  13. * Class UserManager
  14. *
  15. * This library provides functions for user management.
  16. * Include/require it in your code to use its functionality.
  17. * @package chamilo.library
  18. * @author Julio Montoya <gugli100@gmail.com> Social network groups added 2009/12
  19. *
  20. */
  21. class UserManager
  22. {
  23. // This constants are deprecated use the constants located in ExtraField
  24. const USER_FIELD_TYPE_TEXT = 1;
  25. const USER_FIELD_TYPE_TEXTAREA = 2;
  26. const USER_FIELD_TYPE_RADIO = 3;
  27. const USER_FIELD_TYPE_SELECT = 4;
  28. const USER_FIELD_TYPE_SELECT_MULTIPLE = 5;
  29. const USER_FIELD_TYPE_DATE = 6;
  30. const USER_FIELD_TYPE_DATETIME = 7;
  31. const USER_FIELD_TYPE_DOUBLE_SELECT = 8;
  32. const USER_FIELD_TYPE_DIVIDER = 9;
  33. const USER_FIELD_TYPE_TAG = 10;
  34. const USER_FIELD_TYPE_TIMEZONE = 11;
  35. const USER_FIELD_TYPE_SOCIAL_PROFILE = 12;
  36. const USER_FIELD_TYPE_FILE = 13;
  37. const USER_FIELD_TYPE_MOBILE_PHONE_NUMBER = 14;
  38. private static $encryptionMethod;
  39. /**
  40. * Constructor
  41. * @assert () === null
  42. */
  43. public function __construct()
  44. {
  45. }
  46. /**
  47. * Repository is use to query the DB, selects, etc
  48. * @return Chamilo\UserBundle\Entity\Repository\UserRepository
  49. */
  50. public static function getRepository()
  51. {
  52. return Database::getManager()->getRepository('ChamiloUserBundle:User');
  53. }
  54. /**
  55. * Create/update/delete methods are available in the UserManager
  56. * (based in the Sonata\UserBundle\Entity\UserManager)
  57. *
  58. * @return Chamilo\UserBundle\Entity\Manager\UserManager
  59. */
  60. public static function getManager()
  61. {
  62. return Container::getUserManager();
  63. }
  64. /**
  65. * @param string $encryptionMethod
  66. */
  67. public static function setPasswordEncryption($encryptionMethod)
  68. {
  69. self::$encryptionMethod = $encryptionMethod;
  70. }
  71. /**
  72. * @return bool|mixed
  73. */
  74. public static function getPasswordEncryption()
  75. {
  76. $encryptionMethod = self::$encryptionMethod;
  77. if (empty($encryptionMethod)) {
  78. $encryptionMethod = api_get_configuration_value('password_encryption');
  79. }
  80. return $encryptionMethod;
  81. }
  82. /**
  83. * @return EncoderFactory
  84. */
  85. private static function getEncoderFactory()
  86. {
  87. $encryption = self::getPasswordEncryption();
  88. $encoders = array(
  89. 'Chamilo\\UserBundle\\Entity\\User' => new \Chamilo\UserBundle\Security\Encoder($encryption)
  90. );
  91. $encoderFactory = new EncoderFactory($encoders);
  92. return $encoderFactory;
  93. }
  94. /**
  95. * @param User $user
  96. *
  97. * @return \Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface
  98. */
  99. private static function getEncoder(User $user)
  100. {
  101. $encoderFactory = self::getEncoderFactory();
  102. return $encoderFactory->getEncoder($user);
  103. }
  104. /**
  105. * Validates the password
  106. *
  107. * @param $encoded
  108. * @param $raw
  109. * @param $salt
  110. * @return bool
  111. */
  112. public static function isPasswordValid($encoded, $raw, $salt)
  113. {
  114. $encoder = new \Chamilo\UserBundle\Security\Encoder(self::getPasswordEncryption());
  115. $validPassword = $encoder->isPasswordValid($encoded, $raw, $salt);
  116. return $validPassword;
  117. }
  118. /**
  119. * @param string $raw
  120. * @param User $user
  121. *
  122. * @return bool
  123. */
  124. public static function encryptPassword($raw, User $user)
  125. {
  126. $encoder = self::getEncoder($user);
  127. $encodedPassword = $encoder->encodePassword(
  128. $raw,
  129. $user->getSalt()
  130. );
  131. return $encodedPassword;
  132. }
  133. /**
  134. * @param int $userId
  135. * @param string $password
  136. *
  137. */
  138. public static function updatePassword($userId, $password)
  139. {
  140. $repository = self::getRepository();
  141. /** @var User $user */
  142. $user = $repository->find($userId);
  143. $userManager = self::getManager();
  144. $user->setPlainPassword($password);
  145. $userManager->updateUser($user, true);
  146. }
  147. /**
  148. * Creates a new user for the platform
  149. * @author Hugues Peeters <peeters@ipm.ucl.ac.be>,
  150. * @author Roan Embrechts <roan_embrechts@yahoo.com>
  151. * @param string $firstName
  152. * @param string $lastName
  153. * @param int $status (1 for course tutor, 5 for student, 6 for anonymous)
  154. * @param string $email
  155. * @param string $loginName
  156. * @param string $password
  157. * @param string $official_code Any official code (optional)
  158. * @param string $language User language (optional)
  159. * @param string $phone Phone number (optional)
  160. * @param string $picture_uri Picture URI (optional)
  161. * @param string $authSource Authentication source (optional, defaults to 'platform', dependind on constant)
  162. * @param string $expirationDate Account expiration date (optional, defaults to null)
  163. * @param int $active Whether the account is enabled or disabled by default
  164. * @param int $hr_dept_id The department of HR in which the user is registered (optional, defaults to 0)
  165. * @param array $extra Extra fields
  166. * @param string $encrypt_method Encrypt method used if password is given encrypted. Set to an empty string by default
  167. * @param bool $send_mail
  168. * @param bool $isAdmin
  169. * @param string $address
  170. * @param bool $sendEmailToAllAdmins
  171. * @param FormValidator $form
  172. *
  173. * @return mixed new user id - if the new user creation succeeds, false otherwise
  174. * @desc The function tries to retrieve user id from the session.
  175. * If it exists, the current user id is the creator id. If a problem arises,
  176. * @assert ('Sam','Gamegie',5,'sam@example.com','jo','jo') > 1
  177. * @assert ('Pippin','Took',null,null,'jo','jo') === false
  178. */
  179. public static function create_user(
  180. $firstName,
  181. $lastName,
  182. $status,
  183. $email,
  184. $loginName,
  185. $password,
  186. $official_code = '',
  187. $language = '',
  188. $phone = '',
  189. $picture_uri = '',
  190. $authSource = PLATFORM_AUTH_SOURCE,
  191. $expirationDate = null,
  192. $active = 1,
  193. $hr_dept_id = 0,
  194. $extra = [],
  195. $encrypt_method = '',
  196. $send_mail = false,
  197. $isAdmin = false,
  198. $address = '',
  199. $sendEmailToAllAdmins = false,
  200. $form = null
  201. ) {
  202. $currentUserId = api_get_user_id();
  203. $hook = HookCreateUser::create();
  204. if (!empty($hook)) {
  205. $hook->notifyCreateUser(HOOK_EVENT_TYPE_PRE);
  206. }
  207. // First check wether the login already exists
  208. if (!self::is_username_available($loginName)) {
  209. Display::addFlash(
  210. Display::return_message(get_lang('LoginAlreadyTaken'))
  211. );
  212. return false;
  213. }
  214. global $_configuration;
  215. $original_password = $password;
  216. $access_url_id = 1;
  217. if (api_get_multiple_access_url()) {
  218. $access_url_id = api_get_current_access_url_id();
  219. }
  220. if (isset($_configuration[$access_url_id]) &&
  221. is_array($_configuration[$access_url_id]) &&
  222. isset($_configuration[$access_url_id]['hosting_limit_users']) &&
  223. $_configuration[$access_url_id]['hosting_limit_users'] > 0) {
  224. $num = self::get_number_of_users();
  225. if ($num >= $_configuration[$access_url_id]['hosting_limit_users']) {
  226. api_warn_hosting_contact('hosting_limit_users');
  227. Display::addFlash(
  228. Display::return_message(
  229. get_lang('PortalUsersLimitReached'),
  230. 'warning'
  231. )
  232. );
  233. return false;
  234. }
  235. }
  236. if ($status === 1 &&
  237. isset($_configuration[$access_url_id]) &&
  238. is_array($_configuration[$access_url_id]) &&
  239. isset($_configuration[$access_url_id]['hosting_limit_teachers']) &&
  240. $_configuration[$access_url_id]['hosting_limit_teachers'] > 0
  241. ) {
  242. $num = self::get_number_of_users(1);
  243. if ($num >= $_configuration[$access_url_id]['hosting_limit_teachers']) {
  244. Display::addFlash(
  245. Display::return_message(
  246. get_lang('PortalTeachersLimitReached'),
  247. 'warning'
  248. )
  249. );
  250. api_warn_hosting_contact('hosting_limit_teachers');
  251. return false;
  252. }
  253. }
  254. if (empty($password)) {
  255. if ($authSource === PLATFORM_AUTH_SOURCE) {
  256. Display::addFlash(
  257. Display::return_message(
  258. get_lang('ThisFieldIsRequired').': '.get_lang(
  259. 'Password'
  260. ),
  261. 'warning'
  262. )
  263. );
  264. return false;
  265. }
  266. // We use the authSource as password.
  267. // The real validation will be by processed by the auth
  268. // source not Chamilo
  269. //$password = $authSource;
  270. }
  271. // database table definition
  272. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  273. // Checking the user language
  274. $languages = api_get_languages();
  275. $language = strtolower($language);
  276. if (isset($languages['folder'])) {
  277. if (!in_array($language, $languages['folder'])) {
  278. $language = api_get_setting('platformLanguage');
  279. }
  280. }
  281. if (!empty($currentUserId)) {
  282. $creator_id = $currentUserId;
  283. } else {
  284. $creator_id = 0;
  285. }
  286. $currentDate = api_get_utc_datetime();
  287. $now = new DateTime();
  288. if (empty($expirationDate) || $expirationDate == '0000-00-00 00:00:00') {
  289. // Default expiration date
  290. // if there is a default duration of a valid account then
  291. // we have to change the expiration_date accordingly
  292. // Accept 0000-00-00 00:00:00 as a null value to avoid issues with
  293. // third party code using this method with the previous (pre-1.10)
  294. // value of 0000...
  295. if (api_get_setting('account_valid_duration') != '') {
  296. $expirationDate = new DateTime($currentDate);
  297. $days = intval(api_get_setting('account_valid_duration'));
  298. $expirationDate->modify('+'.$days.' day');
  299. }
  300. } else {
  301. $expirationDate = api_get_utc_datetime($expirationDate);
  302. $expirationDate = new \DateTime($expirationDate, new DateTimeZone('UTC'));
  303. }
  304. $em = Database::getManager();
  305. $userManager = self::getManager();
  306. /** @var User $user */
  307. $user = $userManager->createUser();
  308. $user
  309. ->setLastname($lastName)
  310. ->setFirstname($firstName)
  311. ->setUsername($loginName)
  312. ->setStatus($status)
  313. ->setPlainPassword($password)
  314. ->setEmail($email)
  315. ->setOfficialCode($official_code)
  316. ->setPictureUri($picture_uri)
  317. ->setCreatorId($creator_id)
  318. ->setAuthSource($authSource)
  319. ->setPhone($phone)
  320. ->setAddress($address)
  321. ->setLanguage($language)
  322. ->setRegistrationDate($now)
  323. ->setHrDeptId($hr_dept_id)
  324. ->setActive($active)
  325. ->setEnabled($active)
  326. ;
  327. if (!empty($expirationDate)) {
  328. $user->setExpirationDate($expirationDate);
  329. }
  330. $url = $em->getRepository('ChamiloCoreBundle:AccessUrl')->find(api_get_current_access_url_id());
  331. $accessRelUser = new AccessUrlRelUser();
  332. $accessRelUser->setUser($user);
  333. $accessRelUser->setPortal($url);
  334. $user->setPortal($accessRelUser);
  335. // Default group is student
  336. $group = 'student';
  337. switch ($status) {
  338. case STUDENT:
  339. $group = 'student';
  340. break;
  341. case COURSEMANAGER:
  342. $group = 'teacher';
  343. break;
  344. case DRH:
  345. $group = 'drh';
  346. break;
  347. case SESSIONADMIN:
  348. $group = 'session_manager';
  349. break;
  350. /*case QUESTION:
  351. $group = 'question_manager';
  352. break;*/
  353. case STUDENT_BOSS:
  354. $group = 'student_boss';
  355. break;
  356. case INVITEE:
  357. $group = 'invitee';
  358. break;
  359. }
  360. if ($isAdmin) {
  361. $group = 'admin';
  362. }
  363. $criteria = ['code' => $group];
  364. $group = $em->getRepository('ChamiloUserBundle:Group')->findOneBy($criteria);
  365. $user->setGroups(array($group));
  366. $userManager->updateUser($user, true);
  367. $userId = $user->getId();
  368. if (!empty($userId)) {
  369. $sql = "UPDATE $table_user SET user_id = $userId WHERE id = $userId";
  370. Database::query($sql);
  371. if ($isAdmin) {
  372. UserManager::add_user_as_admin($user);
  373. }
  374. $extra['item_id'] = $userId;
  375. if (is_array($extra) && count($extra) > 0) {
  376. $courseFieldValue = new ExtraFieldValue('user');
  377. $courseFieldValue->saveFieldValues($extra);
  378. } else {
  379. // Create notify settings by default
  380. self::update_extra_field_value($userId, 'mail_notify_invitation', '1');
  381. self::update_extra_field_value($userId, 'mail_notify_message', '1');
  382. self::update_extra_field_value($userId, 'mail_notify_group_message', '1');
  383. }
  384. self::update_extra_field_value($userId, 'already_logged_in', 'false');
  385. if (!empty($email) && $send_mail) {
  386. $recipient_name = api_get_person_name(
  387. $firstName,
  388. $lastName,
  389. null,
  390. PERSON_NAME_EMAIL_ADDRESS
  391. );
  392. $tplSubject = new Template(
  393. null,
  394. false,
  395. false,
  396. false,
  397. false,
  398. false
  399. );
  400. $layoutSubject = $tplSubject->get_template(
  401. 'mail/subject_registration_platform.tpl'
  402. );
  403. $emailSubject = $tplSubject->fetch($layoutSubject);
  404. $sender_name = api_get_person_name(
  405. api_get_setting('administratorName'),
  406. api_get_setting('administratorSurname'),
  407. null,
  408. PERSON_NAME_EMAIL_ADDRESS
  409. );
  410. $email_admin = api_get_setting('emailAdministrator');
  411. $url = api_get_path(WEB_PATH);
  412. if (api_is_multiple_url_enabled()) {
  413. $access_url_id = api_get_current_access_url_id();
  414. if ($access_url_id != -1) {
  415. $urlInfo = api_get_access_url($access_url_id);
  416. if ($urlInfo) {
  417. $url = $urlInfo['url'];
  418. }
  419. }
  420. }
  421. $tplContent = new Template(null, false, false, false, false, false);
  422. // variables for the default template
  423. $tplContent->assign('complete_name', stripslashes(api_get_person_name($firstName, $lastName)));
  424. $tplContent->assign('login_name', $loginName);
  425. $tplContent->assign('original_password', stripslashes($original_password));
  426. $tplContent->assign('mailWebPath', $url);
  427. $tplContent->assign('new_user', $user);
  428. $layoutContent = $tplContent->get_template('mail/content_registration_platform.tpl');
  429. $emailBody = $tplContent->fetch($layoutContent);
  430. /* MANAGE EVENT WITH MAIL */
  431. if (EventsMail::check_if_using_class('user_registration')) {
  432. $values["about_user"] = $userId;
  433. $values["password"] = $original_password;
  434. $values["send_to"] = array($userId);
  435. $values["prior_lang"] = null;
  436. EventsDispatcher::events('user_registration', $values);
  437. } else {
  438. $phoneNumber = isset($extra['mobile_phone_number']) ? $extra['mobile_phone_number'] : null;
  439. $additionalParameters = array(
  440. 'smsType' => SmsPlugin::WELCOME_LOGIN_PASSWORD,
  441. 'userId' => $userId,
  442. 'mobilePhoneNumber' => $phoneNumber,
  443. 'password' => $original_password
  444. );
  445. api_mail_html(
  446. $recipient_name,
  447. $email,
  448. $emailSubject,
  449. $emailBody,
  450. $sender_name,
  451. $email_admin,
  452. null,
  453. null,
  454. null,
  455. $additionalParameters
  456. );
  457. }
  458. if ($sendEmailToAllAdmins) {
  459. $adminList = self::get_all_administrators();
  460. $tplContent = new Template(null, false, false, false, false, false);
  461. // variables for the default template
  462. $tplContent->assign('complete_name', stripslashes(api_get_person_name($firstName, $lastName)));
  463. $tplContent->assign('user_added', $user);
  464. $renderer = FormValidator::getDefaultRenderer();
  465. // Form template
  466. $elementTemplate = ' {label}: {element} <br />';
  467. $renderer->setElementTemplate($elementTemplate);
  468. /** @var FormValidator $form */
  469. $form->freeze(null, $elementTemplate);
  470. $form->removeElement('submit');
  471. $formData = $form->returnForm();
  472. $url = api_get_path(WEB_CODE_PATH).'admin/user_information.php?user_id='.$user->getId();
  473. $tplContent->assign('link', Display::url($url, $url));
  474. $tplContent->assign('form', $formData);
  475. $layoutContent = $tplContent->get_template('mail/content_registration_platform_to_admin.tpl');
  476. $emailBody = $tplContent->fetch($layoutContent);
  477. $subject = get_lang('UserAdded');
  478. foreach ($adminList as $adminId => $data) {
  479. MessageManager::send_message_simple($adminId, $subject, $emailBody);
  480. }
  481. }
  482. /* ENDS MANAGE EVENT WITH MAIL */
  483. }
  484. if (!empty($hook)) {
  485. $hook->setEventData(array(
  486. 'return' => $userId,
  487. 'originalPassword' => $original_password
  488. ));
  489. $hook->notifyCreateUser(HOOK_EVENT_TYPE_POST);
  490. }
  491. Event::addEvent(LOG_USER_CREATE, LOG_USER_ID, $userId);
  492. } else {
  493. Display::addFlash(
  494. Display::return_message(get_lang('ErrorContactPlatformAdmin'))
  495. );
  496. return false;
  497. }
  498. return $userId;
  499. }
  500. /**
  501. * Can user be deleted? This function checks whether there's a course
  502. * in which the given user is the
  503. * only course administrator. If that is the case, the user can't be
  504. * deleted because the course would remain without a course admin.
  505. * @param int $user_id The user id
  506. * @return boolean true if user can be deleted
  507. * @assert (null) === false
  508. * @assert (-1) === false
  509. * @assert ('abc') === false
  510. */
  511. public static function can_delete_user($user_id)
  512. {
  513. $deny = api_get_configuration_value('deny_delete_users');
  514. if ($deny) {
  515. return false;
  516. }
  517. $table_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  518. if ($user_id != strval(intval($user_id))) {
  519. return false;
  520. }
  521. if ($user_id === false) {
  522. return false;
  523. }
  524. $sql = "SELECT * FROM $table_course_user
  525. WHERE status = 1 AND user_id = ".$user_id;
  526. $res = Database::query($sql);
  527. while ($course = Database::fetch_object($res)) {
  528. $sql = "SELECT id FROM $table_course_user
  529. WHERE status=1 AND c_id = ".intval($course->c_id);
  530. $res2 = Database::query($sql);
  531. if (Database::num_rows($res2) == 1) {
  532. return false;
  533. }
  534. }
  535. return true;
  536. }
  537. /**
  538. * Delete a user from the platform, and all its belongings. This is a
  539. * very dangerous function that should only be accessible by
  540. * super-admins. Other roles should only be able to disable a user,
  541. * which removes access to the platform but doesn't delete anything.
  542. * @param int The ID of th user to be deleted
  543. * @return boolean true if user is successfully deleted, false otherwise
  544. * @assert (null) === false
  545. * @assert ('abc') === false
  546. */
  547. public static function delete_user($user_id)
  548. {
  549. if ($user_id != strval(intval($user_id))) {
  550. return false;
  551. }
  552. if ($user_id === false) {
  553. return false;
  554. }
  555. if (!self::can_delete_user($user_id)) {
  556. return false;
  557. }
  558. $user = self::getManager()->find($user_id);
  559. if (empty($user)) {
  560. return false;
  561. }
  562. $usergroup_rel_user = Database :: get_main_table(TABLE_USERGROUP_REL_USER);
  563. $table_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  564. $table_course = Database :: get_main_table(TABLE_MAIN_COURSE);
  565. $table_session = Database :: get_main_table(TABLE_MAIN_SESSION);
  566. $table_admin = Database :: get_main_table(TABLE_MAIN_ADMIN);
  567. $table_session_user = Database :: get_main_table(TABLE_MAIN_SESSION_USER);
  568. $table_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  569. $table_group = Database :: get_course_table(TABLE_GROUP_USER);
  570. $table_work = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
  571. // Unsubscribe the user from all groups in all his courses
  572. $sql = "SELECT c.id
  573. FROM $table_course c
  574. INNER JOIN $table_course_user cu
  575. ON (c.id = cu.c_id)
  576. WHERE
  577. cu.user_id = '".$user_id."' AND
  578. relation_type<>".COURSE_RELATION_TYPE_RRHH."
  579. ";
  580. $res = Database::query($sql);
  581. while ($course = Database::fetch_object($res)) {
  582. $sql = "DELETE FROM $table_group
  583. WHERE c_id = {$course->id} AND user_id = $user_id";
  584. Database::query($sql);
  585. }
  586. // Unsubscribe user from usergroup_rel_user
  587. $sql = "DELETE FROM $usergroup_rel_user WHERE user_id = '".$user_id."'";
  588. Database::query($sql);
  589. // Unsubscribe user from all courses
  590. $sql = "DELETE FROM $table_course_user WHERE user_id = '".$user_id."'";
  591. Database::query($sql);
  592. // Unsubscribe user from all courses in sessions
  593. $sql = "DELETE FROM $table_session_course_user WHERE user_id = '".$user_id."'";
  594. Database::query($sql);
  595. // If the user was added as a id_coach then set the current admin as coach see BT#
  596. $currentUserId = api_get_user_id();
  597. $sql = "UPDATE $table_session SET id_coach = $currentUserId
  598. WHERE id_coach = '".$user_id."'";
  599. Database::query($sql);
  600. $sql = "UPDATE $table_session SET id_coach = $currentUserId
  601. WHERE session_admin_id = '".$user_id."'";
  602. Database::query($sql);
  603. // Unsubscribe user from all sessions
  604. $sql = "DELETE FROM $table_session_user
  605. WHERE user_id = '".$user_id."'";
  606. Database::query($sql);
  607. // Delete user picture
  608. /* TODO: Logic about api_get_setting('split_users_upload_directory') == 'true'
  609. a user has 4 different sized photos to be deleted. */
  610. $user_info = api_get_user_info($user_id);
  611. if (strlen($user_info['picture_uri']) > 0) {
  612. $path = self::getUserPathById($user_id, 'system');
  613. $img_path = $path.$user_info['picture_uri'];
  614. if (file_exists($img_path)) {
  615. unlink($img_path);
  616. }
  617. }
  618. // Delete the personal course categories
  619. $course_cat_table = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
  620. $sql = "DELETE FROM $course_cat_table WHERE user_id = '".$user_id."'";
  621. Database::query($sql);
  622. // Delete user from the admin table
  623. $sql = "DELETE FROM $table_admin WHERE user_id = '".$user_id."'";
  624. Database::query($sql);
  625. // Delete the personal agenda-items from this user
  626. $agenda_table = Database::get_main_table(TABLE_PERSONAL_AGENDA);
  627. $sql = "DELETE FROM $agenda_table WHERE user = '".$user_id."'";
  628. Database::query($sql);
  629. $gradebook_results_table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
  630. $sql = 'DELETE FROM '.$gradebook_results_table.' WHERE user_id = '.$user_id;
  631. Database::query($sql);
  632. $extraFieldValue = new ExtraFieldValue('user');
  633. $extraFieldValue->deleteValuesByItem($user_id);
  634. UrlManager::deleteUserFromAllUrls($user_id);
  635. if (api_get_setting('allow_social_tool') == 'true') {
  636. $userGroup = new UserGroup();
  637. //Delete user from portal groups
  638. $group_list = $userGroup->get_groups_by_user($user_id);
  639. if (!empty($group_list)) {
  640. foreach ($group_list as $group_id => $data) {
  641. $userGroup->delete_user_rel_group($user_id, $group_id);
  642. }
  643. }
  644. // Delete user from friend lists
  645. SocialManager::remove_user_rel_user($user_id, true);
  646. }
  647. // Removing survey invitation
  648. SurveyManager::delete_all_survey_invitations_by_user($user_id);
  649. // Delete students works
  650. $sql = "DELETE FROM $table_work WHERE user_id = $user_id AND c_id <> 0";
  651. Database::query($sql);
  652. $sql = "UPDATE c_item_property SET to_user_id = NULL
  653. WHERE to_user_id = '".$user_id."'";
  654. Database::query($sql);
  655. $sql = "UPDATE c_item_property SET insert_user_id = NULL
  656. WHERE insert_user_id = '".$user_id."'";
  657. Database::query($sql);
  658. $sql = "UPDATE c_item_property SET lastedit_user_id = NULL
  659. WHERE lastedit_user_id = '".$user_id."'";
  660. Database::query($sql);
  661. // Skills
  662. $table = Database::get_main_table(TABLE_MAIN_SKILL_REL_USER);
  663. $sql = "DELETE FROM $table WHERE user_id = $user_id";
  664. Database::query($sql);
  665. $connection = Database::getManager()->getConnection();
  666. $tableExists = $connection->getSchemaManager()->tablesExist(['plugin_bbb_room']);
  667. if ($tableExists) {
  668. // Delete user from database
  669. $sql = "DELETE FROM plugin_bbb_room WHERE participant_id = $user_id";
  670. Database::query($sql);
  671. }
  672. // Delete user/ticket relationships :(
  673. $tableExists = $connection->getSchemaManager()->tablesExist(['ticket_ticket']);
  674. if ($tableExists) {
  675. TicketManager::deleteUserFromTicketSystem($user_id);
  676. }
  677. $tableExists = $connection->getSchemaManager()->tablesExist(['c_lp_category_user']);
  678. if ($tableExists) {
  679. $sql = "DELETE FROM c_lp_category_user WHERE user_id = $user_id";
  680. Database::query($sql);
  681. }
  682. // Delete user from database
  683. /*$sql = "DELETE FROM $table_user WHERE id = '".$user_id."'";
  684. Database::query($sql);*/
  685. self::getManager()->delete($user);
  686. // Add event to system log
  687. $user_id_manager = api_get_user_id();
  688. Event::addEvent(
  689. LOG_USER_DELETE,
  690. LOG_USER_ID,
  691. $user_id,
  692. api_get_utc_datetime(),
  693. $user_id_manager
  694. );
  695. Event::addEvent(
  696. LOG_USER_DELETE,
  697. LOG_USER_OBJECT,
  698. $user_info,
  699. api_get_utc_datetime(),
  700. $user_id_manager
  701. );
  702. $cacheAvailable = api_get_configuration_value('apc');
  703. if ($cacheAvailable === true) {
  704. $apcVar = api_get_configuration_value('apc_prefix').'userinfo_'.$user_id;
  705. if (apcu_exists($apcVar)) {
  706. apcu_delete($apcVar);
  707. }
  708. }
  709. return true;
  710. }
  711. /**
  712. * Deletes users completely. Can be called either as:
  713. * - UserManager::delete_users(1, 2, 3); or
  714. * - UserManager::delete_users(array(1, 2, 3));
  715. * @param array|int $ids
  716. * @return boolean True if at least one user was successfuly deleted. False otherwise.
  717. * @author Laurent Opprecht
  718. * @uses UserManager::delete_user() to actually delete each user
  719. * @assert (null) === false
  720. * @assert (-1) === false
  721. * @assert (array(-1)) === false
  722. */
  723. public static function delete_users($ids = array())
  724. {
  725. $result = false;
  726. $ids = is_array($ids) ? $ids : func_get_args();
  727. if (!is_array($ids) || count($ids) == 0) {
  728. return false;
  729. }
  730. $ids = array_map('intval', $ids);
  731. foreach ($ids as $id) {
  732. if (empty($id) || $id < 1) {
  733. continue;
  734. }
  735. $deleted = self::delete_user($id);
  736. $result = $deleted || $result;
  737. }
  738. return $result;
  739. }
  740. /**
  741. * Disable users. Can be called either as:
  742. * - UserManager::deactivate_users(1, 2, 3);
  743. * - UserManager::deactivate_users(array(1, 2, 3));
  744. * @param array|int $ids
  745. * @return boolean
  746. * @author Laurent Opprecht
  747. * @assert (null) === false
  748. * @assert (array(-1)) === false
  749. */
  750. public static function deactivate_users($ids = array())
  751. {
  752. if (empty($ids)) {
  753. return false;
  754. }
  755. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  756. $ids = is_array($ids) ? $ids : func_get_args();
  757. $ids = array_map('intval', $ids);
  758. $ids = implode(',', $ids);
  759. $sql = "UPDATE $table_user SET active = 0 WHERE id IN ($ids)";
  760. $r = Database::query($sql);
  761. if ($r !== false) {
  762. Event::addEvent(LOG_USER_DISABLE, LOG_USER_ID, $ids);
  763. }
  764. return $r;
  765. }
  766. /**
  767. * Enable users. Can be called either as:
  768. * - UserManager::activate_users(1, 2, 3);
  769. * - UserManager::activate_users(array(1, 2, 3));
  770. * @param array|int IDs of the users to enable
  771. * @return boolean
  772. * @author Laurent Opprecht
  773. * @assert (null) === false
  774. * @assert (array(-1)) === false
  775. */
  776. public static function activate_users($ids = array())
  777. {
  778. if (empty($ids)) {
  779. return false;
  780. }
  781. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  782. $ids = is_array($ids) ? $ids : func_get_args();
  783. $ids = array_map('intval', $ids);
  784. $ids = implode(',', $ids);
  785. $sql = "UPDATE $table_user SET active = 1 WHERE id IN ($ids)";
  786. $r = Database::query($sql);
  787. if ($r !== false) {
  788. Event::addEvent(LOG_USER_ENABLE, LOG_USER_ID, $ids);
  789. }
  790. return $r;
  791. }
  792. /**
  793. * Update user information with new openid
  794. * @param int $user_id
  795. * @param string $openid
  796. * @return boolean true if the user information was updated
  797. * @assert (false,'') === false
  798. * @assert (-1,'') === false
  799. */
  800. public static function update_openid($user_id, $openid)
  801. {
  802. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  803. if ($user_id != strval(intval($user_id))) {
  804. return false;
  805. }
  806. if ($user_id === false) {
  807. return false;
  808. }
  809. $sql = "UPDATE $table_user SET
  810. openid='".Database::escape_string($openid)."'";
  811. $sql .= " WHERE id= $user_id";
  812. return Database::query($sql);
  813. }
  814. /**
  815. * Update user information with all the parameters passed to this function
  816. * @param int The ID of the user to be updated
  817. * @param string The user's firstname
  818. * @param string The user's lastname
  819. * @param string The user's username (login)
  820. * @param string The user's password
  821. * @param string The authentication source (default: "platform")
  822. * @param string The user's e-mail address
  823. * @param int The user's status
  824. * @param string The user's official code (usually just an internal institutional code)
  825. * @param string The user's phone number
  826. * @param string The user's picture URL (internal to the Chamilo directory)
  827. * @param int The user ID of the person who registered this user (optional, defaults to null)
  828. * @param int The department of HR in which the user is registered (optional, defaults to 0)
  829. * @param array A series of additional fields to add to this user as extra fields (optional, defaults to null)
  830. * @return boolean|integer False on error, or the user ID if the user information was updated
  831. * @assert (false, false, false, false, false, false, false, false, false, false, false, false, false) === false
  832. */
  833. public static function update_user(
  834. $user_id,
  835. $firstname,
  836. $lastname,
  837. $username,
  838. $password = null,
  839. $auth_source = null,
  840. $email,
  841. $status,
  842. $official_code,
  843. $phone,
  844. $picture_uri,
  845. $expiration_date,
  846. $active,
  847. $creator_id = null,
  848. $hr_dept_id = 0,
  849. $extra = null,
  850. $language = 'english',
  851. $encrypt_method = '',
  852. $send_email = false,
  853. $reset_password = 0,
  854. $address = null
  855. ) {
  856. $hook = HookUpdateUser::create();
  857. if (!empty($hook)) {
  858. $hook->notifyUpdateUser(HOOK_EVENT_TYPE_PRE);
  859. }
  860. $original_password = $password;
  861. if ($user_id != strval(intval($user_id))) {
  862. return false;
  863. }
  864. if (empty($user_id)) {
  865. return false;
  866. }
  867. $userManager = self::getManager();
  868. /** @var Chamilo\UserBundle\Entity\User $user */
  869. $user = self::getRepository()->find($user_id);
  870. if (empty($user)) {
  871. return false;
  872. }
  873. if ($reset_password == 0) {
  874. $password = null;
  875. $auth_source = $user->getAuthSource();
  876. } elseif ($reset_password == 1) {
  877. $original_password = $password = api_generate_password();
  878. $auth_source = PLATFORM_AUTH_SOURCE;
  879. } elseif ($reset_password == 2) {
  880. $password = $password;
  881. $auth_source = PLATFORM_AUTH_SOURCE;
  882. } elseif ($reset_password == 3) {
  883. $password = $password;
  884. $auth_source = $auth_source;
  885. }
  886. // Checking the user language
  887. $languages = api_get_platform_isocodes();
  888. if (!in_array($language, $languages)) {
  889. $language = api_get_setting('platformLanguage');
  890. }
  891. $change_active = 0;
  892. $isUserActive = $user->getActive();
  893. if ($isUserActive != $active) {
  894. $change_active = 1;
  895. }
  896. $originalUsername = $user->getUsername();
  897. // If username is different from original then check if it exists.
  898. if ($originalUsername !== $username) {
  899. $available = self::is_username_available($username);
  900. if ($available === false) {
  901. return false;
  902. }
  903. }
  904. if (!empty($expiration_date)) {
  905. $expiration_date = api_get_utc_datetime($expiration_date);
  906. $expiration_date = new \DateTime(
  907. $expiration_date,
  908. new DateTimeZone('UTC')
  909. );
  910. }
  911. $user
  912. ->setLastname($lastname)
  913. ->setFirstname($firstname)
  914. ->setUsername($username)
  915. ->setStatus($status)
  916. ->setAuthSource($auth_source)
  917. ->setLanguage($language)
  918. ->setEmail($email)
  919. ->setOfficialCode($official_code)
  920. ->setPhone($phone)
  921. ->setAddress($address)
  922. ->setPictureUri($picture_uri)
  923. ->setExpirationDate($expiration_date)
  924. ->setActive($active)
  925. ->setEnabled($active)
  926. ->setHrDeptId($hr_dept_id)
  927. ;
  928. if (!is_null($password)) {
  929. $user->setPlainPassword($password);
  930. }
  931. $userManager->updateUser($user, true);
  932. if ($change_active == 1) {
  933. if ($active == 1) {
  934. $event_title = LOG_USER_ENABLE;
  935. } else {
  936. $event_title = LOG_USER_DISABLE;
  937. }
  938. Event::addEvent($event_title, LOG_USER_ID, $user_id);
  939. }
  940. if (is_array($extra) && count($extra) > 0) {
  941. $res = true;
  942. foreach ($extra as $fname => $fvalue) {
  943. $res = $res && self::update_extra_field_value(
  944. $user_id,
  945. $fname,
  946. $fvalue
  947. );
  948. }
  949. }
  950. if (!empty($email) && $send_email) {
  951. $recipient_name = api_get_person_name($firstname, $lastname, null, PERSON_NAME_EMAIL_ADDRESS);
  952. $emailsubject = '['.api_get_setting('siteName').'] '.get_lang('YourReg').' '.api_get_setting('siteName');
  953. $sender_name = api_get_person_name(
  954. api_get_setting('administratorName'),
  955. api_get_setting('administratorSurname'),
  956. null,
  957. PERSON_NAME_EMAIL_ADDRESS
  958. );
  959. $email_admin = api_get_setting('emailAdministrator');
  960. if (api_is_multiple_url_enabled()) {
  961. $access_url_id = api_get_current_access_url_id();
  962. if ($access_url_id != -1) {
  963. $url = api_get_access_url($access_url_id);
  964. $emailbody = get_lang('Dear')." ".stripslashes(api_get_person_name($firstname, $lastname)).",\n\n".
  965. get_lang('YouAreReg')." ".api_get_setting('siteName')." ".get_lang('WithTheFollowingSettings')."\n\n".
  966. get_lang('Username')." : ".$username.(($reset_password > 0) ? "\n".
  967. get_lang('Pass')." : ".stripslashes($original_password) : "")."\n\n".
  968. get_lang('Address')." ".api_get_setting('siteName')." ".get_lang('Is')." : ".$url['url']."\n\n".
  969. get_lang('Problem')."\n\n".
  970. get_lang('SignatureFormula').",\n\n".
  971. api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'))."\n".
  972. get_lang('Manager')." ".api_get_setting('siteName')."\nT. ".api_get_setting('administratorTelephone')."\n".
  973. get_lang('Email')." : ".api_get_setting('emailAdministrator');
  974. }
  975. } else {
  976. $emailbody = get_lang('Dear')." ".stripslashes(api_get_person_name($firstname, $lastname)).",\n\n".
  977. get_lang('YouAreReg')." ".api_get_setting('siteName')." ".get_lang('WithTheFollowingSettings')."\n\n".
  978. get_lang('Username')." : ".$username.(($reset_password > 0) ? "\n".
  979. get_lang('Pass')." : ".stripslashes($original_password) : "")."\n\n".
  980. get_lang('Address')." ".api_get_setting('siteName')." ".get_lang('Is')." : ".api_get_path(WEB_PATH)."\n\n".
  981. get_lang('Problem')."\n\n".
  982. get_lang('SignatureFormula').",\n\n".
  983. api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'))."\n".
  984. get_lang('Manager')." ".api_get_setting('siteName')."\nT. ".api_get_setting('administratorTelephone')."\n".
  985. get_lang('Email')." : ".api_get_setting('emailAdministrator');
  986. }
  987. $emailbody = nl2br($emailbody);
  988. api_mail_html(
  989. $recipient_name,
  990. $email,
  991. $emailsubject,
  992. $emailbody,
  993. $sender_name,
  994. $email_admin
  995. );
  996. }
  997. if (!empty($hook)) {
  998. $hook->notifyUpdateUser(HOOK_EVENT_TYPE_POST);
  999. }
  1000. $cacheAvailable = api_get_configuration_value('apc');
  1001. if ($cacheAvailable === true) {
  1002. $apcVar = api_get_configuration_value('apc_prefix').'userinfo_'.$user_id;
  1003. if (apcu_exists($apcVar)) {
  1004. apcu_delete($apcVar);
  1005. }
  1006. }
  1007. return $user->getId();
  1008. }
  1009. /**
  1010. * Disables or enables a user
  1011. * @param int $user_id
  1012. * @param int $active Enable or disable
  1013. * @return void
  1014. * @assert (-1,0) === false
  1015. * @assert (1,1) === true
  1016. */
  1017. private static function change_active_state($user_id, $active)
  1018. {
  1019. if (strval(intval($user_id)) != $user_id) {
  1020. return false;
  1021. }
  1022. if ($user_id < 1) {
  1023. return false;
  1024. }
  1025. $user_id = intval($user_id);
  1026. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  1027. $sql = "UPDATE $table_user SET active = '$active' WHERE id = $user_id";
  1028. $r = Database::query($sql);
  1029. $ev = LOG_USER_DISABLE;
  1030. if ($active == 1) {
  1031. $ev = LOG_USER_ENABLE;
  1032. }
  1033. if ($r !== false) {
  1034. Event::addEvent($ev, LOG_USER_ID, $user_id);
  1035. }
  1036. return $r;
  1037. }
  1038. /**
  1039. * Disables a user
  1040. * @param int User id
  1041. * @return bool
  1042. * @uses UserManager::change_active_state() to actually disable the user
  1043. * @assert (0) === false
  1044. */
  1045. public static function disable($user_id)
  1046. {
  1047. if (empty($user_id)) {
  1048. return false;
  1049. }
  1050. self::change_active_state($user_id, 0);
  1051. return true;
  1052. }
  1053. /**
  1054. * Enable a user
  1055. * @param int User id
  1056. * @return bool
  1057. * @uses UserManager::change_active_state() to actually disable the user
  1058. * @assert (0) === false
  1059. */
  1060. public static function enable($user_id)
  1061. {
  1062. if (empty($user_id)) {
  1063. return false;
  1064. }
  1065. self::change_active_state($user_id, 1);
  1066. return true;
  1067. }
  1068. /**
  1069. * Returns the user's id based on the original id and field name in
  1070. * the extra fields. Returns 0 if no user was found. This function is
  1071. * mostly useful in the context of a web services-based sinchronization
  1072. * @param string Original user id
  1073. * @param string Original field name
  1074. * @return int User id
  1075. * @assert ('0','---') === 0
  1076. */
  1077. public static function get_user_id_from_original_id(
  1078. $original_user_id_value,
  1079. $original_user_id_name
  1080. ) {
  1081. $t_uf = Database::get_main_table(TABLE_EXTRA_FIELD);
  1082. $t_ufv = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  1083. $extraFieldType = EntityExtraField::USER_FIELD_TYPE;
  1084. $sql = "SELECT item_id as user_id
  1085. FROM $t_uf uf
  1086. INNER JOIN $t_ufv ufv
  1087. ON ufv.field_id=uf.id
  1088. WHERE
  1089. variable='$original_user_id_name' AND
  1090. value='$original_user_id_value' AND
  1091. extra_field_type = $extraFieldType
  1092. ";
  1093. $res = Database::query($sql);
  1094. $row = Database::fetch_object($res);
  1095. if ($row) {
  1096. return $row->user_id;
  1097. } else {
  1098. return 0;
  1099. }
  1100. }
  1101. /**
  1102. * Check if a username is available
  1103. * @param string $username the wanted username
  1104. * @return boolean true if the wanted username is available
  1105. * @assert ('') === false
  1106. * @assert ('xyzxyzxyz') === true
  1107. */
  1108. public static function is_username_available($username)
  1109. {
  1110. if (empty($username)) {
  1111. return false;
  1112. }
  1113. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  1114. $sql = "SELECT username FROM $table_user
  1115. WHERE username = '".Database::escape_string($username)."'";
  1116. $res = Database::query($sql);
  1117. return Database::num_rows($res) == 0;
  1118. }
  1119. /**
  1120. * Creates a username using person's names, i.e. creates jmontoya from Julio Montoya.
  1121. * @param string $firstname The first name of the user.
  1122. * @param string $lastname The last name of the user.
  1123. * @return string Suggests a username that contains only ASCII-letters and digits,
  1124. * without check for uniqueness within the system.
  1125. * @author Julio Montoya Armas
  1126. * @author Ivan Tcholakov, 2009 - rework about internationalization.
  1127. * @assert ('','') === false
  1128. * @assert ('a','b') === 'ab'
  1129. */
  1130. public static function create_username($firstname, $lastname)
  1131. {
  1132. if (empty($firstname) && empty($lastname)) {
  1133. return false;
  1134. }
  1135. // The first letter only.
  1136. $firstname = api_substr(
  1137. preg_replace(USERNAME_PURIFIER, '', $firstname),
  1138. 0,
  1139. 1
  1140. );
  1141. //Looking for a space in the lastname
  1142. $pos = api_strpos($lastname, ' ');
  1143. if ($pos !== false) {
  1144. $lastname = api_substr($lastname, 0, $pos);
  1145. }
  1146. $lastname = preg_replace(USERNAME_PURIFIER, '', $lastname);
  1147. $username = $firstname.$lastname;
  1148. if (empty($username)) {
  1149. $username = 'user';
  1150. }
  1151. $username = URLify::transliterate($username);
  1152. return strtolower(substr($username, 0, USERNAME_MAX_LENGTH - 3));
  1153. }
  1154. /**
  1155. * Creates a unique username, using:
  1156. * 1. the first name and the last name of a user;
  1157. * 2. an already created username but not checked for uniqueness yet.
  1158. * @param string $firstname The first name of a given user. If the second parameter $lastname is NULL, then this
  1159. * parameter is treated as username which is to be checked for uniqueness and to be modified when it is necessary.
  1160. * @param string $lastname The last name of the user.
  1161. * @return string Returns a username that contains only ASCII-letters and digits, and that is unique within the system.
  1162. * Note: When the method is called several times with same parameters, its results look like the following sequence: ivan, ivan2, ivan3, ivan4, ...
  1163. * @author Ivan Tcholakov, 2009
  1164. */
  1165. public static function create_unique_username($firstname, $lastname = null)
  1166. {
  1167. if (is_null($lastname)) {
  1168. // In this case the actual input parameter $firstname should contain ASCII-letters and digits only.
  1169. // For making this method tolerant of mistakes, let us transliterate and purify the suggested input username anyway.
  1170. // So, instead of the sentence $username = $firstname; we place the following:
  1171. $username = strtolower(preg_replace(USERNAME_PURIFIER, '', $firstname));
  1172. } else {
  1173. $username = self::create_username($firstname, $lastname);
  1174. }
  1175. if (!self::is_username_available($username)) {
  1176. $i = 2;
  1177. $temp_username = substr($username, 0, USERNAME_MAX_LENGTH - strlen((string) $i)).$i;
  1178. while (!self::is_username_available($temp_username)) {
  1179. $i++;
  1180. $temp_username = substr($username, 0, USERNAME_MAX_LENGTH - strlen((string) $i)).$i;
  1181. }
  1182. $username = $temp_username;
  1183. }
  1184. $username = URLify::transliterate($username);
  1185. return $username;
  1186. }
  1187. /**
  1188. * Modifies a given username accordingly to the specification for valid characters and length.
  1189. * @param $username string The input username.
  1190. * @param bool $strict (optional) When this flag is TRUE, the result is guaranteed for full compliance,
  1191. * otherwise compliance may be partial. The default value is FALSE.
  1192. * @return string The resulting purified username.
  1193. */
  1194. public static function purify_username($username, $strict = false)
  1195. {
  1196. if ($strict) {
  1197. // 1. Conversion of unacceptable letters (latinian letters with accents for example)
  1198. // into ASCII letters in order they not to be totally removed.
  1199. // 2. Applying the strict purifier.
  1200. // 3. Length limitation.
  1201. $return = api_get_setting('login_is_email') === 'true' ? substr(preg_replace(USERNAME_PURIFIER_MAIL, '', $username), 0, USERNAME_MAX_LENGTH) : substr(preg_replace(USERNAME_PURIFIER, '', $username), 0, USERNAME_MAX_LENGTH);
  1202. $return = URLify::transliterate($return);
  1203. return $return;
  1204. }
  1205. // 1. Applying the shallow purifier.
  1206. // 2. Length limitation.
  1207. return substr(
  1208. preg_replace(USERNAME_PURIFIER_SHALLOW, '', $username),
  1209. 0,
  1210. USERNAME_MAX_LENGTH
  1211. );
  1212. }
  1213. /**
  1214. * Checks whether the user id exists in the database
  1215. *
  1216. * @param int User id
  1217. * @return bool True if user id was found, false otherwise
  1218. */
  1219. public static function is_user_id_valid($userId)
  1220. {
  1221. $resultData = Database::select(
  1222. 'COUNT(1) AS count',
  1223. Database::get_main_table(TABLE_MAIN_USER),
  1224. [
  1225. 'where' => ['id = ?' => intval($userId)]
  1226. ],
  1227. 'first'
  1228. );
  1229. if ($resultData === false) {
  1230. return false;
  1231. }
  1232. return $resultData['count'] > 0;
  1233. }
  1234. /**
  1235. * Checks whether a given username matches to the specification strictly. The empty username is assumed here as invalid.
  1236. * Mostly this function is to be used in the user interface built-in validation routines for providing feedback while usernames are enterd manually.
  1237. * @param string $username The input username.
  1238. * @return bool Returns TRUE if the username is valid, FALSE otherwise.
  1239. */
  1240. public static function is_username_valid($username)
  1241. {
  1242. return !empty($username) && $username == self::purify_username($username, true);
  1243. }
  1244. /**
  1245. * Checks whether a username is empty. If the username contains whitespace characters, such as spaces, tabulators, newlines, etc.,
  1246. * it is assumed as empty too. This function is safe for validation unpurified data (during importing).
  1247. * @param string $username The given username.
  1248. * @return bool Returns TRUE if length of the username exceeds the limit, FALSE otherwise.
  1249. */
  1250. public static function is_username_empty($username)
  1251. {
  1252. return (strlen(self::purify_username($username, false)) == 0);
  1253. }
  1254. /**
  1255. * Checks whether a username is too long or not.
  1256. * @param string $username The given username, it should contain only ASCII-letters and digits.
  1257. * @return bool Returns TRUE if length of the username exceeds the limit, FALSE otherwise.
  1258. */
  1259. public static function is_username_too_long($username)
  1260. {
  1261. return (strlen($username) > USERNAME_MAX_LENGTH);
  1262. }
  1263. /**
  1264. * Get the users by ID
  1265. * @param array $ids student ids
  1266. * @param string $active
  1267. * @param string $order
  1268. * @param string $limit
  1269. * @return array $result student information
  1270. */
  1271. public static function get_user_list_by_ids($ids = array(), $active = null, $order = null, $limit = null)
  1272. {
  1273. if (empty($ids)) {
  1274. return array();
  1275. }
  1276. $ids = is_array($ids) ? $ids : array($ids);
  1277. $ids = array_map('intval', $ids);
  1278. $ids = implode(',', $ids);
  1279. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  1280. $sql = "SELECT * FROM $tbl_user WHERE id IN ($ids)";
  1281. if (!is_null($active)) {
  1282. $sql .= ' AND active='.($active ? '1' : '0');
  1283. }
  1284. if (!is_null($order)) {
  1285. $order = Database::escape_string($order);
  1286. $sql .= ' ORDER BY '.$order;
  1287. }
  1288. if (!is_null($limit)) {
  1289. $limit = Database::escape_string($limit);
  1290. $sql .= ' LIMIT '.$limit;
  1291. }
  1292. $rs = Database::query($sql);
  1293. $result = array();
  1294. while ($row = Database::fetch_array($rs)) {
  1295. $result[] = $row;
  1296. }
  1297. return $result;
  1298. }
  1299. /**
  1300. * Get a list of users of which the given conditions match with an = 'cond'
  1301. * @param array $conditions a list of condition (example : status=>STUDENT)
  1302. * @param array $order_by a list of fields on which sort
  1303. * @return array An array with all users of the platform.
  1304. * @todo optional course code parameter, optional sorting parameters...
  1305. * @todo security filter order by
  1306. */
  1307. public static function get_user_list(
  1308. $conditions = [],
  1309. $order_by = [],
  1310. $limit_from = false,
  1311. $limit_to = false
  1312. ) {
  1313. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  1314. $userUrlTable = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  1315. $urlId = api_get_current_access_url_id();
  1316. $return_array = array();
  1317. $sql = "SELECT user.* FROM $user_table user
  1318. INNER JOIN $userUrlTable url_user
  1319. ON (user.user_id = url_user.user_id)
  1320. WHERE url_user.access_url_id = $urlId
  1321. ";
  1322. if (count($conditions) > 0) {
  1323. foreach ($conditions as $field => $value) {
  1324. $field = Database::escape_string($field);
  1325. $value = Database::escape_string($value);
  1326. $sql .= " AND $field = '$value'";
  1327. }
  1328. }
  1329. if (count($order_by) > 0) {
  1330. $sql .= ' ORDER BY '.Database::escape_string(implode(',', $order_by), null, false);
  1331. }
  1332. if (is_numeric($limit_from) && is_numeric($limit_from)) {
  1333. $limit_from = intval($limit_from);
  1334. $limit_to = intval($limit_to);
  1335. $sql .= " LIMIT $limit_from, $limit_to";
  1336. }
  1337. $sql_result = Database::query($sql);
  1338. while ($result = Database::fetch_array($sql_result)) {
  1339. $result['complete_name'] = api_get_person_name($result['firstname'], $result['lastname']);
  1340. $return_array[] = $result;
  1341. }
  1342. return $return_array;
  1343. }
  1344. /**
  1345. * Get a list of users of which the given conditions match with a LIKE '%cond%'
  1346. * @param array $conditions a list of condition (exemple : status=>STUDENT)
  1347. * @param array $order_by a list of fields on which sort
  1348. * @return array An array with all users of the platform.
  1349. * @todo optional course code parameter, optional sorting parameters...
  1350. * @todo security filter order_by
  1351. */
  1352. public static function get_user_list_like(
  1353. $conditions = array(),
  1354. $order_by = array(),
  1355. $simple_like = false,
  1356. $condition = 'AND'
  1357. ) {
  1358. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  1359. $tblAccessUrlRelUser = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  1360. $return_array = array();
  1361. $sql_query = "SELECT user.id FROM $user_table user ";
  1362. if (api_is_multiple_url_enabled()) {
  1363. $sql_query .= " INNER JOIN $tblAccessUrlRelUser auru ON auru.user_id = user.id ";
  1364. }
  1365. if (count($conditions) > 0) {
  1366. $sql_query .= ' WHERE ';
  1367. $temp_conditions = array();
  1368. foreach ($conditions as $field => $value) {
  1369. $field = Database::escape_string($field);
  1370. $value = Database::escape_string($value);
  1371. if ($simple_like) {
  1372. $temp_conditions[] = $field." LIKE '$value%'";
  1373. } else {
  1374. $temp_conditions[] = $field.' LIKE \'%'.$value.'%\'';
  1375. }
  1376. }
  1377. if (!empty($temp_conditions)) {
  1378. $sql_query .= implode(' '.$condition.' ', $temp_conditions);
  1379. }
  1380. if (api_is_multiple_url_enabled()) {
  1381. $sql_query .= ' AND auru.access_url_id = '.api_get_current_access_url_id();
  1382. }
  1383. } else {
  1384. if (api_is_multiple_url_enabled()) {
  1385. $sql_query .= ' WHERE auru.access_url_id = '.api_get_current_access_url_id();
  1386. }
  1387. }
  1388. if (count($order_by) > 0) {
  1389. $sql_query .= ' ORDER BY '.Database::escape_string(implode(',', $order_by), null, false);
  1390. }
  1391. $sql_result = Database::query($sql_query);
  1392. while ($result = Database::fetch_array($sql_result)) {
  1393. $userInfo = api_get_user_info($result['id']);
  1394. $return_array[] = $userInfo;
  1395. }
  1396. return $return_array;
  1397. }
  1398. /**
  1399. * Get user picture URL or path from user ID (returns an array).
  1400. * The return format is a complete path, enabling recovery of the directory
  1401. * with dirname() or the file with basename(). This also works for the
  1402. * functions dealing with the user's productions, as they are located in
  1403. * the same directory.
  1404. * @param integer $id User ID
  1405. * @param string $type Type of path to return (can be 'system', 'web')
  1406. * @param array $userInfo user information to avoid query the DB
  1407. * returns the /main/img/unknown.jpg image set it at true
  1408. *
  1409. * @return array Array of 2 elements: 'dir' and 'file' which contain
  1410. * the dir and file as the name implies if image does not exist it will
  1411. * return the unknow image if anonymous parameter is true if not it returns an empty array
  1412. */
  1413. public static function get_user_picture_path_by_id(
  1414. $id,
  1415. $type = 'web',
  1416. $userInfo = []
  1417. ) {
  1418. switch ($type) {
  1419. case 'system': // Base: absolute system path.
  1420. $base = api_get_path(SYS_CODE_PATH);
  1421. break;
  1422. case 'web': // Base: absolute web path.
  1423. default:
  1424. $base = api_get_path(WEB_CODE_PATH);
  1425. break;
  1426. }
  1427. $anonymousPath = array(
  1428. 'dir' => $base.'img/',
  1429. 'file' => 'unknown.jpg',
  1430. 'email' => ''
  1431. );
  1432. if (empty($id) || empty($type)) {
  1433. return $anonymousPath;
  1434. }
  1435. $id = intval($id);
  1436. if (empty($userInfo)) {
  1437. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  1438. $sql = "SELECT email, picture_uri FROM $user_table
  1439. WHERE id=".$id;
  1440. $res = Database::query($sql);
  1441. if (!Database::num_rows($res)) {
  1442. return $anonymousPath;
  1443. }
  1444. $user = Database::fetch_array($res);
  1445. if (empty($user['picture_uri'])) {
  1446. return $anonymousPath;
  1447. }
  1448. } else {
  1449. $user = $userInfo;
  1450. }
  1451. $pictureFilename = trim($user['picture_uri']);
  1452. $dir = self::getUserPathById($id, $type);
  1453. return array(
  1454. 'dir' => $dir,
  1455. 'file' => $pictureFilename,
  1456. 'email' => $user['email']
  1457. );
  1458. }
  1459. /**
  1460. * *** READ BEFORE REVIEW THIS FUNCTION ***
  1461. * This function is a exact copy from get_user_picture_path_by_id() and it was create it to avoid
  1462. * a recursive calls for get_user_picture_path_by_id() in another functions when you update a user picture
  1463. * in same script, so you can find this function usage in update_user_picture() function.
  1464. *
  1465. * @param integer $id User ID
  1466. * @param string $type Type of path to return (can be 'system', 'web')
  1467. * @param array $userInfo user information to avoid query the DB
  1468. * returns the /main/img/unknown.jpg image set it at true
  1469. *
  1470. * @return array Array of 2 elements: 'dir' and 'file' which contain
  1471. * the dir and file as the name implies if image does not exist it will
  1472. * return the unknown image if anonymous parameter is true if not it returns an empty array
  1473. */
  1474. public static function getUserPicturePathById($id, $type = 'web', $userInfo = [])
  1475. {
  1476. switch ($type) {
  1477. case 'system': // Base: absolute system path.
  1478. $base = api_get_path(SYS_CODE_PATH);
  1479. break;
  1480. case 'web': // Base: absolute web path.
  1481. default:
  1482. $base = api_get_path(WEB_CODE_PATH);
  1483. break;
  1484. }
  1485. $anonymousPath = array(
  1486. 'dir' => $base.'img/',
  1487. 'file' => 'unknown.jpg',
  1488. 'email' => ''
  1489. );
  1490. if (empty($id) || empty($type)) {
  1491. return $anonymousPath;
  1492. }
  1493. $id = intval($id);
  1494. if (empty($userInfo)) {
  1495. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  1496. $sql = "SELECT email, picture_uri FROM $user_table WHERE id=$id";
  1497. $res = Database::query($sql);
  1498. if (!Database::num_rows($res)) {
  1499. return $anonymousPath;
  1500. }
  1501. $user = Database::fetch_array($res);
  1502. if (empty($user['picture_uri'])) {
  1503. return $anonymousPath;
  1504. }
  1505. } else {
  1506. $user = $userInfo;
  1507. }
  1508. $pictureFilename = trim($user['picture_uri']);
  1509. $dir = self::getUserPathById($id, $type);
  1510. return array(
  1511. 'dir' => $dir,
  1512. 'file' => $pictureFilename,
  1513. 'email' => $user['email']
  1514. );
  1515. }
  1516. /**
  1517. * Get user path from user ID (returns an array).
  1518. * The return format is a complete path to a folder ending with "/"
  1519. * In case the first level of subdirectory of users/ does not exist, the
  1520. * function will attempt to create it. Probably not the right place to do it
  1521. * but at least it avoids headaches in many other places.
  1522. * @param integer $id User ID
  1523. * @param string $type Type of path to return (can be 'system', 'web', 'last')
  1524. * @return string User folder path (i.e. /var/www/chamilo/app/upload/users/1/1/)
  1525. */
  1526. public static function getUserPathById($id, $type)
  1527. {
  1528. $id = intval($id);
  1529. if (!$id) {
  1530. return null;
  1531. }
  1532. $userPath = "users/$id/";
  1533. if (api_get_setting('split_users_upload_directory') === 'true') {
  1534. $userPath = 'users/'.substr((string) $id, 0, 1).'/'.$id.'/';
  1535. // In exceptional cases, on some portals, the intermediate base user
  1536. // directory might not have been created. Make sure it is before
  1537. // going further.
  1538. $rootPath = api_get_path(SYS_UPLOAD_PATH).'users/'.substr((string) $id, 0, 1);
  1539. if (!is_dir($rootPath)) {
  1540. $perm = api_get_permissions_for_new_directories();
  1541. try {
  1542. mkdir($rootPath, $perm);
  1543. } catch (Exception $e) {
  1544. error_log($e->getMessage());
  1545. }
  1546. }
  1547. }
  1548. switch ($type) {
  1549. case 'system': // Base: absolute system path.
  1550. $userPath = api_get_path(SYS_UPLOAD_PATH).$userPath;
  1551. break;
  1552. case 'web': // Base: absolute web path.
  1553. $userPath = api_get_path(WEB_UPLOAD_PATH).$userPath;
  1554. break;
  1555. case 'last': // Only the last part starting with users/
  1556. break;
  1557. }
  1558. return $userPath;
  1559. }
  1560. /**
  1561. * Gets the current user image
  1562. * @param string $user_id
  1563. * @param int $size it can be USER_IMAGE_SIZE_SMALL,
  1564. * USER_IMAGE_SIZE_MEDIUM, USER_IMAGE_SIZE_BIG or USER_IMAGE_SIZE_ORIGINAL
  1565. * @param bool $addRandomId
  1566. * @param array $userInfo to avoid query the DB
  1567. *
  1568. * @return string
  1569. */
  1570. public static function getUserPicture(
  1571. $user_id,
  1572. $size = USER_IMAGE_SIZE_MEDIUM,
  1573. $addRandomId = true,
  1574. $userInfo = []
  1575. ) {
  1576. // Make sure userInfo is defined. Otherwise, define it!
  1577. if (empty($userInfo) || !is_array($userInfo) || count($userInfo) == 0) {
  1578. if (empty($user_id)) {
  1579. return '';
  1580. } else {
  1581. $userInfo = api_get_user_info($user_id);
  1582. }
  1583. }
  1584. $imageWebPath = self::get_user_picture_path_by_id(
  1585. $user_id,
  1586. 'web',
  1587. $userInfo
  1588. );
  1589. $pictureWebFile = $imageWebPath['file'];
  1590. $pictureWebDir = $imageWebPath['dir'];
  1591. $pictureAnonymousSize = '128';
  1592. $gravatarSize = 22;
  1593. $realSizeName = 'small_';
  1594. switch ($size) {
  1595. case USER_IMAGE_SIZE_SMALL:
  1596. $pictureAnonymousSize = '32';
  1597. $realSizeName = 'small_';
  1598. $gravatarSize = 32;
  1599. break;
  1600. case USER_IMAGE_SIZE_MEDIUM:
  1601. $pictureAnonymousSize = '64';
  1602. $realSizeName = 'medium_';
  1603. $gravatarSize = 64;
  1604. break;
  1605. case USER_IMAGE_SIZE_ORIGINAL:
  1606. $pictureAnonymousSize = '128';
  1607. $realSizeName = '';
  1608. $gravatarSize = 128;
  1609. break;
  1610. case USER_IMAGE_SIZE_BIG:
  1611. $pictureAnonymousSize = '128';
  1612. $realSizeName = 'big_';
  1613. $gravatarSize = 128;
  1614. break;
  1615. }
  1616. $gravatarEnabled = api_get_setting('gravatar_enabled');
  1617. $anonymousPath = Display::returnIconPath('unknown.png', $pictureAnonymousSize);
  1618. if ($pictureWebFile == 'unknown.jpg' || empty($pictureWebFile)) {
  1619. if ($gravatarEnabled === 'true') {
  1620. $file = self::getGravatar(
  1621. $imageWebPath['email'],
  1622. $gravatarSize,
  1623. api_get_setting('gravatar_type')
  1624. );
  1625. if ($addRandomId) {
  1626. $file .= '&rand='.uniqid();
  1627. }
  1628. return $file;
  1629. }
  1630. return $anonymousPath;
  1631. }
  1632. $pictureSysPath = self::get_user_picture_path_by_id($user_id, 'system');
  1633. $file = $pictureSysPath['dir'].$realSizeName.$pictureWebFile;
  1634. $picture = '';
  1635. if (file_exists($file)) {
  1636. $picture = $pictureWebDir.$realSizeName.$pictureWebFile;
  1637. } else {
  1638. $file = $pictureSysPath['dir'].$pictureWebFile;
  1639. if (file_exists($file) && !is_dir($file)) {
  1640. $picture = $pictureWebFile['dir'].$pictureWebFile;
  1641. }
  1642. }
  1643. if (empty($picture)) {
  1644. return $anonymousPath;
  1645. }
  1646. if ($addRandomId) {
  1647. $picture .= '?rand='.uniqid();
  1648. }
  1649. return $picture;
  1650. }
  1651. /**
  1652. * Creates new user photos in various sizes of a user, or deletes user photos.
  1653. * Note: This method relies on configuration setting from main/inc/conf/profile.conf.php
  1654. * @param int $user_id The user internal identification number.
  1655. * @param string $file The common file name for the newly created photos.
  1656. * It will be checked and modified for compatibility with the file system.
  1657. * If full name is provided, path component is ignored.
  1658. * If an empty name is provided, then old user photos are deleted only,
  1659. * @see UserManager::delete_user_picture() as the prefered way for deletion.
  1660. * @param string $source_file The full system name of the image from which user photos will be created.
  1661. * @param string $cropParameters Optional string that contents "x,y,width,height" of a cropped image format
  1662. * @return mixed Returns the resulting common file name of created images which usually should be stored in database.
  1663. * When deletion is requested returns empty string. In case of internal error or negative validation returns FALSE.
  1664. */
  1665. public static function update_user_picture(
  1666. $user_id,
  1667. $file = null,
  1668. $source_file = null,
  1669. $cropParameters = ''
  1670. ) {
  1671. if (empty($user_id)) {
  1672. return false;
  1673. }
  1674. $delete = empty($file);
  1675. if (empty($source_file)) {
  1676. $source_file = $file;
  1677. }
  1678. // User-reserved directory where photos have to be placed.
  1679. $path_info = self::getUserPicturePathById($user_id, 'system');
  1680. $path = $path_info['dir'];
  1681. // If this directory does not exist - we create it.
  1682. if (!file_exists($path)) {
  1683. mkdir($path, api_get_permissions_for_new_directories(), true);
  1684. }
  1685. // The old photos (if any).
  1686. $old_file = $path_info['file'];
  1687. // Let us delete them.
  1688. if ($old_file != 'unknown.jpg') {
  1689. if (KEEP_THE_OLD_IMAGE_AFTER_CHANGE) {
  1690. $prefix = 'saved_'.date('Y_m_d_H_i_s').'_'.uniqid('').'_';
  1691. @rename($path.'small_'.$old_file, $path.$prefix.'small_'.$old_file);
  1692. @rename($path.'medium_'.$old_file, $path.$prefix.'medium_'.$old_file);
  1693. @rename($path.'big_'.$old_file, $path.$prefix.'big_'.$old_file);
  1694. @rename($path.$old_file, $path.$prefix.$old_file);
  1695. } else {
  1696. @unlink($path.'small_'.$old_file);
  1697. @unlink($path.'medium_'.$old_file);
  1698. @unlink($path.'big_'.$old_file);
  1699. @unlink($path.$old_file);
  1700. }
  1701. }
  1702. // Exit if only deletion has been requested. Return an empty picture name.
  1703. if ($delete) {
  1704. return '';
  1705. }
  1706. // Validation 2.
  1707. $allowed_types = api_get_supported_image_extensions();
  1708. $file = str_replace('\\', '/', $file);
  1709. $filename = (($pos = strrpos($file, '/')) !== false) ? substr($file, $pos + 1) : $file;
  1710. $extension = strtolower(substr(strrchr($filename, '.'), 1));
  1711. if (!in_array($extension, $allowed_types)) {
  1712. return false;
  1713. }
  1714. // This is the common name for the new photos.
  1715. if (KEEP_THE_NAME_WHEN_CHANGE_IMAGE && $old_file != 'unknown.jpg') {
  1716. $old_extension = strtolower(substr(strrchr($old_file, '.'), 1));
  1717. $filename = in_array($old_extension, $allowed_types) ? substr($old_file, 0, -strlen($old_extension)) : $old_file;
  1718. $filename = (substr($filename, -1) == '.') ? $filename.$extension : $filename.'.'.$extension;
  1719. } else {
  1720. $filename = api_replace_dangerous_char($filename);
  1721. if (PREFIX_IMAGE_FILENAME_WITH_UID) {
  1722. $filename = uniqid('').'_'.$filename;
  1723. }
  1724. // We always prefix user photos with user ids, so on setting
  1725. // api_get_setting('split_users_upload_directory') === 'true'
  1726. // the correspondent directories to be found successfully.
  1727. $filename = $user_id.'_'.$filename;
  1728. }
  1729. //Crop the image to adjust 1:1 ratio
  1730. $image = new Image($source_file);
  1731. $image->crop($cropParameters);
  1732. // Storing the new photos in 4 versions with various sizes.
  1733. $userPath = self::getUserPathById($user_id, 'system');
  1734. // If this path does not exist - we create it.
  1735. if (!file_exists($userPath)) {
  1736. mkdir($userPath, api_get_permissions_for_new_directories(), true);
  1737. }
  1738. $small = new Image($source_file);
  1739. $small->resize(32);
  1740. $small->send_image($userPath.'small_'.$filename);
  1741. $medium = new Image($source_file);
  1742. $medium->resize(85);
  1743. $medium->send_image($userPath.'medium_'.$filename);
  1744. $normal = new Image($source_file);
  1745. $normal->resize(200);
  1746. $normal->send_image($userPath.$filename);
  1747. $big = new Image($source_file); // This is the original picture.
  1748. $big->send_image($userPath.'big_'.$filename);
  1749. $result = $small && $medium && $normal && $big;
  1750. return $result ? $filename : false;
  1751. }
  1752. /**
  1753. * Update User extra field file type into {user_folder}/{$extra_field}
  1754. * @param int $user_id The user internal identification number
  1755. * @param string $extra_field The $extra_field The extra field name
  1756. * @param null $file The filename
  1757. * @param null $source_file The temporal filename
  1758. * @return bool|null return filename if success, but false
  1759. */
  1760. public static function update_user_extra_file(
  1761. $user_id,
  1762. $extra_field = '',
  1763. $file = null,
  1764. $source_file = null
  1765. ) {
  1766. // Add Filter
  1767. $source_file = Security::filter_filename($source_file);
  1768. $file = Security::filter_filename($file);
  1769. if (empty($user_id)) {
  1770. return false;
  1771. }
  1772. if (empty($source_file)) {
  1773. $source_file = $file;
  1774. }
  1775. // User-reserved directory where extra file have to be placed.
  1776. $path_info = self::get_user_picture_path_by_id($user_id, 'system');
  1777. $path = $path_info['dir'];
  1778. if (!empty($extra_field)) {
  1779. $path .= $extra_field.'/';
  1780. }
  1781. // If this directory does not exist - we create it.
  1782. if (!file_exists($path)) {
  1783. @mkdir($path, api_get_permissions_for_new_directories(), true);
  1784. }
  1785. if (filter_extension($file)) {
  1786. if (@move_uploaded_file($source_file, $path.$file)) {
  1787. if ($extra_field) {
  1788. return $extra_field.'/'.$file;
  1789. } else {
  1790. return $file;
  1791. }
  1792. }
  1793. }
  1794. return false; // this should be returned if anything went wrong with the upload
  1795. }
  1796. /**
  1797. * Deletes user photos.
  1798. * Note: This method relies on configuration setting from main/inc/conf/profile.conf.php
  1799. * @param int $user_id The user internal identification number.
  1800. * @return mixed Returns empty string on success, FALSE on error.
  1801. */
  1802. public static function delete_user_picture($user_id)
  1803. {
  1804. return self::update_user_picture($user_id);
  1805. }
  1806. /**
  1807. * Returns an XHTML formatted list of productions for a user, or FALSE if he
  1808. * doesn't have any.
  1809. *
  1810. * If there has been a request to remove a production, the function will return
  1811. * without building the list unless forced to do so by the optional second
  1812. * parameter. This increases performance by avoiding to read through the
  1813. * productions on the filesystem before the removal request has been carried
  1814. * out because they'll have to be re-read afterwards anyway.
  1815. *
  1816. * @param int $user_id User id
  1817. * @param bool $force Optional parameter to force building after a removal request
  1818. * @param bool $showDelete
  1819. *
  1820. * @return string A string containing the XHTML code to display the production list, or FALSE
  1821. */
  1822. public static function build_production_list($user_id, $force = false, $showDelete = false)
  1823. {
  1824. if (!$force && !empty($_POST['remove_production'])) {
  1825. return true; // postpone reading from the filesystem
  1826. }
  1827. $productions = self::get_user_productions($user_id);
  1828. if (empty($productions)) {
  1829. return false;
  1830. }
  1831. $production_dir = self::getUserPathById($user_id, 'web');
  1832. $del_image = Display::returnIconPath('delete.png');
  1833. $add_image = Display::returnIconPath('archive.png');
  1834. $del_text = get_lang('Delete');
  1835. $production_list = '';
  1836. if (count($productions) > 0) {
  1837. $production_list = '<div class="files-production"><ul id="productions">';
  1838. foreach ($productions as $file) {
  1839. $production_list .= '<li><img src="'.$add_image.'" /><a href="'.$production_dir.urlencode($file).'" target="_blank">'.htmlentities($file).'</a>';
  1840. if ($showDelete) {
  1841. $production_list .= '&nbsp;&nbsp;<input style="width:16px;" type="image" name="remove_production['.urlencode($file).']" src="'.$del_image.'" alt="'.$del_text.'" title="'.$del_text.' '.htmlentities($file).'" onclick="javascript: return confirmation(\''.htmlentities($file).'\');" /></li>';
  1842. }
  1843. }
  1844. $production_list .= '</ul></div>';
  1845. }
  1846. return $production_list;
  1847. }
  1848. /**
  1849. * Returns an array with the user's productions.
  1850. *
  1851. * @param $user_id User id
  1852. * @return array An array containing the user's productions
  1853. */
  1854. public static function get_user_productions($user_id)
  1855. {
  1856. $production_repository = self::getUserPathById($user_id, 'system');
  1857. $productions = array();
  1858. if (is_dir($production_repository)) {
  1859. $handle = opendir($production_repository);
  1860. while ($file = readdir($handle)) {
  1861. if ($file == '.' ||
  1862. $file == '..' ||
  1863. $file == '.htaccess' ||
  1864. is_dir($production_repository.$file)
  1865. ) {
  1866. // skip current/parent directory and .htaccess
  1867. continue;
  1868. }
  1869. if (preg_match('/('.$user_id.'|[0-9a-f]{13}|saved)_.+\.(png|jpg|jpeg|gif)$/i', $file)) {
  1870. // User's photos should not be listed as productions.
  1871. continue;
  1872. }
  1873. $productions[] = $file;
  1874. }
  1875. }
  1876. return $productions;
  1877. }
  1878. /**
  1879. * Remove a user production.
  1880. *
  1881. * @param int $user_id User id
  1882. * @param string $production The production to remove
  1883. */
  1884. public static function remove_user_production($user_id, $production)
  1885. {
  1886. $production_path = self::get_user_picture_path_by_id($user_id, 'system');
  1887. $production_file = $production_path['dir'].$production;
  1888. if (is_file($production_file)) {
  1889. unlink($production_file);
  1890. return true;
  1891. }
  1892. return false;
  1893. }
  1894. /**
  1895. * Update an extra field value for a given user
  1896. * @param integer $userId User ID
  1897. * @param string $variable Field variable name
  1898. * @param string $value Field value
  1899. *
  1900. * @return boolean true if field updated, false otherwise
  1901. */
  1902. public static function update_extra_field_value($userId, $variable, $value = '')
  1903. {
  1904. $extraFieldValue = new ExtraFieldValue('user');
  1905. $params = [
  1906. 'item_id' => $userId,
  1907. 'variable' => $variable,
  1908. 'value' => $value
  1909. ];
  1910. return $extraFieldValue->save($params);
  1911. }
  1912. /**
  1913. * Get an array of extra fields with field details (type, default value and options)
  1914. * @param integer Offset (from which row)
  1915. * @param integer Number of items
  1916. * @param integer Column on which sorting is made
  1917. * @param string Sorting direction
  1918. * @param boolean Optional. Whether we get all the fields or just the visible ones
  1919. * @param int Optional. Whether we get all the fields with field_filter 1 or 0 or everything
  1920. * @return array Extra fields details (e.g. $list[2]['type'], $list[4]['options'][2]['title']
  1921. */
  1922. public static function get_extra_fields(
  1923. $from = 0,
  1924. $number_of_items = 0,
  1925. $column = 5,
  1926. $direction = 'ASC',
  1927. $all_visibility = true,
  1928. $field_filter = null
  1929. ) {
  1930. $fields = array();
  1931. $t_uf = Database::get_main_table(TABLE_EXTRA_FIELD);
  1932. $t_ufo = Database::get_main_table(TABLE_EXTRA_FIELD_OPTIONS);
  1933. $columns = array(
  1934. 'id',
  1935. 'variable',
  1936. 'field_type',
  1937. 'display_text',
  1938. 'default_value',
  1939. 'field_order',
  1940. 'filter'
  1941. );
  1942. $column = intval($column);
  1943. $sort_direction = '';
  1944. if (in_array(strtoupper($direction), array('ASC', 'DESC'))) {
  1945. $sort_direction = strtoupper($direction);
  1946. }
  1947. $extraFieldType = EntityExtraField::USER_FIELD_TYPE;
  1948. $sqlf = "SELECT * FROM $t_uf WHERE extra_field_type = $extraFieldType ";
  1949. if (!$all_visibility) {
  1950. $sqlf .= " AND visible_to_self = 1 ";
  1951. }
  1952. if (!is_null($field_filter)) {
  1953. $field_filter = intval($field_filter);
  1954. $sqlf .= " AND filter = $field_filter ";
  1955. }
  1956. $sqlf .= " ORDER BY ".$columns[$column]." $sort_direction ";
  1957. if ($number_of_items != 0) {
  1958. $sqlf .= " LIMIT ".intval($from).','.intval($number_of_items);
  1959. }
  1960. $resf = Database::query($sqlf);
  1961. if (Database::num_rows($resf) > 0) {
  1962. while ($rowf = Database::fetch_array($resf)) {
  1963. $fields[$rowf['id']] = array(
  1964. 0 => $rowf['id'],
  1965. 1 => $rowf['variable'],
  1966. 2 => $rowf['field_type'],
  1967. 3 => empty($rowf['display_text']) ? '' : $rowf['display_text'],
  1968. 4 => $rowf['default_value'],
  1969. 5 => $rowf['field_order'],
  1970. 6 => $rowf['visible_to_self'],
  1971. 7 => $rowf['changeable'],
  1972. 8 => $rowf['filter'],
  1973. 9 => array(),
  1974. 10 => '<a name="'.$rowf['id'].'"></a>',
  1975. );
  1976. $sqlo = "SELECT * FROM $t_ufo
  1977. WHERE field_id = ".$rowf['id']."
  1978. ORDER BY option_order ASC";
  1979. $reso = Database::query($sqlo);
  1980. if (Database::num_rows($reso) > 0) {
  1981. while ($rowo = Database::fetch_array($reso)) {
  1982. $fields[$rowf['id']][9][$rowo['id']] = array(
  1983. 0 => $rowo['id'],
  1984. 1 => $rowo['option_value'],
  1985. 2 => empty($rowo['display_text']) ? '' : $rowo['display_text'],
  1986. 3 => $rowo['option_order']
  1987. );
  1988. }
  1989. }
  1990. }
  1991. }
  1992. return $fields;
  1993. }
  1994. /**
  1995. * Build a list of extra file already uploaded in $user_folder/{$extra_field}/
  1996. * @param $user_id
  1997. * @param $extra_field
  1998. * @param bool $force
  1999. * @param bool $showDelete
  2000. * @return bool|string
  2001. */
  2002. public static function build_user_extra_file_list(
  2003. $user_id,
  2004. $extra_field,
  2005. $force = false,
  2006. $showDelete = false
  2007. ) {
  2008. if (!$force && !empty($_POST['remove_'.$extra_field])) {
  2009. return true; // postpone reading from the filesystem
  2010. }
  2011. $extra_files = self::get_user_extra_files($user_id, $extra_field);
  2012. if (empty($extra_files)) {
  2013. return false;
  2014. }
  2015. $path_info = self::get_user_picture_path_by_id($user_id, 'web');
  2016. $path = $path_info['dir'];
  2017. $del_image = Display::returnIconPath('delete.png');
  2018. $del_text = get_lang('Delete');
  2019. $extra_file_list = '';
  2020. if (count($extra_files) > 0) {
  2021. $extra_file_list = '<div class="files-production"><ul id="productions">';
  2022. foreach ($extra_files as $file) {
  2023. $filename = substr($file, strlen($extra_field) + 1);
  2024. $extra_file_list .= '<li>'.Display::return_icon('archive.png').'<a href="'.$path.$extra_field.'/'.urlencode($filename).'" target="_blank">'.htmlentities($filename).'</a> ';
  2025. if ($showDelete) {
  2026. $extra_file_list .= '<input style="width:16px;" type="image" name="remove_extra_'.$extra_field.'['.urlencode($file).']" src="'.$del_image.'" alt="'.$del_text.'" title="'.$del_text.' '.htmlentities($filename).'" onclick="javascript: return confirmation(\''.htmlentities($filename).'\');" /></li>';
  2027. }
  2028. }
  2029. $extra_file_list .= '</ul></div>';
  2030. }
  2031. return $extra_file_list;
  2032. }
  2033. /**
  2034. * Get valid filenames in $user_folder/{$extra_field}/
  2035. * @param $user_id
  2036. * @param $extra_field
  2037. * @param bool $full_path
  2038. * @return array
  2039. */
  2040. public static function get_user_extra_files($user_id, $extra_field, $full_path = false)
  2041. {
  2042. if (!$full_path) {
  2043. // Nothing to do
  2044. } else {
  2045. $path_info = self::get_user_picture_path_by_id($user_id, 'system');
  2046. $path = $path_info['dir'];
  2047. }
  2048. $extra_data = self::get_extra_user_data_by_field($user_id, $extra_field);
  2049. $extra_files = $extra_data[$extra_field];
  2050. if (is_array($extra_files)) {
  2051. foreach ($extra_files as $key => $value) {
  2052. if (!$full_path) {
  2053. // Relative path from user folder
  2054. $files[] = $value;
  2055. } else {
  2056. $files[] = $path.$value;
  2057. }
  2058. }
  2059. } elseif (!empty($extra_files)) {
  2060. if (!$full_path) {
  2061. // Relative path from user folder
  2062. $files[] = $extra_files;
  2063. } else {
  2064. $files[] = $path.$extra_files;
  2065. }
  2066. }
  2067. return $files; // can be an empty array
  2068. }
  2069. /**
  2070. * Remove an {$extra_file} from the user folder $user_folder/{$extra_field}/
  2071. * @param $user_id
  2072. * @param $extra_field
  2073. * @param $extra_file
  2074. * @return bool
  2075. */
  2076. public static function remove_user_extra_file($user_id, $extra_field, $extra_file)
  2077. {
  2078. $extra_file = Security::filter_filename($extra_file);
  2079. $path_info = self::get_user_picture_path_by_id($user_id, 'system');
  2080. if (strpos($extra_file, $extra_field) !== false) {
  2081. $path_extra_file = $path_info['dir'].$extra_file;
  2082. } else {
  2083. $path_extra_file = $path_info['dir'].$extra_field.'/'.$extra_file;
  2084. }
  2085. if (is_file($path_extra_file)) {
  2086. unlink($path_extra_file);
  2087. return true;
  2088. }
  2089. return false;
  2090. }
  2091. /**
  2092. * Creates a new extra field
  2093. * @param string $variable Field's internal variable name
  2094. * @param int $fieldType Field's type
  2095. * @param string $displayText Field's language var name
  2096. * @param string $default Field's default value
  2097. * @return int
  2098. */
  2099. public static function create_extra_field(
  2100. $variable,
  2101. $fieldType,
  2102. $displayText,
  2103. $default
  2104. ) {
  2105. $extraField = new ExtraField('user');
  2106. $params = [
  2107. 'variable' => $variable,
  2108. 'field_type' => $fieldType,
  2109. 'display_text' => $displayText,
  2110. 'default_value' => $default
  2111. ];
  2112. return $extraField->save($params);
  2113. }
  2114. /**
  2115. * Check if a field is available
  2116. * @param string $variable
  2117. * @return boolean
  2118. */
  2119. public static function is_extra_field_available($variable)
  2120. {
  2121. $extraField = new ExtraField('user');
  2122. $data = $extraField->get_handler_field_info_by_field_variable($variable);
  2123. return !empty($data) ? true : false;
  2124. }
  2125. /**
  2126. * Gets user extra fields data
  2127. * @param integer User ID
  2128. * @param boolean Whether to prefix the fields indexes with "extra_" (might be used by formvalidator)
  2129. * @param boolean Whether to return invisible fields as well
  2130. * @param boolean Whether to split multiple-selection fields or not
  2131. * @return array Array of fields => value for the given user
  2132. */
  2133. public static function get_extra_user_data(
  2134. $user_id,
  2135. $prefix = false,
  2136. $all_visibility = true,
  2137. $splitmultiple = false,
  2138. $field_filter = null
  2139. ) {
  2140. // A sanity check.
  2141. if (empty($user_id)) {
  2142. $user_id = 0;
  2143. } else {
  2144. if ($user_id != strval(intval($user_id)))
  2145. return array();
  2146. }
  2147. $extra_data = array();
  2148. $t_uf = Database::get_main_table(TABLE_EXTRA_FIELD);
  2149. $t_ufv = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  2150. $user_id = intval($user_id);
  2151. $sql = "SELECT f.id as id, f.variable as fvar, f.field_type as type
  2152. FROM $t_uf f
  2153. WHERE
  2154. extra_field_type = ".EntityExtraField::USER_FIELD_TYPE."
  2155. ";
  2156. $filter_cond = '';
  2157. if (!$all_visibility) {
  2158. if (isset($field_filter)) {
  2159. $field_filter = intval($field_filter);
  2160. $filter_cond .= " AND filter = $field_filter ";
  2161. }
  2162. $sql .= " AND f.visible_to_self = 1 $filter_cond ";
  2163. } else {
  2164. if (isset($field_filter)) {
  2165. $field_filter = intval($field_filter);
  2166. $sql .= " AND filter = $field_filter ";
  2167. }
  2168. }
  2169. $sql .= " ORDER BY f.field_order";
  2170. $res = Database::query($sql);
  2171. if (Database::num_rows($res) > 0) {
  2172. while ($row = Database::fetch_array($res)) {
  2173. if ($row['type'] == self::USER_FIELD_TYPE_TAG) {
  2174. $tags = self::get_user_tags_to_string($user_id, $row['id'], false);
  2175. $extra_data['extra_'.$row['fvar']] = $tags;
  2176. } else {
  2177. $sqlu = "SELECT value as fval
  2178. FROM $t_ufv
  2179. WHERE field_id=".$row['id']." AND item_id = ".$user_id;
  2180. $resu = Database::query($sqlu);
  2181. // get default value
  2182. $sql_df = "SELECT default_value as fval_df FROM $t_uf
  2183. WHERE id=".$row['id'];
  2184. $res_df = Database::query($sql_df);
  2185. if (Database::num_rows($resu) > 0) {
  2186. $rowu = Database::fetch_array($resu);
  2187. $fval = $rowu['fval'];
  2188. if ($row['type'] == self::USER_FIELD_TYPE_SELECT_MULTIPLE) {
  2189. $fval = explode(';', $rowu['fval']);
  2190. }
  2191. } else {
  2192. $row_df = Database::fetch_array($res_df);
  2193. $fval = $row_df['fval_df'];
  2194. }
  2195. // We get here (and fill the $extra_data array) even if there
  2196. // is no user with data (we fill it with default values)
  2197. if ($prefix) {
  2198. if ($row['type'] == self::USER_FIELD_TYPE_RADIO) {
  2199. $extra_data['extra_'.$row['fvar']]['extra_'.$row['fvar']] = $fval;
  2200. } else {
  2201. $extra_data['extra_'.$row['fvar']] = $fval;
  2202. }
  2203. } else {
  2204. if ($row['type'] == self::USER_FIELD_TYPE_RADIO) {
  2205. $extra_data['extra_'.$row['fvar']]['extra_'.$row['fvar']] = $fval;
  2206. } else {
  2207. $extra_data[$row['fvar']] = $fval;
  2208. }
  2209. }
  2210. }
  2211. }
  2212. }
  2213. return $extra_data;
  2214. }
  2215. /** Get extra user data by field
  2216. * @param int user ID
  2217. * @param string the internal variable name of the field
  2218. * @return array with extra data info of a user i.e array('field_variable'=>'value');
  2219. */
  2220. public static function get_extra_user_data_by_field(
  2221. $user_id,
  2222. $field_variable,
  2223. $prefix = false,
  2224. $all_visibility = true,
  2225. $splitmultiple = false
  2226. ) {
  2227. // A sanity check.
  2228. if (empty($user_id)) {
  2229. $user_id = 0;
  2230. } else {
  2231. if ($user_id != strval(intval($user_id)))
  2232. return array();
  2233. }
  2234. $extra_data = array();
  2235. $t_uf = Database::get_main_table(TABLE_EXTRA_FIELD);
  2236. $t_ufv = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  2237. $user_id = intval($user_id);
  2238. $sql = "SELECT f.id as id, f.variable as fvar, f.field_type as type
  2239. FROM $t_uf f
  2240. WHERE f.variable = '$field_variable' ";
  2241. if (!$all_visibility) {
  2242. $sql .= " AND f.visible_to_self = 1 ";
  2243. }
  2244. $sql .= " AND extra_field_type = ".EntityExtraField::USER_FIELD_TYPE;
  2245. $sql .= " ORDER BY f.field_order";
  2246. $res = Database::query($sql);
  2247. if (Database::num_rows($res) > 0) {
  2248. while ($row = Database::fetch_array($res)) {
  2249. $sqlu = "SELECT value as fval FROM $t_ufv v
  2250. INNER JOIN $t_uf f
  2251. ON (v.field_id = f.id)
  2252. WHERE
  2253. extra_field_type = ".EntityExtraField::USER_FIELD_TYPE." AND
  2254. field_id = ".$row['id']." AND
  2255. item_id = ".$user_id;
  2256. $resu = Database::query($sqlu);
  2257. $fval = '';
  2258. if (Database::num_rows($resu) > 0) {
  2259. $rowu = Database::fetch_array($resu);
  2260. $fval = $rowu['fval'];
  2261. if ($row['type'] == self::USER_FIELD_TYPE_SELECT_MULTIPLE) {
  2262. $fval = explode(';', $rowu['fval']);
  2263. }
  2264. }
  2265. if ($prefix) {
  2266. $extra_data['extra_'.$row['fvar']] = $fval;
  2267. } else {
  2268. $extra_data[$row['fvar']] = $fval;
  2269. }
  2270. }
  2271. }
  2272. return $extra_data;
  2273. }
  2274. /**
  2275. * Get the extra field information for a certain field (the options as well)
  2276. * @param int $variable The name of the field we want to know everything about
  2277. * @return array Array containing all the information about the extra profile field
  2278. * (first level of array contains field details, then 'options' sub-array contains options details,
  2279. * as returned by the database)
  2280. * @author Julio Montoya
  2281. * @since v1.8.6
  2282. */
  2283. public static function get_extra_field_information_by_name($variable)
  2284. {
  2285. $extraField = new ExtraField('user');
  2286. return $extraField->get_handler_field_info_by_field_variable($variable);
  2287. }
  2288. /**
  2289. * Get the extra field information for user tag (the options as well)
  2290. * @param int $variable The name of the field we want to know everything about
  2291. * @return array Array containing all the information about the extra profile field
  2292. * (first level of array contains field details, then 'options' sub-array contains options details,
  2293. * as returned by the database)
  2294. * @author José Loguercio
  2295. * @since v1.11.0
  2296. */
  2297. public static function get_extra_field_tags_information_by_name($variable)
  2298. {
  2299. $extraField = new ExtraField('user');
  2300. return $extraField->get_handler_field_info_by_tags($variable);
  2301. }
  2302. /**
  2303. * @param string $type
  2304. *
  2305. * @return array
  2306. */
  2307. public static function get_all_extra_field_by_type($type)
  2308. {
  2309. $extraField = new ExtraField('user');
  2310. return $extraField->get_all_extra_field_by_type($type);
  2311. }
  2312. /**
  2313. * Get all the extra field information of a certain field (also the options)
  2314. *
  2315. * @param int $fieldId the ID of the field we want to know everything of
  2316. * @return array $return containing all th information about the extra profile field
  2317. * @author Julio Montoya
  2318. * @deprecated
  2319. * @since v1.8.6
  2320. */
  2321. public static function get_extra_field_information($fieldId)
  2322. {
  2323. $extraField = new ExtraField('user');
  2324. return $extraField->getFieldInfoByFieldId($fieldId);
  2325. }
  2326. /**
  2327. * Get extra user data by value
  2328. * @param string $variable the internal variable name of the field
  2329. * @param string $value the internal value of the field
  2330. * @param bool $all_visibility
  2331. *
  2332. * @return array with extra data info of a user i.e array('field_variable'=>'value');
  2333. */
  2334. public static function get_extra_user_data_by_value($variable, $value, $all_visibility = true)
  2335. {
  2336. $extraFieldValue = new ExtraFieldValue('user');
  2337. $extraField = new ExtraField('user');
  2338. $info = $extraField->get_handler_field_info_by_field_variable($variable);
  2339. if (false === $info) {
  2340. return [];
  2341. }
  2342. $data = $extraFieldValue->get_item_id_from_field_variable_and_field_value(
  2343. $variable,
  2344. $value,
  2345. false,
  2346. false,
  2347. true
  2348. );
  2349. $result = [];
  2350. if (!empty($data)) {
  2351. foreach ($data as $item) {
  2352. $result[] = $item['item_id'];
  2353. }
  2354. }
  2355. return $result;
  2356. }
  2357. /**
  2358. * Get extra user data by tags value
  2359. *
  2360. * @param int $fieldId the ID of the field we want to know everything of
  2361. * @param string $tag the tag name for search
  2362. * @return array with extra data info of a user
  2363. * @author José Loguercio
  2364. * @since v1.11.0
  2365. */
  2366. public static function get_extra_user_data_by_tags($fieldId, $tag)
  2367. {
  2368. $extraField = new ExtraField('user');
  2369. $result = $extraField->getAllUserPerTag($fieldId, $tag);
  2370. $array = [];
  2371. foreach ($result as $index => $user) {
  2372. $array[] = $user['user_id'];
  2373. }
  2374. return $array;
  2375. }
  2376. /**
  2377. * Get extra user data by field variable
  2378. * @param string $variable field variable
  2379. * @return array data
  2380. */
  2381. public static function get_extra_user_data_by_field_variable($variable)
  2382. {
  2383. $extra_information_by_variable = self::get_extra_field_information_by_name($variable);
  2384. $field_id = intval($extra_information_by_variable['id']);
  2385. $extraField = new ExtraFieldValue('user');
  2386. $data = $extraField->getValuesByFieldId($field_id);
  2387. if (!empty($data) > 0) {
  2388. foreach ($data as $row) {
  2389. $user_id = $row['item_id'];
  2390. $data[$user_id] = $row;
  2391. }
  2392. }
  2393. return $data;
  2394. }
  2395. /**
  2396. * Get extra user data tags by field variable
  2397. *
  2398. * @param string $variable field variable
  2399. * @return array
  2400. */
  2401. public static function get_extra_user_data_for_tags($variable)
  2402. {
  2403. $data = self::get_extra_field_tags_information_by_name($variable);
  2404. return $data;
  2405. }
  2406. /**
  2407. * Gives a list of [session_category][session_id] for the current user.
  2408. * @param integer $user_id
  2409. * @param boolean $is_time_over whether to fill the first element or not (to give space for courses out of categories)
  2410. * @param boolean $ignore_visibility_for_admins optional true if limit time from session is over, false otherwise
  2411. * @param boolean $ignoreTimeLimit ignore time start/end
  2412. * @return array list of statuses [session_category][session_id]
  2413. *
  2414. * @todo ensure multiple access urls are managed correctly
  2415. */
  2416. public static function get_sessions_by_category(
  2417. $user_id,
  2418. $is_time_over = true,
  2419. $ignore_visibility_for_admins = false,
  2420. $ignoreTimeLimit = false
  2421. ) {
  2422. if ($user_id != strval(intval($user_id))) {
  2423. return array();
  2424. }
  2425. // Get the list of sessions per user
  2426. $now = new DateTime('now', new DateTimeZone('UTC'));
  2427. // LEFT JOIN is used for session_rel_course_rel_user because an inner
  2428. // join would not catch session-courses where the user is general
  2429. // session coach but which do not have students nor coaches registered
  2430. $dql = "SELECT DISTINCT
  2431. s.id,
  2432. s.name,
  2433. s.accessStartDate AS access_start_date,
  2434. s.accessEndDate AS access_end_date,
  2435. s.duration,
  2436. sc.id AS session_category_id,
  2437. sc.name AS session_category_name,
  2438. sc.dateStart AS session_category_date_start,
  2439. sc.dateEnd AS session_category_date_end,
  2440. s.coachAccessStartDate AS coach_access_start_date,
  2441. s.coachAccessEndDate AS coach_access_end_date
  2442. FROM ChamiloCoreBundle:Session AS s
  2443. LEFT JOIN ChamiloCoreBundle:SessionRelCourseRelUser AS scu WITH scu.session = s
  2444. INNER JOIN ChamiloCoreBundle:AccessUrlRelSession AS url WITH url.session = s
  2445. LEFT JOIN ChamiloCoreBundle:SessionCategory AS sc WITH s.category = sc
  2446. WHERE (scu.user = :user OR s.generalCoach = :user) AND url.url = :url
  2447. ORDER BY sc.name, s.name";
  2448. $dql = Database::getManager()
  2449. ->createQuery($dql)
  2450. ->setParameters(
  2451. ['user' => $user_id, 'url' => api_get_current_access_url_id()]
  2452. )
  2453. ;
  2454. $sessionData = $dql->getResult();
  2455. $categories = [];
  2456. foreach ($sessionData as $row) {
  2457. $session_id = $row['id'];
  2458. $coachList = SessionManager::getCoachesBySession($session_id);
  2459. $categoryStart = $row['session_category_date_start'] ? $row['session_category_date_start']->format('Y-m-d') : '';
  2460. $categoryEnd = $row['session_category_date_end'] ? $row['session_category_date_end']->format('Y-m-d') : '';
  2461. $courseList = self::get_courses_list_by_session(
  2462. $user_id,
  2463. $session_id
  2464. );
  2465. $daysLeft = SessionManager::getDayLeftInSession($row, $user_id);
  2466. // User portal filters:
  2467. if ($ignoreTimeLimit === false) {
  2468. if ($is_time_over) {
  2469. // History
  2470. if ($row['duration']) {
  2471. if ($daysLeft >= 0) {
  2472. continue;
  2473. }
  2474. } else {
  2475. if (empty($row['access_end_date'])) {
  2476. continue;
  2477. } else {
  2478. if ($row['access_end_date'] > $now) {
  2479. continue;
  2480. }
  2481. }
  2482. }
  2483. } else {
  2484. // Current user portal
  2485. $isGeneralCoach = SessionManager::user_is_general_coach($user_id, $row['id']);
  2486. $isCoachOfCourse = in_array($user_id, $coachList);
  2487. if (api_is_platform_admin() || $isGeneralCoach || $isCoachOfCourse) {
  2488. // Teachers can access the session depending in the access_coach date
  2489. } else {
  2490. if ($row['duration']) {
  2491. if ($daysLeft <= 0) {
  2492. continue;
  2493. }
  2494. } else {
  2495. if (isset($row['access_end_date']) &&
  2496. !empty($row['access_end_date'])
  2497. ) {
  2498. if ($row['access_end_date'] <= $now) {
  2499. continue;
  2500. }
  2501. }
  2502. }
  2503. }
  2504. }
  2505. }
  2506. $categories[$row['session_category_id']]['session_category'] = array(
  2507. 'id' => $row['session_category_id'],
  2508. 'name' => $row['session_category_name'],
  2509. 'date_start' => $categoryStart,
  2510. 'date_end' => $categoryEnd
  2511. );
  2512. $visibility = api_get_session_visibility(
  2513. $session_id,
  2514. null,
  2515. $ignore_visibility_for_admins
  2516. );
  2517. if ($visibility != SESSION_VISIBLE) {
  2518. // Course Coach session visibility.
  2519. $blockedCourseCount = 0;
  2520. $closedVisibilityList = array(
  2521. COURSE_VISIBILITY_CLOSED,
  2522. COURSE_VISIBILITY_HIDDEN
  2523. );
  2524. foreach ($courseList as $course) {
  2525. // Checking session visibility
  2526. $sessionCourseVisibility = api_get_session_visibility(
  2527. $session_id,
  2528. $course['real_id'],
  2529. $ignore_visibility_for_admins
  2530. );
  2531. $courseIsVisible = !in_array(
  2532. $course['visibility'],
  2533. $closedVisibilityList
  2534. );
  2535. if ($courseIsVisible === false || $sessionCourseVisibility == SESSION_INVISIBLE) {
  2536. $blockedCourseCount++;
  2537. }
  2538. }
  2539. // If all courses are blocked then no show in the list.
  2540. if ($blockedCourseCount === count($courseList)) {
  2541. $visibility = SESSION_INVISIBLE;
  2542. } else {
  2543. $visibility = $sessionCourseVisibility;
  2544. }
  2545. }
  2546. switch ($visibility) {
  2547. case SESSION_VISIBLE_READ_ONLY:
  2548. case SESSION_VISIBLE:
  2549. case SESSION_AVAILABLE:
  2550. break;
  2551. case SESSION_INVISIBLE:
  2552. if ($ignore_visibility_for_admins === false) {
  2553. continue 2;
  2554. }
  2555. }
  2556. $categories[$row['session_category_id']]['sessions'][$row['id']] = array(
  2557. 'session_name' => $row['name'],
  2558. 'session_id' => $row['id'],
  2559. 'access_start_date' => $row['access_start_date'] ? $row['access_start_date']->format('Y-m-d H:i:s') : null,
  2560. 'access_end_date' => $row['access_end_date'] ? $row['access_end_date']->format('Y-m-d H:i:s') : null,
  2561. 'coach_access_start_date' => $row['coach_access_start_date'] ? $row['coach_access_start_date']->format('Y-m-d H:i:s') : null,
  2562. 'coach_access_end_date' => $row['coach_access_end_date'] ? $row['coach_access_end_date']->format('Y-m-d H:i:s') : null,
  2563. 'display_start_date' => $row['display_start_date'] ? $row['display_start_date']->format(
  2564. 'Y-m-d H:i:s'
  2565. ) : null,
  2566. 'display_end_date' => $row['display_end_date'] ? $row['display_end_date']->format(
  2567. 'Y-m-d H:i:s'
  2568. ) : null,
  2569. 'courses' => $courseList
  2570. );
  2571. }
  2572. return $categories;
  2573. }
  2574. /**
  2575. * Gives a list of [session_id-course_code] => [status] for the current user.
  2576. * @param integer $user_id
  2577. * @param int $sessionLimit
  2578. * @return array list of statuses (session_id-course_code => status)
  2579. */
  2580. public static function get_personal_session_course_list($user_id, $sessionLimit = null)
  2581. {
  2582. // Database Table Definitions
  2583. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  2584. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  2585. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  2586. $tbl_session_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  2587. $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  2588. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2589. if ($user_id != strval(intval($user_id))) {
  2590. return array();
  2591. }
  2592. // We filter the courses from the URL
  2593. $join_access_url = $where_access_url = '';
  2594. if (api_get_multiple_access_url()) {
  2595. $access_url_id = api_get_current_access_url_id();
  2596. if ($access_url_id != -1) {
  2597. $tbl_url_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  2598. $join_access_url = "LEFT JOIN $tbl_url_course url_rel_course ON url_rel_course.c_id = course.id";
  2599. $where_access_url = " AND access_url_id = $access_url_id ";
  2600. }
  2601. }
  2602. // Courses in which we subscribed out of any session
  2603. $tbl_user_course_category = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
  2604. $sql = "SELECT
  2605. course.code,
  2606. course_rel_user.status course_rel_status,
  2607. course_rel_user.sort sort,
  2608. course_rel_user.user_course_cat user_course_cat
  2609. FROM $tbl_course_user course_rel_user
  2610. LEFT JOIN $tbl_course course
  2611. ON course.id = course_rel_user.c_id
  2612. LEFT JOIN $tbl_user_course_category user_course_category
  2613. ON course_rel_user.user_course_cat = user_course_category.id
  2614. $join_access_url
  2615. WHERE
  2616. course_rel_user.user_id = '".$user_id."' AND
  2617. course_rel_user.relation_type <> ".COURSE_RELATION_TYPE_RRHH."
  2618. $where_access_url
  2619. ORDER BY user_course_category.sort, course_rel_user.sort, course.title ASC";
  2620. $course_list_sql_result = Database::query($sql);
  2621. $personal_course_list = array();
  2622. if (Database::num_rows($course_list_sql_result) > 0) {
  2623. while ($result_row = Database::fetch_array($course_list_sql_result, 'ASSOC')) {
  2624. $course_info = api_get_course_info($result_row['code']);
  2625. $result_row['course_info'] = $course_info;
  2626. $personal_course_list[] = $result_row;
  2627. }
  2628. }
  2629. $coachCourseConditions = null;
  2630. // Getting sessions that are related to a coach in the session_rel_course_rel_user table
  2631. if (api_is_allowed_to_create_course()) {
  2632. $sessionListFromCourseCoach = array();
  2633. $sql = " SELECT DISTINCT session_id
  2634. FROM $tbl_session_course_user
  2635. WHERE user_id = $user_id AND status = 2 ";
  2636. $result = Database::query($sql);
  2637. if (Database::num_rows($result)) {
  2638. $result = Database::store_result($result);
  2639. foreach ($result as $session) {
  2640. $sessionListFromCourseCoach[] = $session['session_id'];
  2641. }
  2642. }
  2643. if (!empty($sessionListFromCourseCoach)) {
  2644. $condition = implode("','", $sessionListFromCourseCoach);
  2645. $coachCourseConditions = " OR ( s.id IN ('$condition'))";
  2646. }
  2647. }
  2648. // Get the list of sessions where the user is subscribed
  2649. // This is divided into two different queries
  2650. $sessions = array();
  2651. $sessionLimitRestriction = '';
  2652. if (!empty($sessionLimit)) {
  2653. $sessionLimit = (int) $sessionLimit;
  2654. $sessionLimitRestriction = "LIMIT $sessionLimit";
  2655. }
  2656. $sql = "SELECT DISTINCT s.id, name, access_start_date, access_end_date
  2657. FROM $tbl_session_user su INNER JOIN $tbl_session s
  2658. ON (s.id = su.session_id)
  2659. WHERE (
  2660. su.user_id = $user_id AND
  2661. su.relation_type <> ".SESSION_RELATION_TYPE_RRHH."
  2662. )
  2663. $coachCourseConditions
  2664. ORDER BY access_start_date, access_end_date, name
  2665. $sessionLimitRestriction
  2666. ";
  2667. $result = Database::query($sql);
  2668. if (Database::num_rows($result) > 0) {
  2669. while ($row = Database::fetch_assoc($result)) {
  2670. $sessions[$row['id']] = $row;
  2671. }
  2672. }
  2673. $sql = "SELECT DISTINCT
  2674. id, name, access_start_date, access_end_date
  2675. FROM $tbl_session s
  2676. WHERE (
  2677. id_coach = $user_id
  2678. )
  2679. $coachCourseConditions
  2680. ORDER BY access_start_date, access_end_date, name";
  2681. $result = Database::query($sql);
  2682. if (Database::num_rows($result) > 0) {
  2683. while ($row = Database::fetch_assoc($result)) {
  2684. if (empty($sessions[$row['id']])) {
  2685. $sessions[$row['id']] = $row;
  2686. }
  2687. }
  2688. }
  2689. if (api_is_allowed_to_create_course()) {
  2690. foreach ($sessions as $enreg) {
  2691. $session_id = $enreg['id'];
  2692. $session_visibility = api_get_session_visibility($session_id);
  2693. if ($session_visibility == SESSION_INVISIBLE) {
  2694. continue;
  2695. }
  2696. // This query is horribly slow when more than a few thousand
  2697. // users and just a few sessions to which they are subscribed
  2698. $sql = "SELECT DISTINCT
  2699. course.code code,
  2700. course.title i,
  2701. ".(api_is_western_name_order() ? "CONCAT(user.firstname,' ',user.lastname)" : "CONCAT(user.lastname,' ',user.firstname)")." t,
  2702. email, course.course_language l,
  2703. 1 sort,
  2704. category_code user_course_cat,
  2705. access_start_date,
  2706. access_end_date,
  2707. session.id as session_id,
  2708. session.name as session_name
  2709. FROM $tbl_session_course_user as session_course_user
  2710. INNER JOIN $tbl_course AS course
  2711. ON course.id = session_course_user.c_id
  2712. INNER JOIN $tbl_session as session
  2713. ON session.id = session_course_user.session_id
  2714. LEFT JOIN $tbl_user as user
  2715. ON user.id = session_course_user.user_id OR session.id_coach = user.id
  2716. WHERE
  2717. session_course_user.session_id = $session_id AND (
  2718. (session_course_user.user_id = $user_id AND session_course_user.status = 2)
  2719. OR session.id_coach = $user_id
  2720. )
  2721. ORDER BY i";
  2722. $course_list_sql_result = Database::query($sql);
  2723. while ($result_row = Database::fetch_array($course_list_sql_result, 'ASSOC')) {
  2724. $result_row['course_info'] = api_get_course_info($result_row['code']);
  2725. $key = $result_row['session_id'].' - '.$result_row['code'];
  2726. $personal_course_list[$key] = $result_row;
  2727. }
  2728. }
  2729. }
  2730. foreach ($sessions as $enreg) {
  2731. $session_id = $enreg['id'];
  2732. $session_visibility = api_get_session_visibility($session_id);
  2733. if ($session_visibility == SESSION_INVISIBLE) {
  2734. continue;
  2735. }
  2736. /* This query is very similar to the above query,
  2737. but it will check the session_rel_course_user table if there are courses registered to our user or not */
  2738. $sql = "SELECT DISTINCT
  2739. course.code code,
  2740. course.title i, CONCAT(user.lastname,' ',user.firstname) t,
  2741. email,
  2742. course.course_language l,
  2743. 1 sort,
  2744. category_code user_course_cat,
  2745. access_start_date,
  2746. access_end_date,
  2747. session.id as session_id,
  2748. session.name as session_name,
  2749. IF((session_course_user.user_id = 3 AND session_course_user.status=2),'2', '5')
  2750. FROM $tbl_session_course_user as session_course_user
  2751. INNER JOIN $tbl_course AS course
  2752. ON course.id = session_course_user.c_id AND session_course_user.session_id = $session_id
  2753. INNER JOIN $tbl_session as session
  2754. ON session_course_user.session_id = session.id
  2755. LEFT JOIN $tbl_user as user ON user.id = session_course_user.user_id
  2756. WHERE session_course_user.user_id = $user_id
  2757. ORDER BY i";
  2758. $course_list_sql_result = Database::query($sql);
  2759. while ($result_row = Database::fetch_array($course_list_sql_result, 'ASSOC')) {
  2760. $result_row['course_info'] = api_get_course_info($result_row['code']);
  2761. $key = $result_row['session_id'].' - '.$result_row['code'];
  2762. if (!isset($personal_course_list[$key])) {
  2763. $personal_course_list[$key] = $result_row;
  2764. }
  2765. }
  2766. }
  2767. return $personal_course_list;
  2768. }
  2769. /**
  2770. * Gives a list of courses for the given user in the given session
  2771. * @param integer $user_id
  2772. * @param integer $session_id
  2773. * @return array list of statuses (session_id-course_code => status)
  2774. */
  2775. public static function get_courses_list_by_session($user_id, $session_id)
  2776. {
  2777. // Database Table Definitions
  2778. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  2779. $tableCourse = Database::get_main_table(TABLE_MAIN_COURSE);
  2780. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2781. $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  2782. $user_id = intval($user_id);
  2783. $session_id = intval($session_id);
  2784. //we filter the courses from the URL
  2785. $join_access_url = $where_access_url = '';
  2786. if (api_get_multiple_access_url()) {
  2787. $urlId = api_get_current_access_url_id();
  2788. if ($urlId != -1) {
  2789. $tbl_url_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  2790. $join_access_url = " , $tbl_url_session url_rel_session ";
  2791. $where_access_url = " AND access_url_id = $urlId AND url_rel_session.session_id = $session_id ";
  2792. }
  2793. }
  2794. /* This query is very similar to the query below, but it will check the
  2795. session_rel_course_user table if there are courses registered
  2796. to our user or not */
  2797. $sql = "SELECT DISTINCT
  2798. c.visibility,
  2799. c.id as real_id,
  2800. c.code as course_code,
  2801. sc.position
  2802. FROM $tbl_session_course_user as scu
  2803. INNER JOIN $tbl_session_course sc
  2804. ON (scu.session_id = sc.session_id AND scu.c_id = sc.c_id)
  2805. INNER JOIN $tableCourse as c
  2806. ON (scu.c_id = c.id)
  2807. $join_access_url
  2808. WHERE
  2809. scu.user_id = $user_id AND
  2810. scu.session_id = $session_id
  2811. $where_access_url
  2812. ORDER BY sc.position ASC, c.id";
  2813. $personal_course_list = array();
  2814. $courses = array();
  2815. $result = Database::query($sql);
  2816. if (Database::num_rows($result) > 0) {
  2817. while ($result_row = Database::fetch_array($result, 'ASSOC')) {
  2818. $result_row['status'] = 5;
  2819. if (!in_array($result_row['real_id'], $courses)) {
  2820. $personal_course_list[] = $result_row;
  2821. $courses[] = $result_row['real_id'];
  2822. }
  2823. }
  2824. }
  2825. if (api_is_allowed_to_create_course()) {
  2826. $sql = "SELECT DISTINCT
  2827. c.visibility,
  2828. c.id as real_id,
  2829. c.code as course_code,
  2830. sc.position
  2831. FROM $tbl_session_course_user as scu
  2832. INNER JOIN $tbl_session as s
  2833. ON (scu.session_id = s.id)
  2834. INNER JOIN $tbl_session_course sc
  2835. ON (scu.session_id = sc.session_id AND scu.c_id = sc.c_id)
  2836. INNER JOIN $tableCourse as c
  2837. ON (scu.c_id = c.id)
  2838. $join_access_url
  2839. WHERE
  2840. s.id = $session_id AND
  2841. (
  2842. (scu.user_id = $user_id AND scu.status = 2) OR
  2843. s.id_coach = $user_id
  2844. )
  2845. $where_access_url
  2846. ORDER BY sc.position ASC";
  2847. $result = Database::query($sql);
  2848. if (Database::num_rows($result) > 0) {
  2849. while ($result_row = Database::fetch_array($result, 'ASSOC')) {
  2850. $result_row['status'] = 2;
  2851. if (!in_array($result_row['real_id'], $courses)) {
  2852. $personal_course_list[] = $result_row;
  2853. $courses[] = $result_row['real_id'];
  2854. }
  2855. }
  2856. }
  2857. }
  2858. if (api_is_drh()) {
  2859. $sessionList = SessionManager::get_sessions_followed_by_drh($user_id);
  2860. $sessionList = array_keys($sessionList);
  2861. if (in_array($session_id, $sessionList)) {
  2862. $courseList = SessionManager::get_course_list_by_session_id($session_id);
  2863. if (!empty($courseList)) {
  2864. foreach ($courseList as $course) {
  2865. if (!in_array($course['id'], $courses)) {
  2866. $personal_course_list[] = $course;
  2867. }
  2868. }
  2869. }
  2870. }
  2871. } else {
  2872. //check if user is general coach for this session
  2873. $sessionInfo = api_get_session_info($session_id);
  2874. if ($sessionInfo['id_coach'] == $user_id) {
  2875. $courseList = SessionManager::get_course_list_by_session_id($session_id);
  2876. if (!empty($courseList)) {
  2877. foreach ($courseList as $course) {
  2878. if (!in_array($course['id'], $courses)) {
  2879. $personal_course_list[] = $course;
  2880. }
  2881. }
  2882. }
  2883. }
  2884. }
  2885. return $personal_course_list;
  2886. }
  2887. /**
  2888. * Get user id from a username
  2889. * @param string $username
  2890. * @return int User ID (or false if not found)
  2891. */
  2892. public static function get_user_id_from_username($username)
  2893. {
  2894. if (empty($username)) {
  2895. return false;
  2896. }
  2897. $username = trim($username);
  2898. $username = Database::escape_string($username);
  2899. $t_user = Database::get_main_table(TABLE_MAIN_USER);
  2900. $sql = "SELECT id FROM $t_user WHERE username = '$username'";
  2901. $res = Database::query($sql);
  2902. if ($res === false) {
  2903. return false;
  2904. }
  2905. if (Database::num_rows($res) !== 1) {
  2906. return false;
  2907. }
  2908. $row = Database::fetch_array($res);
  2909. return $row['id'];
  2910. }
  2911. /**
  2912. * Get the users files upload from his share_folder
  2913. * @param string $user_id User ID
  2914. * @param string $course course directory
  2915. * @param string $resourcetype resourcetype: images, all
  2916. * @return int User ID (or false if not found)
  2917. */
  2918. public static function get_user_upload_files_by_course(
  2919. $user_id,
  2920. $course,
  2921. $resourcetype = 'all'
  2922. ) {
  2923. $return = '';
  2924. if (!empty($user_id) && !empty($course)) {
  2925. $user_id = intval($user_id);
  2926. $path = api_get_path(SYS_COURSE_PATH).$course.'/document/shared_folder/sf_user_'.$user_id.'/';
  2927. $web_path = api_get_path(WEB_COURSE_PATH).$course.'/document/shared_folder/sf_user_'.$user_id.'/';
  2928. $file_list = array();
  2929. if (is_dir($path)) {
  2930. $handle = opendir($path);
  2931. while ($file = readdir($handle)) {
  2932. if ($file == '.' || $file == '..' || $file == '.htaccess' || is_dir($path.$file)) {
  2933. continue; // skip current/parent directory and .htaccess
  2934. }
  2935. $file_list[] = $file;
  2936. }
  2937. if (count($file_list) > 0) {
  2938. $return = "<h4>$course</h4>";
  2939. $return .= '<ul class="thumbnails">';
  2940. }
  2941. $extensionList = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'tif'];
  2942. foreach ($file_list as $file) {
  2943. if ($resourcetype == "all") {
  2944. $return .= '<li><a href="'.$web_path.urlencode($file).'" target="_blank">'.htmlentities($file).'</a></li>';
  2945. } elseif ($resourcetype == "images") {
  2946. //get extension
  2947. $ext = explode('.', $file);
  2948. if (isset($ext[1]) && in_array($ext[1], $extensionList)) {
  2949. $return .= '<li class="span2">
  2950. <a class="thumbnail" href="'.$web_path.urlencode($file).'" target="_blank">
  2951. <img src="'.$web_path.urlencode($file).'" >
  2952. </a>
  2953. </li>';
  2954. }
  2955. }
  2956. }
  2957. if (count($file_list) > 0) {
  2958. $return .= '</ul>';
  2959. }
  2960. }
  2961. }
  2962. return $return;
  2963. }
  2964. /**
  2965. * Gets the API key (or keys) and return them into an array
  2966. * @param int Optional user id (defaults to the result of api_get_user_id())
  2967. * @return array Non-indexed array containing the list of API keys for this user, or FALSE on error
  2968. */
  2969. public static function get_api_keys($user_id = null, $api_service = 'dokeos')
  2970. {
  2971. if ($user_id != strval(intval($user_id)))
  2972. return false;
  2973. if (empty($user_id)) {
  2974. $user_id = api_get_user_id();
  2975. }
  2976. if ($user_id === false)
  2977. return false;
  2978. $service_name = Database::escape_string($api_service);
  2979. if (is_string($service_name) === false) {
  2980. return false;
  2981. }
  2982. $t_api = Database::get_main_table(TABLE_MAIN_USER_API_KEY);
  2983. $sql = "SELECT * FROM $t_api WHERE user_id = $user_id AND api_service='$api_service';";
  2984. $res = Database::query($sql);
  2985. if ($res === false)
  2986. return false; //error during query
  2987. $num = Database::num_rows($res);
  2988. if ($num == 0)
  2989. return false;
  2990. $list = array();
  2991. while ($row = Database::fetch_array($res)) {
  2992. $list[$row['id']] = $row['api_key'];
  2993. }
  2994. return $list;
  2995. }
  2996. /**
  2997. * Adds a new API key to the users' account
  2998. * @param int Optional user ID (defaults to the results of api_get_user_id())
  2999. * @return boolean True on success, false on failure
  3000. */
  3001. public static function add_api_key($user_id = null, $api_service = 'dokeos')
  3002. {
  3003. if ($user_id != strval(intval($user_id)))
  3004. return false;
  3005. if (empty($user_id)) {
  3006. $user_id = api_get_user_id();
  3007. }
  3008. if ($user_id === false)
  3009. return false;
  3010. $service_name = Database::escape_string($api_service);
  3011. if (is_string($service_name) === false) {
  3012. return false;
  3013. }
  3014. $t_api = Database::get_main_table(TABLE_MAIN_USER_API_KEY);
  3015. $md5 = md5((time() + ($user_id * 5)) - rand(10000, 10000)); //generate some kind of random key
  3016. $sql = "INSERT INTO $t_api (user_id, api_key,api_service) VALUES ($user_id,'$md5','$service_name')";
  3017. $res = Database::query($sql);
  3018. if ($res === false)
  3019. return false; //error during query
  3020. $num = Database::insert_id();
  3021. return ($num == 0) ? false : $num;
  3022. }
  3023. /**
  3024. * Deletes an API key from the user's account
  3025. * @param int API key's internal ID
  3026. * @return boolean True on success, false on failure
  3027. */
  3028. public static function delete_api_key($key_id)
  3029. {
  3030. if ($key_id != strval(intval($key_id)))
  3031. return false;
  3032. if ($key_id === false)
  3033. return false;
  3034. $t_api = Database::get_main_table(TABLE_MAIN_USER_API_KEY);
  3035. $sql = "SELECT * FROM $t_api WHERE id = ".$key_id;
  3036. $res = Database::query($sql);
  3037. if ($res === false)
  3038. return false; //error during query
  3039. $num = Database::num_rows($res);
  3040. if ($num !== 1)
  3041. return false;
  3042. $sql = "DELETE FROM $t_api WHERE id = ".$key_id;
  3043. $res = Database::query($sql);
  3044. if ($res === false)
  3045. return false; //error during query
  3046. return true;
  3047. }
  3048. /**
  3049. * Regenerate an API key from the user's account
  3050. * @param int user ID (defaults to the results of api_get_user_id())
  3051. * @param string API key's internal ID
  3052. * @return int num
  3053. */
  3054. public static function update_api_key($user_id, $api_service)
  3055. {
  3056. if ($user_id != strval(intval($user_id)))
  3057. return false;
  3058. if ($user_id === false)
  3059. return false;
  3060. $service_name = Database::escape_string($api_service);
  3061. if (is_string($service_name) === false) {
  3062. return false;
  3063. }
  3064. $t_api = Database::get_main_table(TABLE_MAIN_USER_API_KEY);
  3065. $sql = "SELECT id FROM $t_api
  3066. WHERE user_id=".$user_id." AND api_service='".$api_service."'";
  3067. $res = Database::query($sql);
  3068. $num = Database::num_rows($res);
  3069. if ($num == 1) {
  3070. $id_key = Database::fetch_array($res, 'ASSOC');
  3071. self::delete_api_key($id_key['id']);
  3072. $num = self::add_api_key($user_id, $api_service);
  3073. } elseif ($num == 0) {
  3074. $num = self::add_api_key($user_id, $api_service);
  3075. }
  3076. return $num;
  3077. }
  3078. /**
  3079. * @param int user ID (defaults to the results of api_get_user_id())
  3080. * @param string API key's internal ID
  3081. * @return int row ID, or return false if not found
  3082. */
  3083. public static function get_api_key_id($user_id, $api_service)
  3084. {
  3085. if ($user_id != strval(intval($user_id)))
  3086. return false;
  3087. if ($user_id === false)
  3088. return false;
  3089. if (empty($api_service))
  3090. return false;
  3091. $t_api = Database::get_main_table(TABLE_MAIN_USER_API_KEY);
  3092. $api_service = Database::escape_string($api_service);
  3093. $sql = "SELECT id FROM $t_api
  3094. WHERE user_id=".$user_id." AND api_service='".$api_service."'";
  3095. $res = Database::query($sql);
  3096. if (Database::num_rows($res) < 1) {
  3097. return false;
  3098. }
  3099. $row = Database::fetch_array($res, 'ASSOC');
  3100. return $row['id'];
  3101. }
  3102. /**
  3103. * Checks if a user_id is platform admin
  3104. * @param int user ID
  3105. * @return boolean True if is admin, false otherwise
  3106. * @see main_api.lib.php::api_is_platform_admin() for a context-based check
  3107. */
  3108. public static function is_admin($user_id)
  3109. {
  3110. if (empty($user_id) || $user_id != strval(intval($user_id))) {
  3111. return false;
  3112. }
  3113. $admin_table = Database::get_main_table(TABLE_MAIN_ADMIN);
  3114. $sql = "SELECT * FROM $admin_table WHERE user_id = $user_id";
  3115. $res = Database::query($sql);
  3116. return Database::num_rows($res) === 1;
  3117. }
  3118. /**
  3119. * Get the total count of users
  3120. * @param int Status of users to be counted
  3121. * @param int Access URL ID (optional)
  3122. * @return mixed Number of users or false on error
  3123. */
  3124. public static function get_number_of_users($status = 0, $access_url_id = 1)
  3125. {
  3126. $t_u = Database::get_main_table(TABLE_MAIN_USER);
  3127. $t_a = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  3128. $sql = "SELECT count(u.id)
  3129. FROM $t_u u
  3130. INNER JOIN $t_a url_user
  3131. ON (u.id = url_user.user_id)
  3132. WHERE url_user.access_url_id = $access_url_id
  3133. ";
  3134. if (is_int($status) && $status > 0) {
  3135. $sql .= " AND u.status = $status ";
  3136. }
  3137. $res = Database::query($sql);
  3138. if (Database::num_rows($res) === 1) {
  3139. return (int) Database::result($res, 0, 0);
  3140. }
  3141. return false;
  3142. }
  3143. /**
  3144. * @author Isaac flores <isaac.flores@dokeos.com>
  3145. * @param string The email administrator
  3146. * @param integer The user id
  3147. * @param string The message title
  3148. * @param string The content message
  3149. */
  3150. public static function send_message_in_outbox(
  3151. $email_administrator,
  3152. $user_id,
  3153. $title,
  3154. $content
  3155. ) {
  3156. $table_message = Database::get_main_table(TABLE_MESSAGE);
  3157. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  3158. $title = api_utf8_decode($title);
  3159. $content = api_utf8_decode($content);
  3160. $email_administrator = Database::escape_string($email_administrator);
  3161. //message in inbox
  3162. $sql_message_outbox = 'SELECT id from '.$table_user.' WHERE email="'.$email_administrator.'" ';
  3163. //$num_row_query = Database::num_rows($sql_message_outbox);
  3164. $res_message_outbox = Database::query($sql_message_outbox);
  3165. $array_users_administrator = array();
  3166. while ($row_message_outbox = Database::fetch_array($res_message_outbox, 'ASSOC')) {
  3167. $array_users_administrator[] = $row_message_outbox['id'];
  3168. }
  3169. //allow to insert messages in outbox
  3170. for ($i = 0; $i < count($array_users_administrator); $i++) {
  3171. $sql_insert_outbox = "INSERT INTO $table_message(user_sender_id, user_receiver_id, msg_status, send_date, title, content ) ".
  3172. " VALUES (".
  3173. "'".(int) $user_id."', '".(int) ($array_users_administrator[$i])."', '4', '".api_get_utc_datetime()."','".Database::escape_string($title)."','".Database::escape_string($content)."'".
  3174. ")";
  3175. Database::query($sql_insert_outbox);
  3176. }
  3177. }
  3178. /**
  3179. *
  3180. * Gets the tags of a specific field_id
  3181. * USER TAGS
  3182. *
  3183. * Instructions to create a new user tag by Julio Montoya <gugli100@gmail.com>
  3184. *
  3185. * 1. Create a new extra field in main/admin/user_fields.php with the "TAG" field type make it available and visible.
  3186. * Called it "books" for example.
  3187. * 2. Go to profile main/auth/profile.php There you will see a special input (facebook style) that will show suggestions of tags.
  3188. * 3. All the tags are registered in the user_tag table and the relationship between user and tags is in the user_rel_tag table
  3189. * 4. Tags are independent this means that tags can't be shared between tags + book + hobbies.
  3190. * 5. Test and enjoy.
  3191. *
  3192. * @param string $tag
  3193. * @param int $field_id field_id
  3194. * @param string $return_format how we are going to result value in array or in a string (json)
  3195. * @param $limit
  3196. *
  3197. * @return mixed
  3198. *
  3199. */
  3200. public static function get_tags($tag, $field_id, $return_format = 'json', $limit = 10)
  3201. {
  3202. // database table definition
  3203. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  3204. $field_id = intval($field_id);
  3205. $limit = intval($limit);
  3206. $tag = trim(Database::escape_string($tag));
  3207. // all the information of the field
  3208. $sql = "SELECT DISTINCT id, tag from $table_user_tag
  3209. WHERE field_id = $field_id AND tag LIKE '$tag%' ORDER BY tag LIMIT $limit";
  3210. $result = Database::query($sql);
  3211. $return = array();
  3212. if (Database::num_rows($result) > 0) {
  3213. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3214. $return[] = array('id' => $row['tag'], 'text' => $row['tag']);
  3215. }
  3216. }
  3217. if ($return_format === 'json') {
  3218. $return = json_encode($return);
  3219. }
  3220. return $return;
  3221. }
  3222. /**
  3223. * @param int $field_id
  3224. * @param int $limit
  3225. *
  3226. * @return array
  3227. */
  3228. public static function get_top_tags($field_id, $limit = 100)
  3229. {
  3230. // database table definition
  3231. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  3232. $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
  3233. $field_id = intval($field_id);
  3234. $limit = intval($limit);
  3235. // all the information of the field
  3236. $sql = "SELECT count(*) count, tag FROM $table_user_tag_values uv
  3237. INNER JOIN $table_user_tag ut
  3238. ON(ut.id = uv.tag_id)
  3239. WHERE field_id = $field_id
  3240. GROUP BY tag_id
  3241. ORDER BY count DESC
  3242. LIMIT $limit";
  3243. $result = Database::query($sql);
  3244. $return = array();
  3245. if (Database::num_rows($result) > 0) {
  3246. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3247. $return[] = $row;
  3248. }
  3249. }
  3250. return $return;
  3251. }
  3252. /**
  3253. * Get user's tags
  3254. * @param int $user_id
  3255. * @param int $field_id
  3256. *
  3257. * @return array
  3258. */
  3259. public static function get_user_tags($user_id, $field_id)
  3260. {
  3261. // database table definition
  3262. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  3263. $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
  3264. $field_id = intval($field_id);
  3265. $user_id = intval($user_id);
  3266. // all the information of the field
  3267. $sql = "SELECT ut.id, tag, count
  3268. FROM $table_user_tag ut
  3269. INNER JOIN $table_user_tag_values uv
  3270. ON (uv.tag_id=ut.ID)
  3271. WHERE field_id = $field_id AND user_id = $user_id
  3272. ORDER BY tag";
  3273. $result = Database::query($sql);
  3274. $return = array();
  3275. if (Database::num_rows($result) > 0) {
  3276. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3277. $return[$row['id']] = array('tag' => $row['tag'], 'count' => $row['count']);
  3278. }
  3279. }
  3280. return $return;
  3281. }
  3282. /**
  3283. * Get user's tags
  3284. * @param int $user_id
  3285. * @param int $field_id
  3286. * @param bool $show_links show links or not
  3287. *
  3288. * @return array
  3289. */
  3290. public static function get_user_tags_to_string($user_id, $field_id, $show_links = true)
  3291. {
  3292. // database table definition
  3293. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  3294. $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
  3295. $field_id = intval($field_id);
  3296. $user_id = intval($user_id);
  3297. // all the information of the field
  3298. $sql = "SELECT ut.id, tag,count FROM $table_user_tag ut
  3299. INNER JOIN $table_user_tag_values uv
  3300. ON (uv.tag_id = ut.id)
  3301. WHERE field_id = $field_id AND user_id = $user_id
  3302. ORDER BY tag";
  3303. $result = Database::query($sql);
  3304. $return = array();
  3305. if (Database::num_rows($result) > 0) {
  3306. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3307. $return[$row['id']] = array('tag' => $row['tag'], 'count' => $row['count']);
  3308. }
  3309. }
  3310. $user_tags = $return;
  3311. $tag_tmp = array();
  3312. foreach ($user_tags as $tag) {
  3313. if ($show_links) {
  3314. $tag_tmp[] = '<a href="'.api_get_path(WEB_PATH).'main/search/index.php?q='.$tag['tag'].'">'.$tag['tag'].'</a>';
  3315. } else {
  3316. $tag_tmp[] = $tag['tag'];
  3317. }
  3318. }
  3319. if (is_array($user_tags) && count($user_tags) > 0) {
  3320. $return = implode(', ', $tag_tmp);
  3321. } else {
  3322. return '';
  3323. }
  3324. return $return;
  3325. }
  3326. /**
  3327. * Get the tag id
  3328. * @param int $tag
  3329. * @param int $field_id
  3330. * @return int returns 0 if fails otherwise the tag id
  3331. */
  3332. public static function get_tag_id($tag, $field_id)
  3333. {
  3334. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  3335. $tag = Database::escape_string($tag);
  3336. $field_id = intval($field_id);
  3337. //with COLLATE latin1_bin to select query in a case sensitive mode
  3338. $sql = "SELECT id FROM $table_user_tag
  3339. WHERE tag LIKE '$tag' AND field_id = $field_id";
  3340. $result = Database::query($sql);
  3341. if (Database::num_rows($result) > 0) {
  3342. $row = Database::fetch_array($result, 'ASSOC');
  3343. return $row['id'];
  3344. } else {
  3345. return 0;
  3346. }
  3347. }
  3348. /**
  3349. * Get the tag id
  3350. * @param int $tag_id
  3351. * @param int $field_id
  3352. *
  3353. * @return int 0 if fails otherwise the tag id
  3354. */
  3355. public static function get_tag_id_from_id($tag_id, $field_id)
  3356. {
  3357. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  3358. $tag_id = intval($tag_id);
  3359. $field_id = intval($field_id);
  3360. $sql = "SELECT id FROM $table_user_tag
  3361. WHERE id = '$tag_id' AND field_id = $field_id";
  3362. $result = Database::query($sql);
  3363. if (Database::num_rows($result) > 0) {
  3364. $row = Database::fetch_array($result, 'ASSOC');
  3365. return $row['id'];
  3366. } else {
  3367. return false;
  3368. }
  3369. }
  3370. /**
  3371. * Adds a user-tag value
  3372. * @param mixed $tag
  3373. * @param int $user_id
  3374. * @param int $field_id field id of the tag
  3375. * @return bool
  3376. */
  3377. public static function add_tag($tag, $user_id, $field_id)
  3378. {
  3379. // database table definition
  3380. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  3381. $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
  3382. $tag = trim(Database::escape_string($tag));
  3383. $user_id = intval($user_id);
  3384. $field_id = intval($field_id);
  3385. $tag_id = self::get_tag_id($tag, $field_id);
  3386. /* IMPORTANT
  3387. * @todo we don't create tags with numbers
  3388. *
  3389. */
  3390. if (is_numeric($tag)) {
  3391. //the form is sending an id this means that the user select it from the list so it MUST exists
  3392. /* $new_tag_id = self::get_tag_id_from_id($tag,$field_id);
  3393. if ($new_tag_id !== false) {
  3394. $sql = "UPDATE $table_user_tag SET count = count + 1 WHERE id = $new_tag_id";
  3395. $result = Database::query($sql);
  3396. $last_insert_id = $new_tag_id;
  3397. } else {
  3398. $sql = "INSERT INTO $table_user_tag (tag, field_id,count) VALUES ('$tag','$field_id', count + 1)";
  3399. $result = Database::query($sql);
  3400. $last_insert_id = Database::insert_id();
  3401. } */
  3402. }
  3403. //this is a new tag
  3404. if ($tag_id == 0) {
  3405. //the tag doesn't exist
  3406. $sql = "INSERT INTO $table_user_tag (tag, field_id,count) VALUES ('$tag','$field_id', count + 1)";
  3407. Database::query($sql);
  3408. $last_insert_id = Database::insert_id();
  3409. } else {
  3410. //the tag exists we update it
  3411. $sql = "UPDATE $table_user_tag SET count = count + 1 WHERE id = $tag_id";
  3412. Database::query($sql);
  3413. $last_insert_id = $tag_id;
  3414. }
  3415. if (!empty($last_insert_id) && ($last_insert_id != 0)) {
  3416. //we insert the relationship user-tag
  3417. $sql = "SELECT tag_id FROM $table_user_tag_values
  3418. WHERE user_id = $user_id AND tag_id = $last_insert_id ";
  3419. $result = Database::query($sql);
  3420. //if the relationship does not exist we create it
  3421. if (Database::num_rows($result) == 0) {
  3422. $sql = "INSERT INTO $table_user_tag_values SET user_id = $user_id, tag_id = $last_insert_id";
  3423. Database::query($sql);
  3424. }
  3425. }
  3426. }
  3427. /**
  3428. * Deletes an user tag
  3429. * @param int $user_id
  3430. * @param int $field_id
  3431. *
  3432. */
  3433. public static function delete_user_tags($user_id, $field_id)
  3434. {
  3435. // database table definition
  3436. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  3437. $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
  3438. $tags = self::get_user_tags($user_id, $field_id);
  3439. if (is_array($tags) && count($tags) > 0) {
  3440. foreach ($tags as $key => $tag) {
  3441. if ($tag['count'] > '0') {
  3442. $sql = "UPDATE $table_user_tag SET count = count - 1 WHERE id = $key ";
  3443. Database::query($sql);
  3444. }
  3445. $sql = "DELETE FROM $table_user_tag_values
  3446. WHERE user_id = $user_id AND tag_id = $key";
  3447. Database::query($sql);
  3448. }
  3449. }
  3450. }
  3451. /**
  3452. * Process the tag list comes from the UserManager::update_extra_field_value() function
  3453. * @param array $tags the tag list that will be added
  3454. * @param int $user_id
  3455. * @param int $field_id
  3456. *
  3457. * @return bool
  3458. */
  3459. public static function process_tags($tags, $user_id, $field_id)
  3460. {
  3461. // We loop the tags and add it to the DB
  3462. if (is_array($tags)) {
  3463. foreach ($tags as $tag) {
  3464. self::add_tag($tag, $user_id, $field_id);
  3465. }
  3466. } else {
  3467. self::add_tag($tags, $user_id, $field_id);
  3468. }
  3469. return true;
  3470. }
  3471. /**
  3472. * Returns a list of all administrators
  3473. *
  3474. * @return array
  3475. */
  3476. public static function get_all_administrators()
  3477. {
  3478. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  3479. $table_admin = Database::get_main_table(TABLE_MAIN_ADMIN);
  3480. $tbl_url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  3481. $access_url_id = api_get_current_access_url_id();
  3482. if (api_get_multiple_access_url()) {
  3483. $sql = "SELECT admin.user_id, username, firstname, lastname, email, active
  3484. FROM $tbl_url_rel_user as url
  3485. INNER JOIN $table_admin as admin
  3486. ON (admin.user_id=url.user_id)
  3487. INNER JOIN $table_user u
  3488. ON (u.id=admin.user_id)
  3489. WHERE access_url_id ='".$access_url_id."'";
  3490. } else {
  3491. $sql = "SELECT admin.user_id, username, firstname, lastname, email, active
  3492. FROM $table_admin as admin
  3493. INNER JOIN $table_user u
  3494. ON (u.id=admin.user_id)";
  3495. }
  3496. $result = Database::query($sql);
  3497. $return = array();
  3498. if (Database::num_rows($result) > 0) {
  3499. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3500. $return[$row['user_id']] = $row;
  3501. }
  3502. }
  3503. return $return;
  3504. }
  3505. /**
  3506. * Search an user (tags, first name, last name and email )
  3507. * @param string $tag
  3508. * @param int $field_id field id of the tag
  3509. * @param int $from where to start in the query
  3510. * @param int $number_of_items
  3511. * @param bool $getCount get count or not
  3512. * @return array
  3513. */
  3514. public static function get_all_user_tags(
  3515. $tag,
  3516. $field_id = 0,
  3517. $from = 0,
  3518. $number_of_items = 10,
  3519. $getCount = false
  3520. ) {
  3521. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  3522. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  3523. $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
  3524. $access_url_rel_user_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  3525. $field_id = intval($field_id);
  3526. $from = intval($from);
  3527. $number_of_items = intval($number_of_items);
  3528. $where_field = "";
  3529. $where_extra_fields = self::get_search_form_where_extra_fields();
  3530. if ($field_id != 0) {
  3531. $where_field = " field_id = $field_id AND ";
  3532. }
  3533. // all the information of the field
  3534. if ($getCount) {
  3535. $select = "SELECT count(DISTINCT u.id) count";
  3536. } else {
  3537. $select = "SELECT DISTINCT u.id, u.username, firstname, lastname, email, tag, picture_uri";
  3538. }
  3539. $sql = " $select
  3540. FROM $user_table u
  3541. INNER JOIN $access_url_rel_user_table url_rel_user
  3542. ON (u.id = url_rel_user.user_id)
  3543. LEFT JOIN $table_user_tag_values uv
  3544. ON (u.id AND uv.user_id AND uv.user_id = url_rel_user.user_id)
  3545. LEFT JOIN $table_user_tag ut ON (uv.tag_id = ut.id)
  3546. WHERE
  3547. ($where_field tag LIKE '".Database::escape_string($tag."%")."') OR
  3548. (
  3549. u.firstname LIKE '".Database::escape_string("%".$tag."%")."' OR
  3550. u.lastname LIKE '".Database::escape_string("%".$tag."%")."' OR
  3551. u.username LIKE '".Database::escape_string("%".$tag."%")."' OR
  3552. concat(u.firstname, ' ', u.lastname) LIKE '".Database::escape_string("%".$tag."%")."' OR
  3553. concat(u.lastname, ' ', u.firstname) LIKE '".Database::escape_string("%".$tag."%")."'
  3554. )
  3555. ".(!empty($where_extra_fields) ? $where_extra_fields : '')."
  3556. AND url_rel_user.access_url_id=".api_get_current_access_url_id();
  3557. $keyword_active = true;
  3558. // only active users
  3559. if ($keyword_active) {
  3560. $sql .= " AND u.active='1'";
  3561. }
  3562. // avoid anonymous
  3563. $sql .= " AND u.status <> 6 ";
  3564. $sql .= " ORDER BY username";
  3565. $sql .= " LIMIT $from , $number_of_items";
  3566. $result = Database::query($sql);
  3567. $return = array();
  3568. if (Database::num_rows($result) > 0) {
  3569. if ($getCount) {
  3570. $row = Database::fetch_array($result, 'ASSOC');
  3571. return $row['count'];
  3572. }
  3573. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3574. if (isset($return[$row['id']]) &&
  3575. !empty($return[$row['id']]['tag'])
  3576. ) {
  3577. $url = Display::url(
  3578. $row['tag'],
  3579. api_get_path(WEB_PATH).'main/social/search.php?q='.$row['tag'],
  3580. array('class' => 'tag')
  3581. );
  3582. $row['tag'] = $url;
  3583. }
  3584. $return[$row['id']] = $row;
  3585. }
  3586. }
  3587. return $return;
  3588. }
  3589. /**
  3590. * Get extra filtrable user fields (only type select)
  3591. * @return array
  3592. */
  3593. public static function get_extra_filtrable_fields()
  3594. {
  3595. $extraFieldList = self::get_extra_fields();
  3596. $extraFiltrableFields = array();
  3597. if (is_array($extraFieldList)) {
  3598. foreach ($extraFieldList as $extraField) {
  3599. // If is enabled to filter and is a "<select>" field type
  3600. if ($extraField[8] == 1 && $extraField[2] == 4) {
  3601. $extraFiltrableFields[] = array(
  3602. 'name' => $extraField[3],
  3603. 'variable' => $extraField[1],
  3604. 'data' => $extraField[9]
  3605. );
  3606. }
  3607. }
  3608. }
  3609. if (is_array($extraFiltrableFields) && count($extraFiltrableFields) > 0) {
  3610. return $extraFiltrableFields;
  3611. }
  3612. }
  3613. /**
  3614. * Get extra where clauses for finding users based on extra filtrable user fields (type select)
  3615. * @return string With AND clauses based on user's ID which have the values to search in extra user fields
  3616. */
  3617. public static function get_search_form_where_extra_fields()
  3618. {
  3619. $useExtraFields = false;
  3620. $extraFields = self::get_extra_filtrable_fields();
  3621. $extraFieldResult = array();
  3622. if (is_array($extraFields) && count($extraFields) > 0) {
  3623. foreach ($extraFields as $extraField) {
  3624. $varName = 'field_'.$extraField['variable'];
  3625. if (self::is_extra_field_available($extraField['variable'])) {
  3626. if (isset($_GET[$varName]) && $_GET[$varName] != '0') {
  3627. $useExtraFields = true;
  3628. $extraFieldResult[] = self::get_extra_user_data_by_value(
  3629. $extraField['variable'],
  3630. $_GET[$varName]
  3631. );
  3632. }
  3633. }
  3634. }
  3635. }
  3636. if ($useExtraFields) {
  3637. $finalResult = array();
  3638. if (count($extraFieldResult) > 1) {
  3639. for ($i = 0; $i < count($extraFieldResult) - 1; $i++) {
  3640. if (is_array($extraFieldResult[$i]) && is_array($extraFieldResult[$i + 1])) {
  3641. $finalResult = array_intersect($extraFieldResult[$i], $extraFieldResult[$i + 1]);
  3642. }
  3643. }
  3644. } else {
  3645. $finalResult = $extraFieldResult[0];
  3646. }
  3647. if (is_array($finalResult) && count($finalResult) > 0) {
  3648. $whereFilter = " AND u.id IN ('".implode("','", $finalResult)."') ";
  3649. } else {
  3650. //no results
  3651. $whereFilter = " AND u.id = -1 ";
  3652. }
  3653. return $whereFilter;
  3654. }
  3655. }
  3656. /**
  3657. * Show the search form
  3658. * @param string $query the value of the search box
  3659. * @return string HTML form
  3660. */
  3661. public static function get_search_form($query, $defaultParams = [])
  3662. {
  3663. $searchType = isset($_GET['search_type']) ? $_GET['search_type'] : null;
  3664. $form = new FormValidator(
  3665. 'search_user',
  3666. 'get',
  3667. api_get_path(WEB_PATH).'main/social/search.php',
  3668. '',
  3669. array(),
  3670. FormValidator::LAYOUT_HORIZONTAL
  3671. );
  3672. $form->addText('q', get_lang('UsersGroups'), false, array(
  3673. "id" => "q"
  3674. ));
  3675. $options = array(
  3676. 0 => get_lang('Select'),
  3677. 1 => get_lang('User'),
  3678. 2 => get_lang('Group'),
  3679. );
  3680. $form->addSelect(
  3681. 'search_type',
  3682. get_lang('Type'),
  3683. $options,
  3684. array('onchange' => 'javascript: extra_field_toogle();', 'id' => 'search_type')
  3685. );
  3686. // Extra fields
  3687. $extraFields = self::get_extra_filtrable_fields();
  3688. $defaults = [];
  3689. if (is_array($extraFields) && count($extraFields) > 0) {
  3690. foreach ($extraFields as $extraField) {
  3691. $varName = 'field_'.$extraField['variable'];
  3692. $options = [
  3693. 0 => get_lang('Select')
  3694. ];
  3695. foreach ($extraField['data'] as $option) {
  3696. $checked = '';
  3697. if (isset($_GET[$varName])) {
  3698. if ($_GET[$varName] == $option[1]) {
  3699. $defaults[$option[1]] = true;
  3700. }
  3701. }
  3702. $options[$option[1]] = $option[1];
  3703. }
  3704. $form->addSelect($varName, $extraField['name'], $options);
  3705. }
  3706. }
  3707. $defaults['search_type'] = intval($searchType);
  3708. $defaults['q'] = api_htmlentities(Security::remove_XSS($query));
  3709. if (!empty($defaultParams)) {
  3710. $defaults = array_merge($defaults, $defaultParams);
  3711. }
  3712. $form->setDefaults($defaults);
  3713. $form->addButtonSearch(get_lang('Search'));
  3714. $js = '<script>
  3715. extra_field_toogle();
  3716. function extra_field_toogle() {
  3717. if (jQuery("select[name=search_type]").val() != "1") { jQuery(".extra_field").hide(); } else { jQuery(".extra_field").show(); }
  3718. }
  3719. </script>';
  3720. return $js.$form->returnForm();
  3721. }
  3722. /**
  3723. * Shows the user menu
  3724. */
  3725. public static function show_menu()
  3726. {
  3727. echo '<div class="actions">';
  3728. echo '<a href="/main/auth/profile.php">'.Display::return_icon('profile.png').' '.get_lang('PersonalData').'</a>';
  3729. echo '<a href="/main/messages/inbox.php">'.Display::return_icon('inbox.png').' '.get_lang('Inbox').'</a>';
  3730. echo '<a href="/main/messages/outbox.php">'.Display::return_icon('outbox.png').' '.get_lang('Outbox').'</a>';
  3731. echo '<span style="float:right; padding-top:7px;">'.
  3732. '<a href="/main/auth/profile.php?show=1">'.Display::return_icon('edit.gif').' '.get_lang('Configuration').'</a>';
  3733. '</span>';
  3734. echo '</div>';
  3735. }
  3736. /**
  3737. * Allow to register contact to social network
  3738. * @param int $friend_id user friend id
  3739. * @param int $my_user_id user id
  3740. * @param int $relation_type relation between users see constants definition
  3741. */
  3742. public static function relate_users($friend_id, $my_user_id, $relation_type)
  3743. {
  3744. $tbl_my_friend = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  3745. $friend_id = intval($friend_id);
  3746. $my_user_id = intval($my_user_id);
  3747. $relation_type = intval($relation_type);
  3748. $sql = 'SELECT COUNT(*) as count FROM '.$tbl_my_friend.'
  3749. WHERE
  3750. friend_user_id='.$friend_id.' AND
  3751. user_id='.$my_user_id.' AND
  3752. relation_type <> '.USER_RELATION_TYPE_RRHH.' ';
  3753. $result = Database::query($sql);
  3754. $row = Database::fetch_array($result, 'ASSOC');
  3755. $current_date = api_get_utc_datetime();
  3756. if ($row['count'] == 0) {
  3757. $sql = 'INSERT INTO '.$tbl_my_friend.'(friend_user_id,user_id,relation_type,last_edit)
  3758. VALUES ('.$friend_id.','.$my_user_id.','.$relation_type.',"'.$current_date.'")';
  3759. Database::query($sql);
  3760. return true;
  3761. }
  3762. $sql = 'SELECT COUNT(*) as count, relation_type FROM '.$tbl_my_friend.'
  3763. WHERE
  3764. friend_user_id='.$friend_id.' AND
  3765. user_id='.$my_user_id.' AND
  3766. relation_type <> '.USER_RELATION_TYPE_RRHH.' ';
  3767. $result = Database::query($sql);
  3768. $row = Database::fetch_array($result, 'ASSOC');
  3769. if ($row['count'] == 1) {
  3770. //only for the case of a RRHH
  3771. if ($row['relation_type'] != $relation_type && $relation_type == USER_RELATION_TYPE_RRHH) {
  3772. $sql = 'INSERT INTO '.$tbl_my_friend.'(friend_user_id,user_id,relation_type,last_edit)
  3773. VALUES ('.$friend_id.','.$my_user_id.','.$relation_type.',"'.$current_date.'")';
  3774. } else {
  3775. $sql = 'UPDATE '.$tbl_my_friend.' SET relation_type='.$relation_type.'
  3776. WHERE friend_user_id='.$friend_id.' AND user_id='.$my_user_id;
  3777. }
  3778. Database::query($sql);
  3779. return true;
  3780. }
  3781. return false;
  3782. }
  3783. /**
  3784. * Deletes a contact
  3785. * @param int user friend id
  3786. * @param bool true will delete ALL friends relationship from $friend_id
  3787. * @author isaac flores paz <isaac.flores@dokeos.com>
  3788. * @author Julio Montoya <gugli100@gmail.com> Cleaning code
  3789. */
  3790. public static function remove_user_rel_user(
  3791. $friend_id,
  3792. $real_removed = false,
  3793. $with_status_condition = ''
  3794. ) {
  3795. $tbl_my_friend = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  3796. $tbl_my_message = Database::get_main_table(TABLE_MESSAGE);
  3797. $friend_id = intval($friend_id);
  3798. if ($real_removed) {
  3799. $extra_condition = '';
  3800. if ($with_status_condition != '') {
  3801. $extra_condition = ' AND relation_type = '.intval($with_status_condition);
  3802. }
  3803. $sql = 'DELETE FROM '.$tbl_my_friend.'
  3804. WHERE
  3805. relation_type <> '.USER_RELATION_TYPE_RRHH.' AND
  3806. friend_user_id='.$friend_id.' '.$extra_condition;
  3807. Database::query($sql);
  3808. $sql = 'DELETE FROM '.$tbl_my_friend.'
  3809. WHERE
  3810. relation_type <> '.USER_RELATION_TYPE_RRHH.' AND
  3811. user_id='.$friend_id.' '.$extra_condition;
  3812. Database::query($sql);
  3813. } else {
  3814. $user_id = api_get_user_id();
  3815. $sql = 'SELECT COUNT(*) as count FROM '.$tbl_my_friend.'
  3816. WHERE
  3817. user_id='.$user_id.' AND
  3818. relation_type NOT IN('.USER_RELATION_TYPE_DELETED.', '.USER_RELATION_TYPE_RRHH.') AND
  3819. friend_user_id='.$friend_id;
  3820. $result = Database::query($sql);
  3821. $row = Database::fetch_array($result, 'ASSOC');
  3822. if ($row['count'] == 1) {
  3823. //Delete user rel user
  3824. $sql_i = 'UPDATE '.$tbl_my_friend.' SET relation_type='.USER_RELATION_TYPE_DELETED.'
  3825. WHERE user_id='.$user_id.' AND friend_user_id='.$friend_id;
  3826. $sql_j = 'UPDATE '.$tbl_my_message.' SET msg_status='.MESSAGE_STATUS_INVITATION_DENIED.'
  3827. WHERE user_receiver_id='.$user_id.' AND user_sender_id='.$friend_id.' AND update_date="0000-00-00 00:00:00" ';
  3828. //Delete user
  3829. $sql_ij = 'UPDATE '.$tbl_my_friend.' SET relation_type='.USER_RELATION_TYPE_DELETED.'
  3830. WHERE user_id='.$friend_id.' AND friend_user_id='.$user_id;
  3831. $sql_ji = 'UPDATE '.$tbl_my_message.' SET msg_status='.MESSAGE_STATUS_INVITATION_DENIED.'
  3832. WHERE user_receiver_id='.$friend_id.' AND user_sender_id='.$user_id.' AND update_date="0000-00-00 00:00:00" ';
  3833. Database::query($sql_i);
  3834. Database::query($sql_j);
  3835. Database::query($sql_ij);
  3836. Database::query($sql_ji);
  3837. }
  3838. }
  3839. }
  3840. /**
  3841. * @param int $userId
  3842. * @return array
  3843. */
  3844. public static function getDrhListFromUser($userId)
  3845. {
  3846. $tblUser = Database::get_main_table(TABLE_MAIN_USER);
  3847. $tblUserRelUser = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  3848. $tblUserRelAccessUrl = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  3849. $userId = intval($userId);
  3850. $orderBy = null;
  3851. if (api_is_western_name_order()) {
  3852. $orderBy .= " ORDER BY firstname, lastname ";
  3853. } else {
  3854. $orderBy .= " ORDER BY lastname, firstname ";
  3855. }
  3856. $sql = "SELECT u.id, username, u.firstname, u.lastname
  3857. FROM $tblUser u
  3858. INNER JOIN $tblUserRelUser uru ON (uru.friend_user_id = u.id)
  3859. INNER JOIN $tblUserRelAccessUrl a ON (a.user_id = u.id)
  3860. WHERE
  3861. access_url_id = ".api_get_current_access_url_id()." AND
  3862. uru.user_id = '$userId' AND
  3863. relation_type = '".USER_RELATION_TYPE_RRHH."'
  3864. $orderBy
  3865. ";
  3866. $result = Database::query($sql);
  3867. return Database::store_result($result);
  3868. }
  3869. /**
  3870. * get users followed by human resource manager
  3871. * @param int $userId
  3872. * @param int $userStatus (STUDENT, COURSEMANAGER, etc)
  3873. * @param bool $getOnlyUserId
  3874. * @param bool $getSql
  3875. * @param bool $getCount
  3876. * @param int $from
  3877. * @param int $numberItems
  3878. * @param int $column
  3879. * @param string $direction
  3880. * @param int $active
  3881. * @param string $lastConnectionDate
  3882. * @return array users
  3883. */
  3884. public static function get_users_followed_by_drh(
  3885. $userId,
  3886. $userStatus = 0,
  3887. $getOnlyUserId = false,
  3888. $getSql = false,
  3889. $getCount = false,
  3890. $from = null,
  3891. $numberItems = null,
  3892. $column = null,
  3893. $direction = null,
  3894. $active = null,
  3895. $lastConnectionDate = null
  3896. ) {
  3897. return self::getUsersFollowedByUser(
  3898. $userId,
  3899. $userStatus,
  3900. $getOnlyUserId,
  3901. $getSql,
  3902. $getCount,
  3903. $from,
  3904. $numberItems,
  3905. $column,
  3906. $direction,
  3907. $active,
  3908. $lastConnectionDate,
  3909. DRH
  3910. );
  3911. }
  3912. /**
  3913. * Get users followed by human resource manager
  3914. * @param int $userId
  3915. * @param int $userStatus Filter users by status (STUDENT, COURSEMANAGER, etc)
  3916. * @param bool $getOnlyUserId
  3917. * @param bool $getSql
  3918. * @param bool $getCount
  3919. * @param int $from
  3920. * @param int $numberItems
  3921. * @param int $column
  3922. * @param string $direction
  3923. * @param int $active
  3924. * @param string $lastConnectionDate
  3925. * @param int $status the function is called by who? COURSEMANAGER, DRH?
  3926. * @param string $keyword
  3927. *
  3928. * @return array user list
  3929. */
  3930. public static function getUsersFollowedByUser(
  3931. $userId,
  3932. $userStatus = null,
  3933. $getOnlyUserId = false,
  3934. $getSql = false,
  3935. $getCount = false,
  3936. $from = null,
  3937. $numberItems = null,
  3938. $column = null,
  3939. $direction = null,
  3940. $active = null,
  3941. $lastConnectionDate = null,
  3942. $status = null,
  3943. $keyword = null
  3944. ) {
  3945. // Database Table Definitions
  3946. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  3947. $tbl_user_rel_user = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  3948. $tbl_user_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  3949. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  3950. $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  3951. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3952. $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  3953. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  3954. $userId = intval($userId);
  3955. $limitCondition = '';
  3956. if (isset($from) && isset($numberItems)) {
  3957. $from = intval($from);
  3958. $numberItems = intval($numberItems);
  3959. $limitCondition = "LIMIT $from, $numberItems";
  3960. }
  3961. $column = Database::escape_string($column);
  3962. $direction = in_array(strtolower($direction), array('asc', 'desc')) ? $direction : null;
  3963. $userConditions = '';
  3964. if (!empty($userStatus)) {
  3965. $userConditions .= ' AND u.status = '.intval($userStatus);
  3966. }
  3967. $select = " SELECT DISTINCT u.id user_id, u.username, u.lastname, u.firstname, u.email ";
  3968. if ($getOnlyUserId) {
  3969. $select = " SELECT DISTINCT u.id user_id";
  3970. }
  3971. $masterSelect = "SELECT DISTINCT * FROM ";
  3972. if ($getCount) {
  3973. $masterSelect = "SELECT COUNT(DISTINCT(user_id)) as count FROM ";
  3974. $select = " SELECT DISTINCT(u.id) user_id";
  3975. }
  3976. if (!is_null($active)) {
  3977. $active = intval($active);
  3978. $userConditions .= " AND u.active = $active ";
  3979. }
  3980. if (!empty($keyword)) {
  3981. $keyword = Database::escape_string($keyword);
  3982. $userConditions .= " AND (
  3983. u.username LIKE '%$keyword%' OR
  3984. u.firstname LIKE '%$keyword%' OR
  3985. u.lastname LIKE '%$keyword%' OR
  3986. u.official_code LIKE '%$keyword%' OR
  3987. u.email LIKE '%$keyword%'
  3988. )";
  3989. }
  3990. if (!empty($lastConnectionDate)) {
  3991. $lastConnectionDate = Database::escape_string($lastConnectionDate);
  3992. $userConditions .= " AND u.last_login <= '$lastConnectionDate' ";
  3993. }
  3994. $courseConditions = null;
  3995. $sessionConditionsCoach = null;
  3996. $sessionConditionsTeacher = null;
  3997. $drhConditions = null;
  3998. $teacherSelect = null;
  3999. switch ($status) {
  4000. case DRH:
  4001. $drhConditions .= " AND
  4002. friend_user_id = '$userId' AND
  4003. relation_type = '".USER_RELATION_TYPE_RRHH."'
  4004. ";
  4005. break;
  4006. case COURSEMANAGER:
  4007. $drhConditions .= " AND
  4008. friend_user_id = '$userId' AND
  4009. relation_type = '".USER_RELATION_TYPE_RRHH."'
  4010. ";
  4011. $sessionConditionsCoach .= " AND
  4012. (s.id_coach = '$userId')
  4013. ";
  4014. $sessionConditionsTeacher .= " AND
  4015. (scu.status = 2 AND scu.user_id = '$userId')
  4016. ";
  4017. $teacherSelect =
  4018. "UNION ALL (
  4019. $select
  4020. FROM $tbl_user u
  4021. INNER JOIN $tbl_session_rel_user sru ON (sru.user_id = u.id)
  4022. WHERE
  4023. (
  4024. sru.session_id IN (
  4025. SELECT DISTINCT(s.id) FROM $tbl_session s INNER JOIN
  4026. $tbl_session_rel_access_url session_rel_access_rel_user
  4027. ON session_rel_access_rel_user.session_id = s.id
  4028. WHERE access_url_id = ".api_get_current_access_url_id()."
  4029. $sessionConditionsCoach
  4030. ) OR sru.session_id IN (
  4031. SELECT DISTINCT(s.id) FROM $tbl_session s
  4032. INNER JOIN $tbl_session_rel_access_url url
  4033. ON (url.session_id = s.id)
  4034. INNER JOIN $tbl_session_rel_course_rel_user scu
  4035. ON (scu.session_id = s.id)
  4036. WHERE access_url_id = ".api_get_current_access_url_id()."
  4037. $sessionConditionsTeacher
  4038. )
  4039. )
  4040. $userConditions
  4041. )
  4042. UNION ALL(
  4043. $select
  4044. FROM $tbl_user u
  4045. INNER JOIN $tbl_course_user cu ON (cu.user_id = u.id)
  4046. WHERE cu.c_id IN (
  4047. SELECT DISTINCT(c_id) FROM $tbl_course_user
  4048. WHERE user_id = $userId AND status = ".COURSEMANAGER."
  4049. )
  4050. $userConditions
  4051. )"
  4052. ;
  4053. break;
  4054. case STUDENT_BOSS:
  4055. $drhConditions = " AND friend_user_id = $userId AND relation_type = ".USER_RELATION_TYPE_BOSS;
  4056. break;
  4057. case HRM_REQUEST:
  4058. $drhConditions .= " AND
  4059. friend_user_id = '$userId' AND
  4060. relation_type = '".USER_RELATION_TYPE_HRM_REQUEST."'
  4061. ";
  4062. break;
  4063. }
  4064. $join = null;
  4065. $sql = " $masterSelect
  4066. (
  4067. (
  4068. $select
  4069. FROM $tbl_user u
  4070. INNER JOIN $tbl_user_rel_user uru ON (uru.user_id = u.id)
  4071. LEFT JOIN $tbl_user_rel_access_url a ON (a.user_id = u.id)
  4072. $join
  4073. WHERE
  4074. access_url_id = ".api_get_current_access_url_id()."
  4075. $drhConditions
  4076. $userConditions
  4077. )
  4078. $teacherSelect
  4079. ) as t1";
  4080. if ($getSql) {
  4081. return $sql;
  4082. }
  4083. if ($getCount) {
  4084. $result = Database::query($sql);
  4085. $row = Database::fetch_array($result);
  4086. return $row['count'];
  4087. }
  4088. $orderBy = null;
  4089. if ($getOnlyUserId == false) {
  4090. if (api_is_western_name_order()) {
  4091. $orderBy .= " ORDER BY firstname, lastname ";
  4092. } else {
  4093. $orderBy .= " ORDER BY lastname, firstname ";
  4094. }
  4095. if (!empty($column) && !empty($direction)) {
  4096. // Fixing order due the UNIONs
  4097. $column = str_replace('u.', '', $column);
  4098. $orderBy = " ORDER BY $column $direction ";
  4099. }
  4100. }
  4101. $sql .= $orderBy;
  4102. $sql .= $limitCondition;
  4103. $result = Database::query($sql);
  4104. $users = array();
  4105. if (Database::num_rows($result) > 0) {
  4106. while ($row = Database::fetch_array($result)) {
  4107. $users[$row['user_id']] = $row;
  4108. }
  4109. }
  4110. return $users;
  4111. }
  4112. /**
  4113. * Subscribes users to human resource manager (Dashboard feature)
  4114. * @param int $hr_dept_id
  4115. * @param array $users_id
  4116. * @param bool $deleteOtherAssignedUsers
  4117. * @return int
  4118. */
  4119. public static function subscribeUsersToHRManager(
  4120. $hr_dept_id,
  4121. $users_id,
  4122. $deleteOtherAssignedUsers = true
  4123. ) {
  4124. return self::subscribeUsersToUser(
  4125. $hr_dept_id,
  4126. $users_id,
  4127. USER_RELATION_TYPE_RRHH,
  4128. false,
  4129. $deleteOtherAssignedUsers
  4130. );
  4131. }
  4132. /**
  4133. * Register request to assign users to HRM
  4134. * @param int $hrmId The HRM ID
  4135. * @param int $usersId The users ID
  4136. * @return int
  4137. */
  4138. public static function requestUsersToHRManager($hrmId, $usersId)
  4139. {
  4140. return self::subscribeUsersToUser(
  4141. $hrmId,
  4142. $usersId,
  4143. USER_RELATION_TYPE_HRM_REQUEST,
  4144. false,
  4145. false
  4146. );
  4147. }
  4148. /**
  4149. * Remove the requests for assign a user to a HRM
  4150. * @param \Chamilo\UserBundle\Entity\User $hrmId
  4151. */
  4152. public static function clearHrmRequestsForUser(User $hrmId)
  4153. {
  4154. Database::getManager()
  4155. ->createQuery('
  4156. DELETE FROM ChamiloCoreBundle:UserRelUser uru
  4157. WHERE uru.friendUserId = :hrm_id AND uru.relationType = :relation_type
  4158. ')
  4159. ->execute(['hrm_id' => $hrmId, 'relation_type' => USER_RELATION_TYPE_HRM_REQUEST]);
  4160. }
  4161. /**
  4162. * Add subscribed users to a user by relation type
  4163. * @param int $userId The user id
  4164. * @param array $subscribedUsersId The id of suscribed users
  4165. * @param string $relationType The relation type
  4166. * @param bool $deleteUsersBeforeInsert
  4167. * @param bool $deleteOtherAssignedUsers
  4168. * @return int
  4169. */
  4170. public static function subscribeUsersToUser(
  4171. $userId,
  4172. $subscribedUsersId,
  4173. $relationType,
  4174. $deleteUsersBeforeInsert = false,
  4175. $deleteOtherAssignedUsers = true
  4176. ) {
  4177. $userRelUserTable = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  4178. $userRelAccessUrlTable = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  4179. $userId = intval($userId);
  4180. $relationType = intval($relationType);
  4181. $affectedRows = 0;
  4182. if ($deleteOtherAssignedUsers) {
  4183. if (api_get_multiple_access_url()) {
  4184. // Deleting assigned users to hrm_id
  4185. $sql = "SELECT s.user_id
  4186. FROM $userRelUserTable s
  4187. INNER JOIN $userRelAccessUrlTable a
  4188. ON (a.user_id = s.user_id)
  4189. WHERE
  4190. friend_user_id = $userId AND
  4191. relation_type = $relationType AND
  4192. access_url_id = ".api_get_current_access_url_id();
  4193. } else {
  4194. $sql = "SELECT user_id
  4195. FROM $userRelUserTable
  4196. WHERE
  4197. friend_user_id = $userId AND
  4198. relation_type = $relationType";
  4199. }
  4200. $result = Database::query($sql);
  4201. if (Database::num_rows($result) > 0) {
  4202. while ($row = Database::fetch_array($result)) {
  4203. $sql = "DELETE FROM $userRelUserTable
  4204. WHERE
  4205. user_id = {$row['user_id']} AND
  4206. friend_user_id = $userId AND
  4207. relation_type = $relationType";
  4208. Database::query($sql);
  4209. }
  4210. }
  4211. }
  4212. if ($deleteUsersBeforeInsert) {
  4213. $sql = "DELETE FROM $userRelUserTable
  4214. WHERE
  4215. user_id = $userId AND
  4216. relation_type = $relationType";
  4217. Database::query($sql);
  4218. }
  4219. // Inserting new user list
  4220. if (is_array($subscribedUsersId)) {
  4221. foreach ($subscribedUsersId as $subscribedUserId) {
  4222. $subscribedUserId = intval($subscribedUserId);
  4223. $sql = "INSERT IGNORE INTO $userRelUserTable (user_id, friend_user_id, relation_type)
  4224. VALUES ($subscribedUserId, $userId, $relationType)";
  4225. $result = Database::query($sql);
  4226. $affectedRows = Database::affected_rows($result);
  4227. }
  4228. }
  4229. return $affectedRows;
  4230. }
  4231. /**
  4232. * This function check if an user is followed by human resources manager
  4233. * @param int $user_id
  4234. * @param int $hr_dept_id Human resources manager
  4235. * @return bool
  4236. */
  4237. public static function is_user_followed_by_drh($user_id, $hr_dept_id)
  4238. {
  4239. // Database table and variables Definitions
  4240. $tbl_user_rel_user = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  4241. $user_id = intval($user_id);
  4242. $hr_dept_id = intval($hr_dept_id);
  4243. $result = false;
  4244. $sql = "SELECT user_id FROM $tbl_user_rel_user
  4245. WHERE
  4246. user_id = $user_id AND
  4247. friend_user_id = $hr_dept_id AND
  4248. relation_type = ".USER_RELATION_TYPE_RRHH;
  4249. $rs = Database::query($sql);
  4250. if (Database::num_rows($rs) > 0) {
  4251. $result = true;
  4252. }
  4253. return $result;
  4254. }
  4255. /**
  4256. * get user id of teacher or session administrator
  4257. * @param array $courseInfo
  4258. *
  4259. * @return int The user id
  4260. */
  4261. public static function get_user_id_of_course_admin_or_session_admin($courseInfo)
  4262. {
  4263. $session = api_get_session_id();
  4264. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  4265. $table_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  4266. $table_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  4267. $courseId = $courseInfo['real_id'];
  4268. if ($session == 0 || is_null($session)) {
  4269. $sql = 'SELECT u.id uid FROM '.$table_user.' u
  4270. INNER JOIN '.$table_course_user.' ru
  4271. ON ru.user_id = u.id
  4272. WHERE
  4273. ru.status = 1 AND
  4274. ru.c_id = "'.$courseId.'" ';
  4275. $rs = Database::query($sql);
  4276. $num_rows = Database::num_rows($rs);
  4277. if ($num_rows == 1) {
  4278. $row = Database::fetch_array($rs);
  4279. return $row['uid'];
  4280. } else {
  4281. $my_num_rows = $num_rows;
  4282. $my_user_id = Database::result($rs, $my_num_rows - 1, 'uid');
  4283. return $my_user_id;
  4284. }
  4285. } elseif ($session > 0) {
  4286. $sql = 'SELECT u.id uid FROM '.$table_user.' u
  4287. INNER JOIN '.$table_session_course_user.' sru
  4288. ON sru.user_id=u.id
  4289. WHERE
  4290. sru.c_id="'.$courseId.'" AND
  4291. sru.status=2';
  4292. $rs = Database::query($sql);
  4293. $row = Database::fetch_array($rs);
  4294. return $row['uid'];
  4295. }
  4296. }
  4297. /**
  4298. * Determines if a user is a gradebook certified
  4299. * @param int $cat_id The category id of gradebook
  4300. * @param int $user_id The user id
  4301. * @return boolean
  4302. */
  4303. public static function is_user_certified($cat_id, $user_id)
  4304. {
  4305. $table_certificate = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
  4306. $sql = 'SELECT path_certificate FROM '.$table_certificate.'
  4307. WHERE
  4308. cat_id="'.intval($cat_id).'" AND
  4309. user_id="'.intval($user_id).'"';
  4310. $rs = Database::query($sql);
  4311. $row = Database::fetch_array($rs);
  4312. if ($row['path_certificate'] == '' || is_null($row['path_certificate'])) {
  4313. return false;
  4314. } else {
  4315. return true;
  4316. }
  4317. }
  4318. /**
  4319. * Gets the info about a gradebook certificate for a user by course
  4320. * @param string $course_code The course code
  4321. * @param int $user_id The user id
  4322. * @return array if there is not information return false
  4323. */
  4324. public static function getInfoGradeBookCertificate($courseId, $user_id)
  4325. {
  4326. $tbl_grade_certificate = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
  4327. $tbl_grade_category = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  4328. $session_id = api_get_session_id();
  4329. if (empty($session_id)) {
  4330. $session_condition = ' AND (session_id = "" OR session_id = 0 OR session_id IS NULL )';
  4331. } else {
  4332. $session_condition = " AND session_id = $session_id";
  4333. }
  4334. $sql = 'SELECT * FROM '.$tbl_grade_certificate.'
  4335. WHERE cat_id = (
  4336. SELECT id FROM '.$tbl_grade_category.'
  4337. WHERE
  4338. c_id = "'.Database::escape_string($courseId).'" '.$session_condition.'
  4339. LIMIT 1
  4340. )
  4341. AND user_id='.intval($user_id);
  4342. $rs = Database::query($sql);
  4343. if (Database::num_rows($rs) > 0) {
  4344. $row = Database::fetch_array($rs, 'ASSOC');
  4345. $score = $row['score_certificate'];
  4346. $category_id = $row['cat_id'];
  4347. $cat = Category::load($category_id);
  4348. $displayscore = ScoreDisplay::instance();
  4349. if (isset($cat) && $displayscore->is_custom()) {
  4350. $grade = $displayscore->display_score(
  4351. array($score, $cat[0]->get_weight()),
  4352. SCORE_DIV_PERCENT_WITH_CUSTOM
  4353. );
  4354. } else {
  4355. $grade = $displayscore->display_score(
  4356. array($score, $cat[0]->get_weight())
  4357. );
  4358. }
  4359. $row['grade'] = $grade;
  4360. return $row;
  4361. }
  4362. return false;
  4363. }
  4364. /**
  4365. * Gets the user path of user certificated
  4366. * @param int The user id
  4367. * @return array containing path_certificate and cat_id
  4368. */
  4369. public static function get_user_path_certificate($user_id)
  4370. {
  4371. $my_certificate = array();
  4372. $table_certificate = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
  4373. $table_gradebook_category = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  4374. $session_id = api_get_session_id();
  4375. $user_id = intval($user_id);
  4376. if ($session_id == 0 || is_null($session_id)) {
  4377. $sql_session = 'AND (session_id='.intval($session_id).' OR isnull(session_id)) ';
  4378. } elseif ($session_id > 0) {
  4379. $sql_session = 'AND session_id='.intval($session_id);
  4380. } else {
  4381. $sql_session = '';
  4382. }
  4383. $sql = "SELECT tc.path_certificate,tc.cat_id,tgc.course_code,tgc.name
  4384. FROM $table_certificate tc, $table_gradebook_category tgc
  4385. WHERE tgc.id = tc.cat_id AND tc.user_id = $user_id
  4386. ORDER BY tc.date_certificate DESC
  4387. LIMIT 5";
  4388. $rs = Database::query($sql);
  4389. while ($row = Database::fetch_array($rs)) {
  4390. $my_certificate[] = $row;
  4391. }
  4392. return $my_certificate;
  4393. }
  4394. /**
  4395. * This function check if the user is a coach inside session course
  4396. * @param int $user_id User id
  4397. * @param int $courseId
  4398. * @param int $session_id
  4399. * @return bool True if the user is a coach
  4400. *
  4401. */
  4402. public static function is_session_course_coach($user_id, $courseId, $session_id)
  4403. {
  4404. $tbl_session_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  4405. // Protect data
  4406. $user_id = intval($user_id);
  4407. $courseId = intval($courseId);
  4408. $session_id = intval($session_id);
  4409. $result = false;
  4410. $sql = "SELECT session_id FROM $tbl_session_course_rel_user
  4411. WHERE
  4412. session_id = $session_id AND
  4413. c_id = $courseId AND
  4414. user_id = $user_id AND
  4415. status = 2 ";
  4416. $res = Database::query($sql);
  4417. if (Database::num_rows($res) > 0) {
  4418. $result = true;
  4419. }
  4420. return $result;
  4421. }
  4422. /**
  4423. * This function returns an icon path that represents the favicon of the website of which the url given.
  4424. * Defaults to the current Chamilo favicon
  4425. * @param string $url1 URL of website where to look for favicon.ico
  4426. * @param string $url2 Optional second URL of website where to look for favicon.ico
  4427. * @return string Path of icon to load
  4428. */
  4429. public static function get_favicon_from_url($url1, $url2 = null)
  4430. {
  4431. $icon_link = '';
  4432. $url = $url1;
  4433. if (empty($url1)) {
  4434. $url = $url2;
  4435. if (empty($url)) {
  4436. $url = api_get_access_url(api_get_current_access_url_id());
  4437. $url = $url[0];
  4438. }
  4439. }
  4440. if (!empty($url)) {
  4441. $pieces = parse_url($url);
  4442. $icon_link = $pieces['scheme'].'://'.$pieces['host'].'/favicon.ico';
  4443. }
  4444. return $icon_link;
  4445. }
  4446. /**
  4447. *
  4448. * @param int $student_id
  4449. * @param int $years
  4450. * @param bool $warning_message show warning_message
  4451. * @param bool $return_timestamp return_timestamp
  4452. */
  4453. public static function delete_inactive_student(
  4454. $student_id,
  4455. $years = 2,
  4456. $warning_message = false,
  4457. $return_timestamp = false
  4458. ) {
  4459. $tbl_track_login = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  4460. $sql = 'SELECT login_date FROM '.$tbl_track_login.'
  4461. WHERE login_user_id = '.intval($student_id).'
  4462. ORDER BY login_date DESC LIMIT 0,1';
  4463. if (empty($years)) {
  4464. $years = 1;
  4465. }
  4466. $inactive_time = $years * 31536000; //1 year
  4467. $rs = Database::query($sql);
  4468. if (Database::num_rows($rs) > 0) {
  4469. if ($last_login_date = Database::result($rs, 0, 0)) {
  4470. $last_login_date = api_get_local_time(
  4471. $last_login_date,
  4472. null,
  4473. date_default_timezone_get()
  4474. );
  4475. if ($return_timestamp) {
  4476. return api_strtotime($last_login_date);
  4477. } else {
  4478. if (!$warning_message) {
  4479. return api_format_date($last_login_date, DATE_FORMAT_SHORT);
  4480. } else {
  4481. $timestamp = api_strtotime($last_login_date);
  4482. $currentTimestamp = time();
  4483. //If the last connection is > than 7 days, the text is red
  4484. //345600 = 7 days in seconds 63072000= 2 ans
  4485. // if ($currentTimestamp - $timestamp > 184590 )
  4486. if ($currentTimestamp - $timestamp > $inactive_time && self::delete_user($student_id)) {
  4487. echo Display::return_message(get_lang('UserDeleted'));
  4488. echo '<p>', 'id', $student_id, ':', $last_login_date, '</p>';
  4489. }
  4490. }
  4491. }
  4492. }
  4493. }
  4494. return false;
  4495. }
  4496. /**
  4497. * @return array
  4498. */
  4499. public static function get_user_field_types()
  4500. {
  4501. $types = array();
  4502. $types[self::USER_FIELD_TYPE_TEXT] = get_lang('FieldTypeText');
  4503. $types[self::USER_FIELD_TYPE_TEXTAREA] = get_lang('FieldTypeTextarea');
  4504. $types[self::USER_FIELD_TYPE_RADIO] = get_lang('FieldTypeRadio');
  4505. $types[self::USER_FIELD_TYPE_SELECT] = get_lang('FieldTypeSelect');
  4506. $types[self::USER_FIELD_TYPE_SELECT_MULTIPLE] = get_lang('FieldTypeSelectMultiple');
  4507. $types[self::USER_FIELD_TYPE_DATE] = get_lang('FieldTypeDate');
  4508. $types[self::USER_FIELD_TYPE_DATETIME] = get_lang('FieldTypeDatetime');
  4509. $types[self::USER_FIELD_TYPE_DOUBLE_SELECT] = get_lang('FieldTypeDoubleSelect');
  4510. $types[self::USER_FIELD_TYPE_DIVIDER] = get_lang('FieldTypeDivider');
  4511. $types[self::USER_FIELD_TYPE_TAG] = get_lang('FieldTypeTag');
  4512. $types[self::USER_FIELD_TYPE_TIMEZONE] = get_lang('FieldTypeTimezone');
  4513. $types[self::USER_FIELD_TYPE_SOCIAL_PROFILE] = get_lang('FieldTypeSocialProfile');
  4514. $types[self::USER_FIELD_TYPE_FILE] = get_lang('FieldTypeFile');
  4515. $types[self::USER_FIELD_TYPE_MOBILE_PHONE_NUMBER] = get_lang('FieldTypeMobilePhoneNumber');
  4516. return $types;
  4517. }
  4518. /**
  4519. * @param User $user
  4520. */
  4521. public static function add_user_as_admin(User $user)
  4522. {
  4523. $table_admin = Database::get_main_table(TABLE_MAIN_ADMIN);
  4524. if ($user) {
  4525. $userId = $user->getId();
  4526. if (!self::is_admin($userId)) {
  4527. $sql = "INSERT INTO $table_admin SET user_id = $userId";
  4528. Database::query($sql);
  4529. }
  4530. $user->addRole('ROLE_SUPER_ADMIN');
  4531. self::getManager()->updateUser($user, true);
  4532. }
  4533. }
  4534. /**
  4535. * @param int $userId
  4536. */
  4537. public static function remove_user_admin($userId)
  4538. {
  4539. $table_admin = Database::get_main_table(TABLE_MAIN_ADMIN);
  4540. $userId = intval($userId);
  4541. if (self::is_admin($userId)) {
  4542. $sql = "DELETE FROM $table_admin WHERE user_id = $userId";
  4543. Database::query($sql);
  4544. }
  4545. }
  4546. /**
  4547. * @param string $from
  4548. * @param string $to
  4549. */
  4550. public static function update_all_user_languages($from, $to)
  4551. {
  4552. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  4553. $from = Database::escape_string($from);
  4554. $to = Database::escape_string($to);
  4555. if (!empty($to) && !empty($from)) {
  4556. $sql = "UPDATE $table_user SET language = '$to'
  4557. WHERE language = '$from'";
  4558. Database::query($sql);
  4559. }
  4560. }
  4561. /**
  4562. * Subscribe boss to students
  4563. *
  4564. * @param int $bossId The boss id
  4565. * @param array $usersId The users array
  4566. * @return int Affected rows
  4567. */
  4568. public static function subscribeBossToUsers($bossId, $usersId)
  4569. {
  4570. return self::subscribeUsersToUser(
  4571. $bossId,
  4572. $usersId,
  4573. USER_RELATION_TYPE_BOSS
  4574. );
  4575. }
  4576. /**
  4577. * Subscribe boss to students
  4578. *
  4579. * @param int $studentId
  4580. * @param array $bossList
  4581. * @param bool $sendNotification
  4582. * @return int Affected rows
  4583. */
  4584. public static function subscribeUserToBossList(
  4585. $studentId,
  4586. $bossList,
  4587. $sendNotification = false
  4588. ) {
  4589. if ($bossList) {
  4590. $studentId = (int) $studentId;
  4591. $studentInfo = api_get_user_info($studentId);
  4592. if (empty($studentInfo)) {
  4593. return false;
  4594. }
  4595. $userRelUserTable = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  4596. $sql = "DELETE FROM $userRelUserTable
  4597. WHERE user_id = $studentId AND relation_type = ".USER_RELATION_TYPE_BOSS;
  4598. Database::query($sql);
  4599. foreach ($bossList as $bossId) {
  4600. $bossId = (int) $bossId;
  4601. $sql = "INSERT IGNORE INTO $userRelUserTable (user_id, friend_user_id, relation_type)
  4602. VALUES ($studentId, $bossId, ".USER_RELATION_TYPE_BOSS.")";
  4603. $insertId = Database::query($sql);
  4604. if ($insertId && $sendNotification) {
  4605. $name = $studentInfo['complete_name'];
  4606. $url = api_get_path(WEB_CODE_PATH).'mySpace/myStudents.php?student='.$studentId;
  4607. $url = Display::url($url, $url);
  4608. $subject = sprintf(get_lang('UserXHasBeenAssignedToBoss'), $name);
  4609. $message = sprintf(get_lang('UserXHasBeenAssignedToBossWithUrlX'), $name, $url);
  4610. MessageManager::send_message_simple(
  4611. $bossId,
  4612. $subject,
  4613. $message
  4614. );
  4615. }
  4616. }
  4617. }
  4618. }
  4619. /**
  4620. * Get users followed by student boss
  4621. * @param int $userId
  4622. * @param int $userStatus (STUDENT, COURSEMANAGER, etc)
  4623. * @param bool $getOnlyUserId
  4624. * @param bool $getSql
  4625. * @param bool $getCount
  4626. * @param int $from
  4627. * @param int $numberItems
  4628. * @param int $column
  4629. * @param string $direction
  4630. * @param int $active
  4631. * @param string $lastConnectionDate
  4632. * @return array users
  4633. */
  4634. public static function getUsersFollowedByStudentBoss(
  4635. $userId,
  4636. $userStatus = 0,
  4637. $getOnlyUserId = false,
  4638. $getSql = false,
  4639. $getCount = false,
  4640. $from = null,
  4641. $numberItems = null,
  4642. $column = null,
  4643. $direction = null,
  4644. $active = null,
  4645. $lastConnectionDate = null
  4646. ) {
  4647. return self::getUsersFollowedByUser(
  4648. $userId,
  4649. $userStatus,
  4650. $getOnlyUserId,
  4651. $getSql,
  4652. $getCount,
  4653. $from,
  4654. $numberItems,
  4655. $column,
  4656. $direction,
  4657. $active,
  4658. $lastConnectionDate,
  4659. STUDENT_BOSS
  4660. );
  4661. }
  4662. /**
  4663. * Get the teacher (users with COURSEMANGER status) list
  4664. * @return array The list
  4665. */
  4666. public static function getTeachersList()
  4667. {
  4668. $userTable = Database::get_main_table(TABLE_MAIN_USER);
  4669. $resultData = Database::select(
  4670. 'user_id, lastname, firstname, username',
  4671. $userTable,
  4672. array(
  4673. 'where' => array(
  4674. 'status = ?' => COURSEMANAGER
  4675. )
  4676. ));
  4677. foreach ($resultData as &$teacherData) {
  4678. $teacherData['completeName'] = api_get_person_name(
  4679. $teacherData['firstname'],
  4680. $teacherData['lastname']
  4681. );
  4682. }
  4683. return $resultData;
  4684. }
  4685. /**
  4686. * @return array
  4687. */
  4688. public static function getOfficialCodeGrouped()
  4689. {
  4690. $user = Database::get_main_table(TABLE_MAIN_USER);
  4691. $sql = "SELECT DISTINCT official_code
  4692. FROM $user
  4693. GROUP BY official_code";
  4694. $result = Database::query($sql);
  4695. $values = Database::store_result($result, 'ASSOC');
  4696. $result = array();
  4697. foreach ($values as $value) {
  4698. $result[$value['official_code']] = $value['official_code'];
  4699. }
  4700. return $result;
  4701. }
  4702. /**
  4703. * @param string $officialCode
  4704. * @return array
  4705. */
  4706. public static function getUsersByOfficialCode($officialCode)
  4707. {
  4708. $user = Database::get_main_table(TABLE_MAIN_USER);
  4709. $officialCode = Database::escape_string($officialCode);
  4710. $sql = "SELECT DISTINCT id
  4711. FROM $user
  4712. WHERE official_code = '$officialCode'
  4713. ";
  4714. $result = Database::query($sql);
  4715. $users = array();
  4716. while ($row = Database::fetch_array($result)) {
  4717. $users[] = $row['id'];
  4718. }
  4719. return $users;
  4720. }
  4721. /**
  4722. * Calc the expended time (in seconds) by a user in a course
  4723. * @param int $userId The user id
  4724. * @param int $courseId The course id
  4725. * @param int $sessionId Optional. The session id
  4726. * @param string $from Optional. From date
  4727. * @param string $until Optional. Until date
  4728. * @return int The time
  4729. */
  4730. public static function getTimeSpentInCourses(
  4731. $userId,
  4732. $courseId,
  4733. $sessionId = 0,
  4734. $from = '',
  4735. $until = ''
  4736. ) {
  4737. $userId = intval($userId);
  4738. $sessionId = intval($sessionId);
  4739. $trackCourseAccessTable = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  4740. $whereConditions = array(
  4741. 'user_id = ? ' => $userId,
  4742. 'AND c_id = ? ' => $courseId,
  4743. 'AND session_id = ? ' => $sessionId
  4744. );
  4745. if (!empty($from) && !empty($until)) {
  4746. $whereConditions["AND (login_course_date >= '?' "] = $from;
  4747. $whereConditions["AND logout_course_date <= DATE_ADD('?', INTERVAL 1 DAY)) "] = $until;
  4748. }
  4749. $trackResult = Database::select(
  4750. 'SUM(UNIX_TIMESTAMP(logout_course_date) - UNIX_TIMESTAMP(login_course_date)) as total_time',
  4751. $trackCourseAccessTable,
  4752. array(
  4753. 'where' => $whereConditions
  4754. ), 'first'
  4755. );
  4756. if ($trackResult != false) {
  4757. return $trackResult['total_time'] ? $trackResult['total_time'] : 0;
  4758. }
  4759. return 0;
  4760. }
  4761. /**
  4762. * Get the boss user ID from a followed user id
  4763. * @param $userId
  4764. * @return bool
  4765. */
  4766. public static function getFirstStudentBoss($userId)
  4767. {
  4768. $userId = intval($userId);
  4769. if ($userId > 0) {
  4770. $userRelTable = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  4771. $row = Database::select(
  4772. 'DISTINCT friend_user_id AS boss_id',
  4773. $userRelTable,
  4774. array(
  4775. 'where' => array(
  4776. 'user_id = ? AND relation_type = ? LIMIT 1' => array(
  4777. $userId,
  4778. USER_RELATION_TYPE_BOSS,
  4779. )
  4780. )
  4781. )
  4782. );
  4783. if (!empty($row)) {
  4784. return $row[0]['boss_id'];
  4785. }
  4786. }
  4787. return false;
  4788. }
  4789. /**
  4790. * Get the boss user ID from a followed user id
  4791. * @param $userId
  4792. * @return bool
  4793. */
  4794. public static function getStudentBossList($userId)
  4795. {
  4796. $userId = intval($userId);
  4797. if ($userId > 0) {
  4798. $userRelTable = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  4799. $result = Database::select(
  4800. 'DISTINCT friend_user_id AS boss_id',
  4801. $userRelTable,
  4802. array(
  4803. 'where' => array(
  4804. 'user_id = ? AND relation_type = ? ' => array(
  4805. $userId,
  4806. USER_RELATION_TYPE_BOSS,
  4807. )
  4808. )
  4809. ),
  4810. 'all'
  4811. );
  4812. return $result;
  4813. }
  4814. return false;
  4815. }
  4816. /**
  4817. * @param int $bossId
  4818. * @param int $studentId
  4819. *
  4820. * @return bool
  4821. */
  4822. public static function userIsBossOfStudent($bossId, $studentId)
  4823. {
  4824. $result = false;
  4825. $bossList = self::getStudentBossList($studentId);
  4826. if ($bossList) {
  4827. $bossList = array_column($bossList, 'boss_id');
  4828. if (in_array($bossId, $bossList)) {
  4829. $result = true;
  4830. }
  4831. }
  4832. return $result;
  4833. }
  4834. /**
  4835. * Get either a Gravatar URL or complete image tag for a specified email address.
  4836. *
  4837. * @param string $email The email address
  4838. * @param string $s Size in pixels, defaults to 80px [ 1 - 2048 ]
  4839. * @param string $d Default imageset to use [ 404 | mm | identicon | monsterid | wavatar ]
  4840. * @param string $r Maximum rating (inclusive) [ g | pg | r | x ]
  4841. * @param boole $img True to return a complete IMG tag False for just the URL
  4842. * @param array $atts Optional, additional key/value attributes to include in the IMG tag
  4843. * @return String containing either just a URL or a complete image tag
  4844. * @source http://gravatar.com/site/implement/images/php/
  4845. */
  4846. private static function getGravatar(
  4847. $email,
  4848. $s = 80,
  4849. $d = 'mm',
  4850. $r = 'g',
  4851. $img = false,
  4852. $atts = array()
  4853. ) {
  4854. $url = 'http://www.gravatar.com/avatar/';
  4855. if (!empty($_SERVER['HTTPS'])) {
  4856. $url = 'https://secure.gravatar.com/avatar/';
  4857. }
  4858. $url .= md5(strtolower(trim($email)));
  4859. $url .= "?s=$s&d=$d&r=$r";
  4860. if ($img) {
  4861. $url = '<img src="'.$url.'"';
  4862. foreach ($atts as $key => $val)
  4863. $url .= ' '.$key.'="'.$val.'"';
  4864. $url .= ' />';
  4865. }
  4866. return $url;
  4867. }
  4868. /**
  4869. * Displays the name of the user and makes the link to the user profile
  4870. * @param array $userInfo
  4871. *
  4872. * @return string
  4873. */
  4874. public static function getUserProfileLink($userInfo)
  4875. {
  4876. if (isset($userInfo) && isset($userInfo['user_id'])) {
  4877. return Display::url(
  4878. $userInfo['complete_name_with_username'],
  4879. $userInfo['profile_url']
  4880. );
  4881. } else {
  4882. return get_lang('Anonymous');
  4883. }
  4884. }
  4885. /**
  4886. * Displays the name of the user and makes the link to the user profile
  4887. *
  4888. * @param $userInfo
  4889. *
  4890. * @return string
  4891. */
  4892. public static function getUserProfileLinkWithPicture($userInfo)
  4893. {
  4894. return Display::url(
  4895. Display::img($userInfo['avatar']),
  4896. $userInfo['profile_url']
  4897. );
  4898. }
  4899. /**
  4900. * Get users whose name matches $firstname and $lastname
  4901. * @param string $firstname Firstname to search
  4902. * @param string $lastname Lastname to search
  4903. * @return array The user list
  4904. */
  4905. public static function getUsersByName($firstname, $lastname)
  4906. {
  4907. $firstname = Database::escape_string($firstname);
  4908. $lastname = Database::escape_string($lastname);
  4909. $userTable = Database::get_main_table(TABLE_MAIN_USER);
  4910. $sql = <<<SQL
  4911. SELECT id, username, lastname, firstname
  4912. FROM $userTable
  4913. WHERE
  4914. firstname LIKE '$firstname%' AND
  4915. lastname LIKE '$lastname%'
  4916. SQL;
  4917. $result = Database::query($sql);
  4918. $users = [];
  4919. while ($resultData = Database::fetch_object($result)) {
  4920. $users[] = $resultData;
  4921. }
  4922. return $users;
  4923. }
  4924. /**
  4925. * @param int $optionSelected
  4926. * @return string
  4927. */
  4928. public static function getUserSubscriptionTab($optionSelected = 1)
  4929. {
  4930. $allowAdmin = api_get_setting('allow_user_course_subscription_by_course_admin');
  4931. if (($allowAdmin === 'true' && api_is_allowed_to_edit()) ||
  4932. api_is_platform_admin()
  4933. ) {
  4934. $userPath = api_get_path(WEB_CODE_PATH).'user/';
  4935. $headers = [
  4936. [
  4937. 'url' => $userPath.'user.php?'.api_get_cidreq().'&type='.STUDENT,
  4938. 'content' => get_lang('Students'),
  4939. ],
  4940. [
  4941. 'url' => $userPath.'user.php?'.api_get_cidreq().'&type='.COURSEMANAGER,
  4942. 'content' => get_lang('Teachers'),
  4943. ],
  4944. /*[
  4945. 'url' => $userPath.'subscribe_user.php?'.api_get_cidreq(),
  4946. 'content' => get_lang('Students'),
  4947. ],
  4948. [
  4949. 'url' => $userPath.'subscribe_user.php?type=teacher&'.api_get_cidreq(),
  4950. 'content' => get_lang('Teachers'),
  4951. ],*/
  4952. [
  4953. 'url' => api_get_path(WEB_CODE_PATH).'group/group.php?'.api_get_cidreq(),
  4954. 'content' => get_lang('Groups'),
  4955. ],
  4956. [
  4957. 'url' => $userPath.'class.php?'.api_get_cidreq(),
  4958. 'content' => get_lang('Classes'),
  4959. ]
  4960. ];
  4961. return Display::tabsOnlyLink($headers, $optionSelected);
  4962. }
  4963. }
  4964. /**
  4965. * Make sure this function is protected because it does NOT check password!
  4966. *
  4967. * This function defines globals.
  4968. * @param int $userId
  4969. * @param bool $checkIfUserCanLoginAs
  4970. * @return array
  4971. * @author Evie Embrechts
  4972. * @author Yannick Warnier <yannick.warnier@dokeos.com>
  4973. */
  4974. public static function loginAsUser($userId, $checkIfUserCanLoginAs = true)
  4975. {
  4976. $userId = intval($userId);
  4977. $userInfo = api_get_user_info($userId);
  4978. // Check if the user is allowed to 'login_as'
  4979. $canLoginAs = true;
  4980. if ($checkIfUserCanLoginAs) {
  4981. $canLoginAs = api_can_login_as($userId);
  4982. }
  4983. if (!$canLoginAs || empty($userInfo)) {
  4984. return false;
  4985. }
  4986. if ($userId) {
  4987. // Logout the current user
  4988. self::loginDelete(api_get_user_id());
  4989. Session::erase('_user');
  4990. Session::erase('is_platformAdmin');
  4991. Session::erase('is_allowedCreateCourse');
  4992. Session::erase('_uid');
  4993. // Cleaning session variables
  4994. $_user['firstName'] = $userInfo['firstname'];
  4995. $_user['lastName'] = $userInfo['lastname'];
  4996. $_user['mail'] = $userInfo['email'];
  4997. $_user['official_code'] = $userInfo['official_code'];
  4998. $_user['picture_uri'] = $userInfo['picture_uri'];
  4999. $_user['user_id'] = $userId;
  5000. $_user['id'] = $userId;
  5001. $_user['status'] = $userInfo['status'];
  5002. // Filling session variables with new data
  5003. Session::write('_uid', $userId);
  5004. Session::write('_user', $userInfo);
  5005. Session::write('is_platformAdmin', (bool) UserManager::is_admin($userId));
  5006. Session::write('is_allowedCreateCourse', (bool) ($userInfo['status'] == 1));
  5007. // will be useful later to know if the user is actually an admin or not (example reporting)
  5008. Session::write('login_as', true);
  5009. return true;
  5010. }
  5011. return false;
  5012. }
  5013. /**
  5014. * Remove all login records from the track_e_online stats table,
  5015. * for the given user ID.
  5016. * @param int User ID
  5017. * @param integer $user_id
  5018. * @return void
  5019. */
  5020. public static function loginDelete($user_id)
  5021. {
  5022. $online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
  5023. $user_id = intval($user_id);
  5024. $query = "DELETE FROM ".$online_table." WHERE login_user_id = $user_id";
  5025. Database::query($query);
  5026. }
  5027. /**
  5028. * Login as first admin user registered in the platform
  5029. * @return array
  5030. */
  5031. public static function logInAsFirstAdmin()
  5032. {
  5033. $adminList = self::get_all_administrators();
  5034. if (!empty($adminList)) {
  5035. $userInfo = current($adminList);
  5036. if (!empty($userInfo)) {
  5037. $result = self::loginAsUser($userInfo['user_id'], false);
  5038. if ($result && api_is_platform_admin()) {
  5039. return api_get_user_info();
  5040. }
  5041. }
  5042. }
  5043. return [];
  5044. }
  5045. /**
  5046. * Check if user is teacher of a student based in their courses
  5047. * @param $teacherId
  5048. * @param $studentId
  5049. * @return array
  5050. */
  5051. public static function getCommonCoursesBetweenTeacherAndStudent($teacherId, $studentId)
  5052. {
  5053. $courses = CourseManager::getCoursesFollowedByUser(
  5054. $teacherId,
  5055. COURSEMANAGER
  5056. );
  5057. if (empty($courses)) {
  5058. return false;
  5059. }
  5060. $coursesFromUser = CourseManager::get_courses_list_by_user_id($studentId);
  5061. if (empty($coursesFromUser)) {
  5062. return false;
  5063. }
  5064. $coursesCodeList = array_column($courses, 'code');
  5065. $coursesCodeFromUserList = array_column($coursesFromUser, 'code');
  5066. $commonCourses = array_intersect($coursesCodeList, $coursesCodeFromUserList);
  5067. $commonCourses = array_filter($commonCourses);
  5068. if (!empty($commonCourses)) {
  5069. return $commonCourses;
  5070. }
  5071. return [];
  5072. }
  5073. /**
  5074. * @param $teacherId
  5075. * @param $studentId
  5076. * @return bool
  5077. */
  5078. public static function isTeacherOfStudent($teacherId, $studentId)
  5079. {
  5080. $courses = self::getCommonCoursesBetweenTeacherAndStudent(
  5081. $teacherId,
  5082. $studentId
  5083. );
  5084. if (!empty($courses)) {
  5085. return true;
  5086. }
  5087. return false;
  5088. }
  5089. /**
  5090. * @param int $user_id
  5091. * @return bool
  5092. */
  5093. public static function user_is_online($user_id)
  5094. {
  5095. $track_online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
  5096. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  5097. $access_url_id = api_get_current_access_url_id();
  5098. $time_limit = api_get_setting('display.time_limit_whosonline');
  5099. $online_time = time() - $time_limit*60;
  5100. $limit_date = api_get_utc_datetime($online_time);
  5101. $user_id = intval($user_id);
  5102. $query = " SELECT login_user_id,login_date
  5103. FROM $track_online_table track
  5104. INNER JOIN $table_user u ON (u.id=track.login_user_id)
  5105. WHERE
  5106. track.access_url_id = $access_url_id AND
  5107. login_date >= '".$limit_date."' AND
  5108. u.id = $user_id
  5109. LIMIT 1 ";
  5110. $result = Database::query($query);
  5111. if (Database::num_rows($result)) {
  5112. return true;
  5113. }
  5114. return false;
  5115. }
  5116. /**
  5117. * @param int $time_limit seconds
  5118. * @param bool $friends show friends (true) or all users (false)
  5119. * @return bool
  5120. */
  5121. public static function whoIsOnlineCount(
  5122. $time_limit = 0,
  5123. $friends = false
  5124. ) {
  5125. if (empty($time_limit)) {
  5126. $time_limit = api_get_setting('display.time_limit_whosonline');
  5127. } else {
  5128. $time_limit = intval($time_limit);
  5129. }
  5130. $track_online_table = Database::get_main_table(
  5131. TABLE_STATISTIC_TRACK_E_ONLINE
  5132. );
  5133. $friend_user_table = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  5134. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  5135. $online_time = time() - $time_limit * 60;
  5136. $current_date = api_get_utc_datetime($online_time);
  5137. if ($friends) {
  5138. // who friends from social network is online
  5139. $query = "SELECT DISTINCT count(login_user_id) as count
  5140. FROM $track_online_table INNER JOIN $friend_user_table
  5141. ON (friend_user_id = login_user_id)
  5142. WHERE
  5143. login_date >= '$current_date' AND
  5144. friend_user_id <> '".api_get_user_id()."' AND
  5145. relation_type='".USER_RELATION_TYPE_FRIEND."' AND
  5146. user_id = '".api_get_user_id()."' ";
  5147. } else {
  5148. // All users online
  5149. $query = "SELECT count(login_id) as count
  5150. FROM $track_online_table track INNER JOIN $table_user u
  5151. ON (u.id=track.login_user_id)
  5152. WHERE u.status != ".ANONYMOUS." AND login_date >= '$current_date' ";
  5153. }
  5154. if (api_get_multiple_access_url()) {
  5155. $access_url_id = api_get_current_access_url_id();
  5156. if ($access_url_id != -1) {
  5157. if ($friends) {
  5158. // friends from social network is online
  5159. $query = "SELECT DISTINCT count(login_user_id) as count
  5160. FROM $track_online_table track
  5161. INNER JOIN $friend_user_table ON (friend_user_id = login_user_id)
  5162. WHERE
  5163. track.access_url_id = $access_url_id AND
  5164. login_date >= '".$current_date."' AND
  5165. friend_user_id <> '".api_get_user_id()."' AND
  5166. relation_type='".USER_RELATION_TYPE_FRIEND."' ";
  5167. } else {
  5168. // all users online
  5169. $query = "SELECT count(login_id) as count FROM $track_online_table track
  5170. INNER JOIN $table_user u ON (u.id=track.login_user_id)
  5171. WHERE
  5172. u.status != ".ANONYMOUS." AND
  5173. track.access_url_id = $access_url_id AND
  5174. login_date >= '$current_date' ";
  5175. }
  5176. }
  5177. }
  5178. // Dev purposes show all users online
  5179. /*$table_user = Database::get_main_table(TABLE_MAIN_USER);
  5180. $query = "SELECT count(*) as count FROM ".$table_user;*/
  5181. $result = Database::query($query);
  5182. if (Database::num_rows($result) > 0) {
  5183. $row = Database::fetch_array($result);
  5184. return $row['count'];
  5185. } else {
  5186. return false;
  5187. }
  5188. }
  5189. /**
  5190. * Gives a list of people online now (and in the last $valid minutes)
  5191. *
  5192. * @param int $from
  5193. * @param int $number_of_items
  5194. * @param string $column
  5195. * @param string $direction
  5196. * @param int $time_limit in seconds
  5197. * @param bool $friends show friends (true) or all users (false)
  5198. * @return array|bool
  5199. */
  5200. public static function whoIsOnline(
  5201. $from,
  5202. $number_of_items,
  5203. $column = '',
  5204. $direction = '',
  5205. $time_limit = 0,
  5206. $friends = false
  5207. ) {
  5208. // Time limit in seconds?
  5209. if (empty($time_limit)) {
  5210. $time_limit = api_get_setting('display.time_limit_whosonline');
  5211. } else {
  5212. $time_limit = intval($time_limit);
  5213. }
  5214. $from = intval($from);
  5215. $number_of_items = intval($number_of_items);
  5216. if (empty($column)) {
  5217. $column = 'picture_uri';
  5218. if ($friends) {
  5219. $column = 'login_date';
  5220. }
  5221. }
  5222. if (empty($direction)) {
  5223. $direction = 'DESC';
  5224. } else {
  5225. if (!in_array(strtolower($direction), array('asc', 'desc'))) {
  5226. $direction = 'DESC';
  5227. }
  5228. }
  5229. $online_time = time() - $time_limit * 60;
  5230. $current_date = api_get_utc_datetime($online_time);
  5231. $track_online_table = Database::get_main_table(
  5232. TABLE_STATISTIC_TRACK_E_ONLINE
  5233. );
  5234. $friend_user_table = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  5235. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  5236. if ($friends) {
  5237. // who friends from social network is online
  5238. $query = "SELECT DISTINCT login_user_id, login_date
  5239. FROM $track_online_table INNER JOIN $friend_user_table
  5240. ON (friend_user_id = login_user_id)
  5241. WHERE
  5242. login_date >= '".$current_date."' AND
  5243. friend_user_id <> '".api_get_user_id()."' AND
  5244. relation_type='".USER_RELATION_TYPE_FRIEND."' AND
  5245. user_id = '".api_get_user_id()."'
  5246. ORDER BY $column $direction
  5247. LIMIT $from, $number_of_items";
  5248. } else {
  5249. $query = "SELECT DISTINCT login_user_id, login_date
  5250. FROM ".$track_online_table." e
  5251. INNER JOIN ".$table_user." u ON (u.id = e.login_user_id)
  5252. WHERE u.status != ".ANONYMOUS." AND login_date >= '".$current_date."'
  5253. ORDER BY $column $direction
  5254. LIMIT $from, $number_of_items";
  5255. }
  5256. if (api_get_multiple_access_url()) {
  5257. $access_url_id = api_get_current_access_url_id();
  5258. if ($access_url_id != -1) {
  5259. if ($friends) {
  5260. // friends from social network is online
  5261. $query = "SELECT distinct login_user_id, login_date
  5262. FROM $track_online_table track INNER JOIN $friend_user_table
  5263. ON (friend_user_id = login_user_id)
  5264. WHERE track.access_url_id = $access_url_id AND
  5265. login_date >= '".$current_date."' AND
  5266. friend_user_id <> '".api_get_user_id()."' AND
  5267. relation_type='".USER_RELATION_TYPE_FRIEND."'
  5268. ORDER BY $column $direction
  5269. LIMIT $from, $number_of_items";
  5270. } else {
  5271. // all users online
  5272. $query = "SELECT login_user_id, login_date
  5273. FROM ".$track_online_table." track
  5274. INNER JOIN ".$table_user." u
  5275. ON (u.id=track.login_user_id)
  5276. WHERE u.status != ".ANONYMOUS." AND track.access_url_id = $access_url_id AND
  5277. login_date >= '".$current_date."'
  5278. ORDER BY $column $direction
  5279. LIMIT $from, $number_of_items";
  5280. }
  5281. }
  5282. }
  5283. //This query will show all registered users. Only for dev purposes.
  5284. /*$query = "SELECT DISTINCT u.id as login_user_id, login_date FROM ".$track_online_table ." e , $table_user u
  5285. GROUP by u.id
  5286. ORDER BY $column $direction
  5287. LIMIT $from, $number_of_items";*/
  5288. $result = Database::query($query);
  5289. if ($result) {
  5290. $users_online = array();
  5291. while (list($login_user_id, $login_date) = Database::fetch_row($result)) {
  5292. $users_online[] = $login_user_id;
  5293. }
  5294. return $users_online;
  5295. } else {
  5296. return false;
  5297. }
  5298. }
  5299. /**
  5300. * @param int $user_id
  5301. * @param bool $is_time_over
  5302. * @param bool $get_count
  5303. * @param bool $reverse_order
  5304. * @param int $start
  5305. * @param null $maxPerPage
  5306. * @param null $categoryFilter
  5307. * @return array
  5308. */
  5309. public static function getCategories(
  5310. $user_id,
  5311. $is_time_over = false,
  5312. $get_count = false,
  5313. $reverse_order = false,
  5314. $start = 0,
  5315. $maxPerPage = null,
  5316. $categoryFilter = null
  5317. ) {
  5318. $tableSessionCategory = Database:: get_main_table(
  5319. TABLE_MAIN_SESSION_CATEGORY
  5320. );
  5321. $tableSession = Database:: get_main_table(TABLE_MAIN_SESSION);
  5322. $tableSessionUser = Database:: get_main_table(TABLE_MAIN_SESSION_USER);
  5323. $tableSessionCourseUser = Database:: get_main_table(
  5324. TABLE_MAIN_SESSION_COURSE_USER
  5325. );
  5326. $select = " DISTINCT sc.id, sc.name ";
  5327. if ($get_count) {
  5328. $select = " COUNT(DISTINCT(sc.id)) as total";
  5329. }
  5330. $sql = "SELECT $select
  5331. FROM $tableSessionCategory sc
  5332. INNER JOIN $tableSession s ON (sc.id = s.session_category_id)
  5333. INNER JOIN (
  5334. (
  5335. SELECT DISTINCT session_id as sessionID FROM $tableSessionUser
  5336. WHERE user_id = $user_id AND relation_type <> ".SESSION_RELATION_TYPE_RRHH."
  5337. )
  5338. UNION
  5339. (
  5340. SELECT DISTINCT s.id
  5341. FROM $tableSession s
  5342. WHERE (id_coach = $user_id)
  5343. )
  5344. UNION
  5345. (
  5346. SELECT DISTINCT s.id
  5347. FROM $tableSessionUser su INNER JOIN $tableSession s
  5348. ON (su.session_id = s.id)
  5349. INNER JOIN $tableSessionCourseUser scu
  5350. ON (scu.session_id = s.id)
  5351. WHERE (scu.user_id = $user_id)
  5352. )
  5353. ) as t ON (t.sessionId = sc.id)
  5354. ";
  5355. if ($get_count) {
  5356. $result = Database::query($sql);
  5357. $row = Database::fetch_array($result);
  5358. return $row['total'];
  5359. }
  5360. $order = ' ORDER BY sc.name';
  5361. if ($reverse_order) {
  5362. $order = ' ORDER BY sc.name DESC ';
  5363. }
  5364. $sql .= $order;
  5365. if (isset($start) && isset($maxPerPage)) {
  5366. $start = intval($start);
  5367. $maxPerPage = intval($maxPerPage);
  5368. $limitCondition = " LIMIT $start, $maxPerPage";
  5369. $sql .= $limitCondition;
  5370. }
  5371. $result = Database::query($sql);
  5372. $sessionsCategories = array();
  5373. if (Database::num_rows($result)) {
  5374. while ($sessionCategory = Database::fetch_array($result, 'ASSOC')) {
  5375. $sessions = self::get_sessions_by_category(
  5376. $user_id,
  5377. $is_time_over,
  5378. false,
  5379. $reverse_order,
  5380. null,
  5381. null,
  5382. $sessionCategory['id']
  5383. );
  5384. $sessionsCategories[$sessionCategory['id']] = $sessions[$sessionCategory['id']];
  5385. }
  5386. }
  5387. return $sessionsCategories;
  5388. }
  5389. }