usermanager.lib.php 207 KB

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