usermanager.lib.php 229 KB

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