usermanager.lib.php 203 KB

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