usermanager.lib.php 203 KB

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