usermanager.lib.php 199 KB

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