usermanager.lib.php 237 KB

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