usermanager.lib.php 239 KB

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