usermanager.lib.php 194 KB

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