usermanager.lib.php 208 KB

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