usermanager.lib.php 195 KB

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