usermanager.lib.php 211 KB

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