usermanager.lib.php 235 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739
  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. * Get valid filenames in $user_folder/{$extra_field}/.
  2238. *
  2239. * @param $user_id
  2240. * @param $extra_field
  2241. * @param bool $full_path
  2242. *
  2243. * @return array
  2244. */
  2245. public static function get_user_extra_files($user_id, $extra_field, $full_path = false)
  2246. {
  2247. if (!$full_path) {
  2248. // Nothing to do
  2249. } else {
  2250. $path_info = self::get_user_picture_path_by_id($user_id, 'system');
  2251. $path = $path_info['dir'];
  2252. }
  2253. $extra_data = self::get_extra_user_data_by_field($user_id, $extra_field);
  2254. $extra_files = $extra_data[$extra_field];
  2255. $files = [];
  2256. if (is_array($extra_files)) {
  2257. foreach ($extra_files as $key => $value) {
  2258. if (!$full_path) {
  2259. // Relative path from user folder
  2260. $files[] = $value;
  2261. } else {
  2262. $files[] = $path.$value;
  2263. }
  2264. }
  2265. } elseif (!empty($extra_files)) {
  2266. if (!$full_path) {
  2267. // Relative path from user folder
  2268. $files[] = $extra_files;
  2269. } else {
  2270. $files[] = $path.$extra_files;
  2271. }
  2272. }
  2273. return $files; // can be an empty array
  2274. }
  2275. /**
  2276. * Creates a new extra field.
  2277. *
  2278. * @param string $variable Field's internal variable name
  2279. * @param int $fieldType Field's type
  2280. * @param string $displayText Field's language var name
  2281. * @param string $default Field's default value
  2282. *
  2283. * @return int
  2284. */
  2285. public static function create_extra_field(
  2286. $variable,
  2287. $fieldType,
  2288. $displayText,
  2289. $default
  2290. ) {
  2291. $extraField = new ExtraField('user');
  2292. $params = [
  2293. 'variable' => $variable,
  2294. 'field_type' => $fieldType,
  2295. 'display_text' => $displayText,
  2296. 'default_value' => $default,
  2297. ];
  2298. return $extraField->save($params);
  2299. }
  2300. /**
  2301. * Check if a field is available.
  2302. *
  2303. * @param string $variable
  2304. *
  2305. * @return bool
  2306. */
  2307. public static function is_extra_field_available($variable)
  2308. {
  2309. $extraField = new ExtraField('user');
  2310. $data = $extraField->get_handler_field_info_by_field_variable($variable);
  2311. return !empty($data) ? true : false;
  2312. }
  2313. /**
  2314. * Gets user extra fields data.
  2315. *
  2316. * @param int User ID
  2317. * @param bool Whether to prefix the fields indexes with "extra_" (might be used by formvalidator)
  2318. * @param bool Whether to return invisible fields as well
  2319. * @param bool Whether to split multiple-selection fields or not
  2320. *
  2321. * @return array Array of fields => value for the given user
  2322. */
  2323. public static function get_extra_user_data(
  2324. $user_id,
  2325. $prefix = false,
  2326. $allVisibility = true,
  2327. $splitMultiple = false,
  2328. $fieldFilter = null
  2329. ) {
  2330. $user_id = (int) $user_id;
  2331. if (empty($user_id)) {
  2332. return [];
  2333. }
  2334. $extra_data = [];
  2335. $t_uf = Database::get_main_table(TABLE_EXTRA_FIELD);
  2336. $t_ufv = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  2337. $user_id = (int) $user_id;
  2338. $sql = "SELECT f.id as id, f.variable as fvar, f.field_type as type
  2339. FROM $t_uf f
  2340. WHERE
  2341. extra_field_type = ".EntityExtraField::USER_FIELD_TYPE."
  2342. ";
  2343. $filter_cond = '';
  2344. if (!$allVisibility) {
  2345. if (isset($fieldFilter)) {
  2346. $fieldFilter = (int) $fieldFilter;
  2347. $filter_cond .= " AND filter = $fieldFilter ";
  2348. }
  2349. $sql .= " AND f.visible_to_self = 1 $filter_cond ";
  2350. } else {
  2351. if (isset($fieldFilter)) {
  2352. $fieldFilter = (int) $fieldFilter;
  2353. $sql .= " AND filter = $fieldFilter ";
  2354. }
  2355. }
  2356. $sql .= ' ORDER BY f.field_order';
  2357. $res = Database::query($sql);
  2358. if (Database::num_rows($res) > 0) {
  2359. while ($row = Database::fetch_array($res)) {
  2360. if ($row['type'] == self::USER_FIELD_TYPE_TAG) {
  2361. $tags = self::get_user_tags_to_string($user_id, $row['id'], false);
  2362. $extra_data['extra_'.$row['fvar']] = $tags;
  2363. } else {
  2364. $sqlu = "SELECT value as fval
  2365. FROM $t_ufv
  2366. WHERE field_id=".$row['id']." AND item_id = ".$user_id;
  2367. $resu = Database::query($sqlu);
  2368. // get default value
  2369. $sql_df = "SELECT default_value as fval_df FROM $t_uf
  2370. WHERE id=".$row['id'];
  2371. $res_df = Database::query($sql_df);
  2372. if (Database::num_rows($resu) > 0) {
  2373. $rowu = Database::fetch_array($resu);
  2374. $fval = $rowu['fval'];
  2375. if ($row['type'] == self::USER_FIELD_TYPE_SELECT_MULTIPLE) {
  2376. $fval = explode(';', $rowu['fval']);
  2377. }
  2378. } else {
  2379. $row_df = Database::fetch_array($res_df);
  2380. $fval = $row_df['fval_df'];
  2381. }
  2382. // We get here (and fill the $extra_data array) even if there
  2383. // is no user with data (we fill it with default values)
  2384. if ($prefix) {
  2385. if ($row['type'] == self::USER_FIELD_TYPE_RADIO) {
  2386. $extra_data['extra_'.$row['fvar']]['extra_'.$row['fvar']] = $fval;
  2387. } else {
  2388. $extra_data['extra_'.$row['fvar']] = $fval;
  2389. }
  2390. } else {
  2391. if ($row['type'] == self::USER_FIELD_TYPE_RADIO) {
  2392. $extra_data['extra_'.$row['fvar']]['extra_'.$row['fvar']] = $fval;
  2393. } else {
  2394. $extra_data[$row['fvar']] = $fval;
  2395. }
  2396. }
  2397. }
  2398. }
  2399. }
  2400. return $extra_data;
  2401. }
  2402. /** Get extra user data by field
  2403. * @param int user ID
  2404. * @param string the internal variable name of the field
  2405. *
  2406. * @return array with extra data info of a user i.e array('field_variable'=>'value');
  2407. */
  2408. public static function get_extra_user_data_by_field(
  2409. $user_id,
  2410. $field_variable,
  2411. $prefix = false,
  2412. $all_visibility = true,
  2413. $splitmultiple = false
  2414. ) {
  2415. $user_id = (int) $user_id;
  2416. if (empty($user_id)) {
  2417. return [];
  2418. }
  2419. $extra_data = [];
  2420. $t_uf = Database::get_main_table(TABLE_EXTRA_FIELD);
  2421. $t_ufv = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  2422. $sql = "SELECT f.id as id, f.variable as fvar, f.field_type as type
  2423. FROM $t_uf f
  2424. WHERE f.variable = '$field_variable' ";
  2425. if (!$all_visibility) {
  2426. $sql .= " AND f.visible_to_self = 1 ";
  2427. }
  2428. $sql .= " AND extra_field_type = ".EntityExtraField::USER_FIELD_TYPE;
  2429. $sql .= " ORDER BY f.field_order ";
  2430. $res = Database::query($sql);
  2431. if (Database::num_rows($res) > 0) {
  2432. while ($row = Database::fetch_array($res)) {
  2433. $sqlu = "SELECT value as fval FROM $t_ufv v
  2434. INNER JOIN $t_uf f
  2435. ON (v.field_id = f.id)
  2436. WHERE
  2437. extra_field_type = ".EntityExtraField::USER_FIELD_TYPE." AND
  2438. field_id = ".$row['id']." AND
  2439. item_id = ".$user_id;
  2440. $resu = Database::query($sqlu);
  2441. $fval = '';
  2442. if (Database::num_rows($resu) > 0) {
  2443. $rowu = Database::fetch_array($resu);
  2444. $fval = $rowu['fval'];
  2445. if ($row['type'] == self::USER_FIELD_TYPE_SELECT_MULTIPLE) {
  2446. $fval = explode(';', $rowu['fval']);
  2447. }
  2448. }
  2449. if ($prefix) {
  2450. $extra_data['extra_'.$row['fvar']] = $fval;
  2451. } else {
  2452. $extra_data[$row['fvar']] = $fval;
  2453. }
  2454. }
  2455. }
  2456. return $extra_data;
  2457. }
  2458. /**
  2459. * Get the extra field information for a certain field (the options as well).
  2460. *
  2461. * @param int $variable The name of the field we want to know everything about
  2462. *
  2463. * @return array Array containing all the information about the extra profile field
  2464. * (first level of array contains field details, then 'options' sub-array contains options details,
  2465. * as returned by the database)
  2466. *
  2467. * @author Julio Montoya
  2468. *
  2469. * @since v1.8.6
  2470. */
  2471. public static function get_extra_field_information_by_name($variable)
  2472. {
  2473. $extraField = new ExtraField('user');
  2474. return $extraField->get_handler_field_info_by_field_variable($variable);
  2475. }
  2476. /**
  2477. * Get the extra field information for user tag (the options as well).
  2478. *
  2479. * @param int $variable The name of the field we want to know everything about
  2480. *
  2481. * @return array Array containing all the information about the extra profile field
  2482. * (first level of array contains field details, then 'options' sub-array contains options details,
  2483. * as returned by the database)
  2484. *
  2485. * @author José Loguercio
  2486. *
  2487. * @since v1.11.0
  2488. */
  2489. public static function get_extra_field_tags_information_by_name($variable)
  2490. {
  2491. $extraField = new ExtraField('user');
  2492. return $extraField->get_handler_field_info_by_tags($variable);
  2493. }
  2494. /**
  2495. * Get all the extra field information of a certain field (also the options).
  2496. *
  2497. * @param int $fieldId the ID of the field we want to know everything of
  2498. *
  2499. * @return array $return containing all th information about the extra profile field
  2500. *
  2501. * @author Julio Montoya
  2502. *
  2503. * @deprecated
  2504. * @since v1.8.6
  2505. */
  2506. public static function get_extra_field_information($fieldId)
  2507. {
  2508. $extraField = new ExtraField('user');
  2509. return $extraField->getFieldInfoByFieldId($fieldId);
  2510. }
  2511. /**
  2512. * Get extra user data by value.
  2513. *
  2514. * @param string $variable the internal variable name of the field
  2515. * @param string $value the internal value of the field
  2516. * @param bool $all_visibility
  2517. *
  2518. * @return array with extra data info of a user i.e array('field_variable'=>'value');
  2519. */
  2520. public static function get_extra_user_data_by_value($variable, $value, $all_visibility = true)
  2521. {
  2522. $extraFieldValue = new ExtraFieldValue('user');
  2523. $extraField = new ExtraField('user');
  2524. $info = $extraField->get_handler_field_info_by_field_variable($variable);
  2525. if (false === $info) {
  2526. return [];
  2527. }
  2528. $data = $extraFieldValue->get_item_id_from_field_variable_and_field_value(
  2529. $variable,
  2530. $value,
  2531. false,
  2532. false,
  2533. true
  2534. );
  2535. $result = [];
  2536. if (!empty($data)) {
  2537. foreach ($data as $item) {
  2538. $result[] = $item['item_id'];
  2539. }
  2540. }
  2541. return $result;
  2542. }
  2543. /**
  2544. * Get extra user data by tags value.
  2545. *
  2546. * @param int $fieldId the ID of the field we want to know everything of
  2547. * @param string $tag the tag name for search
  2548. *
  2549. * @return array with extra data info of a user
  2550. *
  2551. * @author José Loguercio
  2552. *
  2553. * @since v1.11.0
  2554. */
  2555. public static function get_extra_user_data_by_tags($fieldId, $tag)
  2556. {
  2557. $extraField = new ExtraField('user');
  2558. $result = $extraField->getAllUserPerTag($fieldId, $tag);
  2559. $array = [];
  2560. foreach ($result as $index => $user) {
  2561. $array[] = $user['user_id'];
  2562. }
  2563. return $array;
  2564. }
  2565. /**
  2566. * Get extra user data by field variable.
  2567. *
  2568. * @param string $variable field variable
  2569. *
  2570. * @return array data
  2571. */
  2572. public static function get_extra_user_data_by_field_variable($variable)
  2573. {
  2574. $extraInfo = self::get_extra_field_information_by_name($variable);
  2575. $field_id = (int) $extraInfo['id'];
  2576. $extraField = new ExtraFieldValue('user');
  2577. $data = $extraField->getValuesByFieldId($field_id);
  2578. if (!empty($data)) {
  2579. foreach ($data as $row) {
  2580. $user_id = $row['item_id'];
  2581. $data[$user_id] = $row;
  2582. }
  2583. }
  2584. return $data;
  2585. }
  2586. /**
  2587. * Get extra user data tags by field variable.
  2588. *
  2589. * @param string $variable field variable
  2590. *
  2591. * @return array
  2592. */
  2593. public static function get_extra_user_data_for_tags($variable)
  2594. {
  2595. $data = self::get_extra_field_tags_information_by_name($variable);
  2596. return $data;
  2597. }
  2598. /**
  2599. * Gives a list of [session_category][session_id] for the current user.
  2600. *
  2601. * @param int $user_id
  2602. * @param bool $is_time_over whether to fill the first element or not
  2603. * (to give space for courses out of categories)
  2604. * @param bool $ignore_visibility_for_admins optional true if limit time from session is over, false otherwise
  2605. * @param bool $ignoreTimeLimit ignore time start/end
  2606. * @param bool $getCount
  2607. *
  2608. * @return array list of statuses [session_category][session_id]
  2609. *
  2610. * @todo ensure multiple access urls are managed correctly
  2611. */
  2612. public static function get_sessions_by_category(
  2613. $user_id,
  2614. $is_time_over = true,
  2615. $ignore_visibility_for_admins = false,
  2616. $ignoreTimeLimit = false,
  2617. $getCount = false
  2618. ) {
  2619. $user_id = (int) $user_id;
  2620. if (empty($user_id)) {
  2621. return [];
  2622. }
  2623. $allowOrder = api_get_configuration_value('session_list_order');
  2624. $position = '';
  2625. if ($allowOrder) {
  2626. $position = ', s.position AS position ';
  2627. }
  2628. // Get the list of sessions per user
  2629. $now = new DateTime('now', new DateTimeZone('UTC'));
  2630. // LEFT JOIN is used for session_rel_course_rel_user because an inner
  2631. // join would not catch session-courses where the user is general
  2632. // session coach but which do not have students nor coaches registered
  2633. $dqlSelect = ' COUNT(DISTINCT s.id) ';
  2634. if (!$getCount) {
  2635. $dqlSelect = " DISTINCT
  2636. s.id,
  2637. s.name,
  2638. s.accessStartDate AS access_start_date,
  2639. s.accessEndDate AS access_end_date,
  2640. s.duration,
  2641. sc.id AS session_category_id,
  2642. sc.name AS session_category_name,
  2643. sc.dateStart AS session_category_date_start,
  2644. sc.dateEnd AS session_category_date_end,
  2645. s.coachAccessStartDate AS coach_access_start_date,
  2646. s.coachAccessEndDate AS coach_access_end_date,
  2647. CASE WHEN s.accessEndDate IS NULL THEN 1 ELSE 0 END HIDDEN _isFieldNull
  2648. $position
  2649. ";
  2650. }
  2651. $dql = "SELECT $dqlSelect
  2652. FROM ChamiloCoreBundle:Session AS s
  2653. LEFT JOIN ChamiloCoreBundle:SessionRelCourseRelUser AS scu WITH scu.session = s
  2654. INNER JOIN ChamiloCoreBundle:AccessUrlRelSession AS url WITH url.sessionId = s.id
  2655. LEFT JOIN ChamiloCoreBundle:SessionCategory AS sc WITH s.category = sc ";
  2656. // A single OR operation on scu.user = :user OR s.generalCoach = :user
  2657. // is awfully inefficient for large sets of data (1m25s for 58K
  2658. // sessions, BT#14115) but executing a similar query twice and grouping
  2659. // the results afterwards in PHP takes about 1/1000th of the time
  2660. // (0.1s + 0.0s) for the same set of data, so we do it this way...
  2661. $dqlStudent = $dql.' WHERE scu.user = :user AND url.accessUrlId = :url ';
  2662. $dqlCoach = $dql.' WHERE s.generalCoach = :user AND url.accessUrlId = :url ';
  2663. // Default order
  2664. $order = 'ORDER BY sc.name, s.name';
  2665. // Order by date if showing all sessions
  2666. $showAllSessions = api_get_configuration_value('show_all_sessions_on_my_course_page') === true;
  2667. if ($showAllSessions) {
  2668. $order = 'ORDER BY s.accessStartDate';
  2669. }
  2670. // Order by position
  2671. if ($allowOrder) {
  2672. $order = 'ORDER BY s.position';
  2673. }
  2674. // Order by dates according to settings
  2675. $orderBySettings = api_get_configuration_value('my_courses_session_order');
  2676. if (!empty($orderBySettings) && isset($orderBySettings['field']) && isset($orderBySettings['order'])) {
  2677. $field = $orderBySettings['field'];
  2678. $orderSetting = $orderBySettings['order'];
  2679. switch ($field) {
  2680. case 'start_date':
  2681. $order = " ORDER BY s.accessStartDate $orderSetting";
  2682. break;
  2683. case 'end_date':
  2684. $order = " ORDER BY s.accessEndDate $orderSetting ";
  2685. if ($orderSetting == 'asc') {
  2686. // Put null values at the end
  2687. // https://stackoverflow.com/questions/12652034/how-can-i-order-by-null-in-dql
  2688. $order = ' ORDER BY _isFieldNull asc, s.accessEndDate asc';
  2689. }
  2690. break;
  2691. case 'name':
  2692. $order = " ORDER BY s.name $orderSetting ";
  2693. break;
  2694. }
  2695. }
  2696. $dqlStudent .= $order;
  2697. $dqlCoach .= $order;
  2698. $accessUrlId = api_get_current_access_url_id();
  2699. $dqlStudent = Database::getManager()
  2700. ->createQuery($dqlStudent)
  2701. ->setParameters(
  2702. ['user' => $user_id, 'url' => $accessUrlId]
  2703. )
  2704. ;
  2705. $dqlCoach = Database::getManager()
  2706. ->createQuery($dqlCoach)
  2707. ->setParameters(
  2708. ['user' => $user_id, 'url' => $accessUrlId]
  2709. )
  2710. ;
  2711. if ($getCount) {
  2712. return $dqlStudent->getSingleScalarResult() + $dqlCoach->getSingleScalarResult();
  2713. }
  2714. $sessionDataStudent = $dqlStudent->getResult();
  2715. $sessionDataCoach = $dqlCoach->getResult();
  2716. $sessionData = [];
  2717. // First fill $sessionData with student sessions
  2718. foreach ($sessionDataStudent as $row) {
  2719. $sessionData[$row['id']] = $row;
  2720. }
  2721. // Overwrite session data of the user as a student with session data
  2722. // of the user as a coach.
  2723. // There shouldn't be such duplicate rows, but just in case...
  2724. foreach ($sessionDataCoach as $row) {
  2725. $sessionData[$row['id']] = $row;
  2726. }
  2727. $collapsable = api_get_configuration_value('allow_user_session_collapsable');
  2728. $extraField = new ExtraFieldValue('session');
  2729. $collapsableLink = api_get_path(WEB_PATH).'user_portal.php?action=collapse_session';
  2730. $categories = [];
  2731. foreach ($sessionData as $row) {
  2732. $session_id = $row['id'];
  2733. $coachList = SessionManager::getCoachesBySession($session_id);
  2734. $categoryStart = $row['session_category_date_start'] ? $row['session_category_date_start']->format('Y-m-d') : '';
  2735. $categoryEnd = $row['session_category_date_end'] ? $row['session_category_date_end']->format('Y-m-d') : '';
  2736. $courseList = self::get_courses_list_by_session(
  2737. $user_id,
  2738. $session_id
  2739. );
  2740. $daysLeft = SessionManager::getDayLeftInSession($row, $user_id);
  2741. // User portal filters:
  2742. if ($ignoreTimeLimit === false) {
  2743. if ($is_time_over) {
  2744. // History
  2745. if ($row['duration']) {
  2746. if ($daysLeft >= 0) {
  2747. continue;
  2748. }
  2749. } else {
  2750. if (empty($row['access_end_date'])) {
  2751. continue;
  2752. } else {
  2753. if ($row['access_end_date'] > $now) {
  2754. continue;
  2755. }
  2756. }
  2757. }
  2758. } else {
  2759. // Current user portal
  2760. $isGeneralCoach = SessionManager::user_is_general_coach($user_id, $row['id']);
  2761. $isCoachOfCourse = in_array($user_id, $coachList);
  2762. if (api_is_platform_admin() || $isGeneralCoach || $isCoachOfCourse) {
  2763. // Teachers can access the session depending in the access_coach date
  2764. } else {
  2765. if ($row['duration']) {
  2766. if ($daysLeft <= 0) {
  2767. continue;
  2768. }
  2769. } else {
  2770. if (isset($row['access_end_date']) &&
  2771. !empty($row['access_end_date'])
  2772. ) {
  2773. if ($row['access_end_date'] <= $now) {
  2774. continue;
  2775. }
  2776. }
  2777. }
  2778. }
  2779. }
  2780. }
  2781. $categories[$row['session_category_id']]['session_category'] = [
  2782. 'id' => $row['session_category_id'],
  2783. 'name' => $row['session_category_name'],
  2784. 'date_start' => $categoryStart,
  2785. 'date_end' => $categoryEnd,
  2786. ];
  2787. $visibility = api_get_session_visibility(
  2788. $session_id,
  2789. null,
  2790. $ignore_visibility_for_admins
  2791. );
  2792. if ($visibility != SESSION_VISIBLE) {
  2793. // Course Coach session visibility.
  2794. $blockedCourseCount = 0;
  2795. $closedVisibilityList = [
  2796. COURSE_VISIBILITY_CLOSED,
  2797. COURSE_VISIBILITY_HIDDEN,
  2798. ];
  2799. foreach ($courseList as $course) {
  2800. // Checking session visibility
  2801. $sessionCourseVisibility = api_get_session_visibility(
  2802. $session_id,
  2803. $course['real_id'],
  2804. $ignore_visibility_for_admins
  2805. );
  2806. $courseIsVisible = !in_array($course['visibility'], $closedVisibilityList);
  2807. if ($courseIsVisible === false || $sessionCourseVisibility == SESSION_INVISIBLE) {
  2808. $blockedCourseCount++;
  2809. }
  2810. }
  2811. // If all courses are blocked then no show in the list.
  2812. if ($blockedCourseCount === count($courseList)) {
  2813. $visibility = SESSION_INVISIBLE;
  2814. } else {
  2815. $visibility = $sessionCourseVisibility;
  2816. }
  2817. }
  2818. switch ($visibility) {
  2819. case SESSION_VISIBLE_READ_ONLY:
  2820. case SESSION_VISIBLE:
  2821. case SESSION_AVAILABLE:
  2822. break;
  2823. case SESSION_INVISIBLE:
  2824. if ($ignore_visibility_for_admins === false) {
  2825. continue 2;
  2826. }
  2827. }
  2828. $collapsed = '';
  2829. $collapsedAction = '';
  2830. if ($collapsable) {
  2831. $collapsableData = SessionManager::getCollapsableData(
  2832. $user_id,
  2833. $session_id,
  2834. $extraField,
  2835. $collapsableLink
  2836. );
  2837. $collapsed = $collapsableData['collapsed'];
  2838. $collapsedAction = $collapsableData['collapsable_link'];
  2839. }
  2840. $categories[$row['session_category_id']]['sessions'][] = [
  2841. 'session_name' => $row['name'],
  2842. 'session_id' => $row['id'],
  2843. 'access_start_date' => $row['access_start_date'] ? $row['access_start_date']->format('Y-m-d H:i:s') : null,
  2844. 'access_end_date' => $row['access_end_date'] ? $row['access_end_date']->format('Y-m-d H:i:s') : null,
  2845. 'coach_access_start_date' => $row['coach_access_start_date'] ? $row['coach_access_start_date']->format('Y-m-d H:i:s') : null,
  2846. 'coach_access_end_date' => $row['coach_access_end_date'] ? $row['coach_access_end_date']->format('Y-m-d H:i:s') : null,
  2847. 'courses' => $courseList,
  2848. 'collapsed' => $collapsed,
  2849. 'collapsable_link' => $collapsedAction,
  2850. 'duration' => $row['duration'],
  2851. ];
  2852. }
  2853. return $categories;
  2854. }
  2855. /**
  2856. * Gives a list of [session_id-course_code] => [status] for the current user.
  2857. *
  2858. * @param int $user_id
  2859. * @param int $sessionLimit
  2860. *
  2861. * @return array list of statuses (session_id-course_code => status)
  2862. */
  2863. public static function get_personal_session_course_list($user_id, $sessionLimit = null)
  2864. {
  2865. // Database Table Definitions
  2866. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  2867. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  2868. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  2869. $tbl_session_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  2870. $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  2871. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2872. $user_id = (int) $user_id;
  2873. if (empty($user_id)) {
  2874. return [];
  2875. }
  2876. // We filter the courses from the URL
  2877. $join_access_url = $where_access_url = '';
  2878. if (api_get_multiple_access_url()) {
  2879. $access_url_id = api_get_current_access_url_id();
  2880. if ($access_url_id != -1) {
  2881. $tbl_url_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  2882. $join_access_url = "LEFT JOIN $tbl_url_course url_rel_course ON url_rel_course.c_id = course.id";
  2883. $where_access_url = " AND access_url_id = $access_url_id ";
  2884. }
  2885. }
  2886. // Courses in which we subscribed out of any session
  2887. $tbl_user_course_category = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
  2888. $sql = "SELECT
  2889. course.code,
  2890. course_rel_user.status course_rel_status,
  2891. course_rel_user.sort sort,
  2892. course_rel_user.user_course_cat user_course_cat
  2893. FROM $tbl_course_user course_rel_user
  2894. LEFT JOIN $tbl_course course
  2895. ON course.id = course_rel_user.c_id
  2896. LEFT JOIN $tbl_user_course_category user_course_category
  2897. ON course_rel_user.user_course_cat = user_course_category.id
  2898. $join_access_url
  2899. WHERE
  2900. course_rel_user.user_id = '".$user_id."' AND
  2901. course_rel_user.relation_type <> ".COURSE_RELATION_TYPE_RRHH."
  2902. $where_access_url
  2903. ORDER BY user_course_category.sort, course_rel_user.sort, course.title ASC";
  2904. $course_list_sql_result = Database::query($sql);
  2905. $personal_course_list = [];
  2906. if (Database::num_rows($course_list_sql_result) > 0) {
  2907. while ($result_row = Database::fetch_array($course_list_sql_result, 'ASSOC')) {
  2908. $course_info = api_get_course_info($result_row['code']);
  2909. $result_row['course_info'] = $course_info;
  2910. $personal_course_list[] = $result_row;
  2911. }
  2912. }
  2913. $coachCourseConditions = '';
  2914. // Getting sessions that are related to a coach in the session_rel_course_rel_user table
  2915. if (api_is_allowed_to_create_course()) {
  2916. $sessionListFromCourseCoach = [];
  2917. $sql = " SELECT DISTINCT session_id
  2918. FROM $tbl_session_course_user
  2919. WHERE user_id = $user_id AND status = 2 ";
  2920. $result = Database::query($sql);
  2921. if (Database::num_rows($result)) {
  2922. $result = Database::store_result($result);
  2923. foreach ($result as $session) {
  2924. $sessionListFromCourseCoach[] = $session['session_id'];
  2925. }
  2926. }
  2927. if (!empty($sessionListFromCourseCoach)) {
  2928. $condition = implode("','", $sessionListFromCourseCoach);
  2929. $coachCourseConditions = " OR ( s.id IN ('$condition'))";
  2930. }
  2931. }
  2932. // Get the list of sessions where the user is subscribed
  2933. // This is divided into two different queries
  2934. $sessions = [];
  2935. $sessionLimitRestriction = '';
  2936. if (!empty($sessionLimit)) {
  2937. $sessionLimit = (int) $sessionLimit;
  2938. $sessionLimitRestriction = "LIMIT $sessionLimit";
  2939. }
  2940. $sql = "SELECT DISTINCT s.id, name, access_start_date, access_end_date
  2941. FROM $tbl_session_user su INNER JOIN $tbl_session s
  2942. ON (s.id = su.session_id)
  2943. WHERE (
  2944. su.user_id = $user_id AND
  2945. su.relation_type <> ".SESSION_RELATION_TYPE_RRHH."
  2946. )
  2947. $coachCourseConditions
  2948. ORDER BY access_start_date, access_end_date, name
  2949. $sessionLimitRestriction
  2950. ";
  2951. $result = Database::query($sql);
  2952. if (Database::num_rows($result) > 0) {
  2953. while ($row = Database::fetch_assoc($result)) {
  2954. $sessions[$row['id']] = $row;
  2955. }
  2956. }
  2957. $sql = "SELECT DISTINCT
  2958. id, name, access_start_date, access_end_date
  2959. FROM $tbl_session s
  2960. WHERE (
  2961. id_coach = $user_id
  2962. )
  2963. $coachCourseConditions
  2964. ORDER BY access_start_date, access_end_date, name";
  2965. $result = Database::query($sql);
  2966. if (Database::num_rows($result) > 0) {
  2967. while ($row = Database::fetch_assoc($result)) {
  2968. if (empty($sessions[$row['id']])) {
  2969. $sessions[$row['id']] = $row;
  2970. }
  2971. }
  2972. }
  2973. if (api_is_allowed_to_create_course()) {
  2974. foreach ($sessions as $enreg) {
  2975. $session_id = $enreg['id'];
  2976. $session_visibility = api_get_session_visibility($session_id);
  2977. if ($session_visibility == SESSION_INVISIBLE) {
  2978. continue;
  2979. }
  2980. // This query is horribly slow when more than a few thousand
  2981. // users and just a few sessions to which they are subscribed
  2982. $sql = "SELECT DISTINCT
  2983. course.code code,
  2984. course.title i,
  2985. ".(api_is_western_name_order() ? "CONCAT(user.firstname,' ',user.lastname)" : "CONCAT(user.lastname,' ',user.firstname)")." t,
  2986. email, course.course_language l,
  2987. 1 sort,
  2988. category_code user_course_cat,
  2989. access_start_date,
  2990. access_end_date,
  2991. session.id as session_id,
  2992. session.name as session_name
  2993. FROM $tbl_session_course_user as session_course_user
  2994. INNER JOIN $tbl_course AS course
  2995. ON course.id = session_course_user.c_id
  2996. INNER JOIN $tbl_session as session
  2997. ON session.id = session_course_user.session_id
  2998. LEFT JOIN $tbl_user as user
  2999. ON user.id = session_course_user.user_id OR session.id_coach = user.id
  3000. WHERE
  3001. session_course_user.session_id = $session_id AND (
  3002. (session_course_user.user_id = $user_id AND session_course_user.status = 2)
  3003. OR session.id_coach = $user_id
  3004. )
  3005. ORDER BY i";
  3006. $course_list_sql_result = Database::query($sql);
  3007. while ($result_row = Database::fetch_array($course_list_sql_result, 'ASSOC')) {
  3008. $result_row['course_info'] = api_get_course_info($result_row['code']);
  3009. $key = $result_row['session_id'].' - '.$result_row['code'];
  3010. $personal_course_list[$key] = $result_row;
  3011. }
  3012. }
  3013. }
  3014. foreach ($sessions as $enreg) {
  3015. $session_id = $enreg['id'];
  3016. $session_visibility = api_get_session_visibility($session_id);
  3017. if ($session_visibility == SESSION_INVISIBLE) {
  3018. continue;
  3019. }
  3020. /* This query is very similar to the above query,
  3021. but it will check the session_rel_course_user table if there are courses registered to our user or not */
  3022. $sql = "SELECT DISTINCT
  3023. course.code code,
  3024. course.title i, CONCAT(user.lastname,' ',user.firstname) t,
  3025. email,
  3026. course.course_language l,
  3027. 1 sort,
  3028. category_code user_course_cat,
  3029. access_start_date,
  3030. access_end_date,
  3031. session.id as session_id,
  3032. session.name as session_name,
  3033. IF((session_course_user.user_id = 3 AND session_course_user.status=2),'2', '5')
  3034. FROM $tbl_session_course_user as session_course_user
  3035. INNER JOIN $tbl_course AS course
  3036. ON course.id = session_course_user.c_id AND session_course_user.session_id = $session_id
  3037. INNER JOIN $tbl_session as session
  3038. ON session_course_user.session_id = session.id
  3039. LEFT JOIN $tbl_user as user ON user.id = session_course_user.user_id
  3040. WHERE session_course_user.user_id = $user_id
  3041. ORDER BY i";
  3042. $course_list_sql_result = Database::query($sql);
  3043. while ($result_row = Database::fetch_array($course_list_sql_result, 'ASSOC')) {
  3044. $result_row['course_info'] = api_get_course_info($result_row['code']);
  3045. $key = $result_row['session_id'].' - '.$result_row['code'];
  3046. if (!isset($personal_course_list[$key])) {
  3047. $personal_course_list[$key] = $result_row;
  3048. }
  3049. }
  3050. }
  3051. return $personal_course_list;
  3052. }
  3053. /**
  3054. * Gives a list of courses for the given user in the given session.
  3055. *
  3056. * @param int $user_id
  3057. * @param int $session_id
  3058. *
  3059. * @return array list of statuses (session_id-course_code => status)
  3060. */
  3061. public static function get_courses_list_by_session($user_id, $session_id)
  3062. {
  3063. // Database Table Definitions
  3064. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  3065. $tableCourse = Database::get_main_table(TABLE_MAIN_COURSE);
  3066. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3067. $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  3068. $user_id = (int) $user_id;
  3069. $session_id = (int) $session_id;
  3070. // We filter the courses from the URL
  3071. $join_access_url = $where_access_url = '';
  3072. if (api_get_multiple_access_url()) {
  3073. $urlId = api_get_current_access_url_id();
  3074. if ($urlId != -1) {
  3075. $tbl_url_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  3076. $join_access_url = " , $tbl_url_session url_rel_session ";
  3077. $where_access_url = " AND access_url_id = $urlId AND url_rel_session.session_id = $session_id ";
  3078. }
  3079. }
  3080. /* This query is very similar to the query below, but it will check the
  3081. session_rel_course_user table if there are courses registered
  3082. to our user or not */
  3083. $sql = "SELECT DISTINCT
  3084. c.visibility,
  3085. c.id as real_id,
  3086. c.code as course_code,
  3087. sc.position
  3088. FROM $tbl_session_course_user as scu
  3089. INNER JOIN $tbl_session_course sc
  3090. ON (scu.session_id = sc.session_id AND scu.c_id = sc.c_id)
  3091. INNER JOIN $tableCourse as c
  3092. ON (scu.c_id = c.id)
  3093. $join_access_url
  3094. WHERE
  3095. scu.user_id = $user_id AND
  3096. scu.session_id = $session_id
  3097. $where_access_url
  3098. ORDER BY sc.position ASC";
  3099. $myCourseList = [];
  3100. $courses = [];
  3101. $result = Database::query($sql);
  3102. if (Database::num_rows($result) > 0) {
  3103. while ($result_row = Database::fetch_array($result, 'ASSOC')) {
  3104. $result_row['status'] = 5;
  3105. if (!in_array($result_row['real_id'], $courses)) {
  3106. $position = $result_row['position'];
  3107. if (!isset($myCourseList[$position])) {
  3108. $myCourseList[$position] = $result_row;
  3109. } else {
  3110. $myCourseList[] = $result_row;
  3111. }
  3112. $courses[] = $result_row['real_id'];
  3113. }
  3114. }
  3115. }
  3116. if (api_is_allowed_to_create_course()) {
  3117. $sql = "SELECT DISTINCT
  3118. c.visibility,
  3119. c.id as real_id,
  3120. c.code as course_code,
  3121. sc.position
  3122. FROM $tbl_session_course_user as scu
  3123. INNER JOIN $tbl_session as s
  3124. ON (scu.session_id = s.id)
  3125. INNER JOIN $tbl_session_course sc
  3126. ON (scu.session_id = sc.session_id AND scu.c_id = sc.c_id)
  3127. INNER JOIN $tableCourse as c
  3128. ON (scu.c_id = c.id)
  3129. $join_access_url
  3130. WHERE
  3131. s.id = $session_id AND
  3132. (
  3133. (scu.user_id = $user_id AND scu.status = 2) OR
  3134. s.id_coach = $user_id
  3135. )
  3136. $where_access_url
  3137. ORDER BY sc.position ASC";
  3138. $result = Database::query($sql);
  3139. if (Database::num_rows($result) > 0) {
  3140. while ($result_row = Database::fetch_array($result, 'ASSOC')) {
  3141. $result_row['status'] = 2;
  3142. if (!in_array($result_row['real_id'], $courses)) {
  3143. $position = $result_row['position'];
  3144. if (!isset($myCourseList[$position])) {
  3145. $myCourseList[$position] = $result_row;
  3146. } else {
  3147. $myCourseList[] = $result_row;
  3148. }
  3149. $courses[] = $result_row['real_id'];
  3150. }
  3151. }
  3152. }
  3153. }
  3154. if (api_is_drh()) {
  3155. $sessionList = SessionManager::get_sessions_followed_by_drh($user_id);
  3156. $sessionList = array_keys($sessionList);
  3157. if (in_array($session_id, $sessionList)) {
  3158. $courseList = SessionManager::get_course_list_by_session_id($session_id);
  3159. if (!empty($courseList)) {
  3160. foreach ($courseList as $course) {
  3161. if (!in_array($course['id'], $courses)) {
  3162. $position = $course['position'];
  3163. if (!isset($myCourseList[$position])) {
  3164. $myCourseList[$position] = $course;
  3165. } else {
  3166. $myCourseList[] = $course;
  3167. }
  3168. }
  3169. }
  3170. }
  3171. }
  3172. } else {
  3173. //check if user is general coach for this session
  3174. $sessionInfo = api_get_session_info($session_id);
  3175. if ($sessionInfo['id_coach'] == $user_id) {
  3176. $courseList = SessionManager::get_course_list_by_session_id($session_id);
  3177. if (!empty($courseList)) {
  3178. foreach ($courseList as $course) {
  3179. if (!in_array($course['id'], $courses)) {
  3180. $position = $course['position'];
  3181. if (!isset($myCourseList[$position])) {
  3182. $myCourseList[$position] = $course;
  3183. } else {
  3184. $myCourseList[] = $course;
  3185. }
  3186. }
  3187. }
  3188. }
  3189. }
  3190. }
  3191. if (!empty($myCourseList)) {
  3192. ksort($myCourseList);
  3193. $checkPosition = array_filter(array_column($myCourseList, 'position'));
  3194. if (empty($checkPosition)) {
  3195. // The session course list doesn't have any position,
  3196. // then order the course list by course code
  3197. $list = array_column($myCourseList, 'course_code');
  3198. array_multisort($myCourseList, SORT_ASC, $list);
  3199. }
  3200. }
  3201. return $myCourseList;
  3202. }
  3203. /**
  3204. * Get user id from a username.
  3205. *
  3206. * @param string $username
  3207. *
  3208. * @return int User ID (or false if not found)
  3209. */
  3210. public static function get_user_id_from_username($username)
  3211. {
  3212. if (empty($username)) {
  3213. return false;
  3214. }
  3215. $username = trim($username);
  3216. $username = Database::escape_string($username);
  3217. $t_user = Database::get_main_table(TABLE_MAIN_USER);
  3218. $sql = "SELECT id FROM $t_user WHERE username = '$username'";
  3219. $res = Database::query($sql);
  3220. if ($res === false) {
  3221. return false;
  3222. }
  3223. if (Database::num_rows($res) !== 1) {
  3224. return false;
  3225. }
  3226. $row = Database::fetch_array($res);
  3227. return $row['id'];
  3228. }
  3229. /**
  3230. * Get the users files upload from his share_folder.
  3231. *
  3232. * @param string $user_id User ID
  3233. * @param string $course course directory
  3234. * @param string $resourceType resource type: images, all
  3235. *
  3236. * @return string
  3237. */
  3238. public static function get_user_upload_files_by_course(
  3239. $user_id,
  3240. $course,
  3241. $resourceType = 'all'
  3242. ) {
  3243. $return = '';
  3244. $user_id = (int) $user_id;
  3245. if (!empty($user_id) && !empty($course)) {
  3246. $path = api_get_path(SYS_COURSE_PATH).$course.'/document/shared_folder/sf_user_'.$user_id.'/';
  3247. $web_path = api_get_path(WEB_COURSE_PATH).$course.'/document/shared_folder/sf_user_'.$user_id.'/';
  3248. $file_list = [];
  3249. if (is_dir($path)) {
  3250. $handle = opendir($path);
  3251. while ($file = readdir($handle)) {
  3252. if ($file == '.' || $file == '..' || $file == '.htaccess' || is_dir($path.$file)) {
  3253. continue; // skip current/parent directory and .htaccess
  3254. }
  3255. $file_list[] = $file;
  3256. }
  3257. if (count($file_list) > 0) {
  3258. $return = "<h4>$course</h4>";
  3259. $return .= '<ul class="thumbnails">';
  3260. }
  3261. $extensionList = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'tif'];
  3262. foreach ($file_list as $file) {
  3263. if ($resourceType == 'all') {
  3264. $return .= '<li>
  3265. <a href="'.$web_path.urlencode($file).'" target="_blank">'.htmlentities($file).'</a></li>';
  3266. } elseif ($resourceType == 'images') {
  3267. //get extension
  3268. $ext = explode('.', $file);
  3269. if (isset($ext[1]) && in_array($ext[1], $extensionList)) {
  3270. $return .= '<li class="span2">
  3271. <a class="thumbnail" href="'.$web_path.urlencode($file).'" target="_blank">
  3272. <img src="'.$web_path.urlencode($file).'" >
  3273. </a>
  3274. </li>';
  3275. }
  3276. }
  3277. }
  3278. if (count($file_list) > 0) {
  3279. $return .= '</ul>';
  3280. }
  3281. }
  3282. }
  3283. return $return;
  3284. }
  3285. /**
  3286. * Gets the API key (or keys) and return them into an array.
  3287. *
  3288. * @param int Optional user id (defaults to the result of api_get_user_id())
  3289. * @param string $api_service
  3290. *
  3291. * @return mixed Non-indexed array containing the list of API keys for this user, or FALSE on error
  3292. */
  3293. public static function get_api_keys($user_id = null, $api_service = 'dokeos')
  3294. {
  3295. if ($user_id != strval(intval($user_id))) {
  3296. return false;
  3297. }
  3298. if (empty($user_id)) {
  3299. $user_id = api_get_user_id();
  3300. }
  3301. if ($user_id === false) {
  3302. return false;
  3303. }
  3304. $service_name = Database::escape_string($api_service);
  3305. if (is_string($service_name) === false) {
  3306. return false;
  3307. }
  3308. $t_api = Database::get_main_table(TABLE_MAIN_USER_API_KEY);
  3309. $sql = "SELECT * FROM $t_api WHERE user_id = $user_id AND api_service='$api_service';";
  3310. $res = Database::query($sql);
  3311. if ($res === false) {
  3312. return false;
  3313. } //error during query
  3314. $num = Database::num_rows($res);
  3315. if ($num == 0) {
  3316. return false;
  3317. }
  3318. $list = [];
  3319. while ($row = Database::fetch_array($res)) {
  3320. $list[$row['id']] = $row['api_key'];
  3321. }
  3322. return $list;
  3323. }
  3324. /**
  3325. * Adds a new API key to the users' account.
  3326. *
  3327. * @param int Optional user ID (defaults to the results of api_get_user_id())
  3328. * @param string $api_service
  3329. *
  3330. * @return bool True on success, false on failure
  3331. */
  3332. public static function add_api_key($user_id = null, $api_service = 'dokeos')
  3333. {
  3334. if ($user_id != strval(intval($user_id))) {
  3335. return false;
  3336. }
  3337. if (empty($user_id)) {
  3338. $user_id = api_get_user_id();
  3339. }
  3340. if ($user_id === false) {
  3341. return false;
  3342. }
  3343. $service_name = Database::escape_string($api_service);
  3344. if (is_string($service_name) === false) {
  3345. return false;
  3346. }
  3347. $t_api = Database::get_main_table(TABLE_MAIN_USER_API_KEY);
  3348. $md5 = md5((time() + ($user_id * 5)) - rand(10000, 10000)); //generate some kind of random key
  3349. $sql = "INSERT INTO $t_api (user_id, api_key,api_service) VALUES ($user_id,'$md5','$service_name')";
  3350. $res = Database::query($sql);
  3351. if ($res === false) {
  3352. return false;
  3353. } //error during query
  3354. $num = Database::insert_id();
  3355. return $num == 0 ? false : $num;
  3356. }
  3357. /**
  3358. * Deletes an API key from the user's account.
  3359. *
  3360. * @param int API key's internal ID
  3361. *
  3362. * @return bool True on success, false on failure
  3363. */
  3364. public static function delete_api_key($key_id)
  3365. {
  3366. if ($key_id != strval(intval($key_id))) {
  3367. return false;
  3368. }
  3369. if ($key_id === false) {
  3370. return false;
  3371. }
  3372. $t_api = Database::get_main_table(TABLE_MAIN_USER_API_KEY);
  3373. $sql = "SELECT * FROM $t_api WHERE id = ".$key_id;
  3374. $res = Database::query($sql);
  3375. if ($res === false) {
  3376. return false;
  3377. } //error during query
  3378. $num = Database::num_rows($res);
  3379. if ($num !== 1) {
  3380. return false;
  3381. }
  3382. $sql = "DELETE FROM $t_api WHERE id = ".$key_id;
  3383. $res = Database::query($sql);
  3384. if ($res === false) {
  3385. return false;
  3386. } //error during query
  3387. return true;
  3388. }
  3389. /**
  3390. * Regenerate an API key from the user's account.
  3391. *
  3392. * @param int user ID (defaults to the results of api_get_user_id())
  3393. * @param string API key's internal ID
  3394. *
  3395. * @return int num
  3396. */
  3397. public static function update_api_key($user_id, $api_service)
  3398. {
  3399. if ($user_id != strval(intval($user_id))) {
  3400. return false;
  3401. }
  3402. if ($user_id === false) {
  3403. return false;
  3404. }
  3405. $service_name = Database::escape_string($api_service);
  3406. if (is_string($service_name) === false) {
  3407. return false;
  3408. }
  3409. $t_api = Database::get_main_table(TABLE_MAIN_USER_API_KEY);
  3410. $sql = "SELECT id FROM $t_api
  3411. WHERE user_id=".$user_id." AND api_service='".$api_service."'";
  3412. $res = Database::query($sql);
  3413. $num = Database::num_rows($res);
  3414. if ($num == 1) {
  3415. $id_key = Database::fetch_array($res, 'ASSOC');
  3416. self::delete_api_key($id_key['id']);
  3417. $num = self::add_api_key($user_id, $api_service);
  3418. } elseif ($num == 0) {
  3419. $num = self::add_api_key($user_id, $api_service);
  3420. }
  3421. return $num;
  3422. }
  3423. /**
  3424. * @param int user ID (defaults to the results of api_get_user_id())
  3425. * @param string API key's internal ID
  3426. *
  3427. * @return int row ID, or return false if not found
  3428. */
  3429. public static function get_api_key_id($user_id, $api_service)
  3430. {
  3431. if ($user_id != strval(intval($user_id))) {
  3432. return false;
  3433. }
  3434. if ($user_id === false) {
  3435. return false;
  3436. }
  3437. if (empty($api_service)) {
  3438. return false;
  3439. }
  3440. $t_api = Database::get_main_table(TABLE_MAIN_USER_API_KEY);
  3441. $api_service = Database::escape_string($api_service);
  3442. $sql = "SELECT id FROM $t_api
  3443. WHERE user_id=".$user_id." AND api_service='".$api_service."'";
  3444. $res = Database::query($sql);
  3445. if (Database::num_rows($res) < 1) {
  3446. return false;
  3447. }
  3448. $row = Database::fetch_array($res, 'ASSOC');
  3449. return $row['id'];
  3450. }
  3451. /**
  3452. * Checks if a user_id is platform admin.
  3453. *
  3454. * @param int user ID
  3455. *
  3456. * @return bool True if is admin, false otherwise
  3457. *
  3458. * @see main_api.lib.php::api_is_platform_admin() for a context-based check
  3459. */
  3460. public static function is_admin($user_id)
  3461. {
  3462. $user_id = (int) $user_id;
  3463. if (empty($user_id)) {
  3464. return false;
  3465. }
  3466. $admin_table = Database::get_main_table(TABLE_MAIN_ADMIN);
  3467. $sql = "SELECT * FROM $admin_table WHERE user_id = $user_id";
  3468. $res = Database::query($sql);
  3469. return Database::num_rows($res) === 1;
  3470. }
  3471. /**
  3472. * Get the total count of users.
  3473. *
  3474. * @param int $status Status of users to be counted
  3475. * @param int $access_url_id Access URL ID (optional)
  3476. * @param int $active
  3477. *
  3478. * @return mixed Number of users or false on error
  3479. */
  3480. public static function get_number_of_users($status = 0, $access_url_id = 1, $active = null)
  3481. {
  3482. $t_u = Database::get_main_table(TABLE_MAIN_USER);
  3483. $t_a = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  3484. if (api_is_multiple_url_enabled()) {
  3485. $sql = "SELECT count(u.id)
  3486. FROM $t_u u
  3487. INNER JOIN $t_a url_user
  3488. ON (u.id = url_user.user_id)
  3489. WHERE url_user.access_url_id = $access_url_id
  3490. ";
  3491. } else {
  3492. $sql = "SELECT count(u.id)
  3493. FROM $t_u u
  3494. WHERE 1 = 1 ";
  3495. }
  3496. if (is_int($status) && $status > 0) {
  3497. $status = (int) $status;
  3498. $sql .= " AND u.status = $status ";
  3499. }
  3500. if ($active !== null) {
  3501. $active = (int) $active;
  3502. $sql .= " AND u.active = $active ";
  3503. }
  3504. $res = Database::query($sql);
  3505. if (Database::num_rows($res) === 1) {
  3506. return (int) Database::result($res, 0, 0);
  3507. }
  3508. return false;
  3509. }
  3510. /**
  3511. * Gets the tags of a specific field_id
  3512. * USER TAGS.
  3513. *
  3514. * Instructions to create a new user tag by Julio Montoya <gugli100@gmail.com>
  3515. *
  3516. * 1. Create a new extra field in main/admin/user_fields.php with the "TAG" field type make it available and visible.
  3517. * Called it "books" for example.
  3518. * 2. Go to profile main/auth/profile.php There you will see a special input (facebook style) that will show suggestions of tags.
  3519. * 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
  3520. * 4. Tags are independent this means that tags can't be shared between tags + book + hobbies.
  3521. * 5. Test and enjoy.
  3522. *
  3523. * @param string $tag
  3524. * @param int $field_id field_id
  3525. * @param string $return_format how we are going to result value in array or in a string (json)
  3526. * @param $limit
  3527. *
  3528. * @return mixed
  3529. */
  3530. public static function get_tags($tag, $field_id, $return_format = 'json', $limit = 10)
  3531. {
  3532. // database table definition
  3533. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  3534. $field_id = (int) $field_id;
  3535. $limit = (int) $limit;
  3536. $tag = trim(Database::escape_string($tag));
  3537. // all the information of the field
  3538. $sql = "SELECT DISTINCT id, tag from $table_user_tag
  3539. WHERE field_id = $field_id AND tag LIKE '$tag%' ORDER BY tag LIMIT $limit";
  3540. $result = Database::query($sql);
  3541. $return = [];
  3542. if (Database::num_rows($result) > 0) {
  3543. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3544. $return[] = ['id' => $row['tag'], 'text' => $row['tag']];
  3545. }
  3546. }
  3547. if ($return_format === 'json') {
  3548. $return = json_encode($return);
  3549. }
  3550. return $return;
  3551. }
  3552. /**
  3553. * @param int $field_id
  3554. * @param int $limit
  3555. *
  3556. * @return array
  3557. */
  3558. public static function get_top_tags($field_id, $limit = 100)
  3559. {
  3560. // database table definition
  3561. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  3562. $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
  3563. $field_id = (int) $field_id;
  3564. $limit = (int) $limit;
  3565. // all the information of the field
  3566. $sql = "SELECT count(*) count, tag FROM $table_user_tag_values uv
  3567. INNER JOIN $table_user_tag ut
  3568. ON (ut.id = uv.tag_id)
  3569. WHERE field_id = $field_id
  3570. GROUP BY tag_id
  3571. ORDER BY count DESC
  3572. LIMIT $limit";
  3573. $result = Database::query($sql);
  3574. $return = [];
  3575. if (Database::num_rows($result) > 0) {
  3576. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3577. $return[] = $row;
  3578. }
  3579. }
  3580. return $return;
  3581. }
  3582. /**
  3583. * Get user's tags.
  3584. *
  3585. * @param int $user_id
  3586. * @param int $field_id
  3587. *
  3588. * @return array
  3589. */
  3590. public static function get_user_tags($user_id, $field_id)
  3591. {
  3592. // database table definition
  3593. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  3594. $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
  3595. $field_id = (int) $field_id;
  3596. $user_id = (int) $user_id;
  3597. // all the information of the field
  3598. $sql = "SELECT ut.id, tag, count
  3599. FROM $table_user_tag ut
  3600. INNER JOIN $table_user_tag_values uv
  3601. ON (uv.tag_id=ut.ID)
  3602. WHERE field_id = $field_id AND user_id = $user_id
  3603. ORDER BY tag";
  3604. $result = Database::query($sql);
  3605. $return = [];
  3606. if (Database::num_rows($result) > 0) {
  3607. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3608. $return[$row['id']] = ['tag' => $row['tag'], 'count' => $row['count']];
  3609. }
  3610. }
  3611. return $return;
  3612. }
  3613. /**
  3614. * Get user's tags.
  3615. *
  3616. * @param int $user_id
  3617. * @param int $field_id
  3618. * @param bool $show_links show links or not
  3619. *
  3620. * @return string
  3621. */
  3622. public static function get_user_tags_to_string($user_id, $field_id, $show_links = true)
  3623. {
  3624. // database table definition
  3625. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  3626. $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
  3627. $field_id = (int) $field_id;
  3628. $user_id = (int) $user_id;
  3629. // all the information of the field
  3630. $sql = "SELECT ut.id, tag,count FROM $table_user_tag ut
  3631. INNER JOIN $table_user_tag_values uv
  3632. ON (uv.tag_id = ut.id)
  3633. WHERE field_id = $field_id AND user_id = $user_id
  3634. ORDER BY tag";
  3635. $result = Database::query($sql);
  3636. $return = [];
  3637. if (Database::num_rows($result) > 0) {
  3638. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3639. $return[$row['id']] = ['tag' => $row['tag'], 'count' => $row['count']];
  3640. }
  3641. }
  3642. $user_tags = $return;
  3643. $tag_tmp = [];
  3644. foreach ($user_tags as $tag) {
  3645. if ($show_links) {
  3646. $tag_tmp[] = '<a href="'.api_get_path(WEB_PATH).'main/search/index.php?q='.$tag['tag'].'">'.
  3647. $tag['tag'].
  3648. '</a>';
  3649. } else {
  3650. $tag_tmp[] = $tag['tag'];
  3651. }
  3652. }
  3653. if (is_array($user_tags) && count($user_tags) > 0) {
  3654. return implode(', ', $tag_tmp);
  3655. } else {
  3656. return '';
  3657. }
  3658. }
  3659. /**
  3660. * Get the tag id.
  3661. *
  3662. * @param int $tag
  3663. * @param int $field_id
  3664. *
  3665. * @return int returns 0 if fails otherwise the tag id
  3666. */
  3667. public static function get_tag_id($tag, $field_id)
  3668. {
  3669. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  3670. $tag = Database::escape_string($tag);
  3671. $field_id = (int) $field_id;
  3672. //with COLLATE latin1_bin to select query in a case sensitive mode
  3673. $sql = "SELECT id FROM $table_user_tag
  3674. WHERE tag LIKE '$tag' AND field_id = $field_id";
  3675. $result = Database::query($sql);
  3676. if (Database::num_rows($result) > 0) {
  3677. $row = Database::fetch_array($result, 'ASSOC');
  3678. return $row['id'];
  3679. } else {
  3680. return 0;
  3681. }
  3682. }
  3683. /**
  3684. * Get the tag id.
  3685. *
  3686. * @param int $tag_id
  3687. * @param int $field_id
  3688. *
  3689. * @return int 0 if fails otherwise the tag id
  3690. */
  3691. public static function get_tag_id_from_id($tag_id, $field_id)
  3692. {
  3693. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  3694. $tag_id = (int) $tag_id;
  3695. $field_id = (int) $field_id;
  3696. $sql = "SELECT id FROM $table_user_tag
  3697. WHERE id = '$tag_id' AND field_id = $field_id";
  3698. $result = Database::query($sql);
  3699. if (Database::num_rows($result) > 0) {
  3700. $row = Database::fetch_array($result, 'ASSOC');
  3701. return $row['id'];
  3702. } else {
  3703. return false;
  3704. }
  3705. }
  3706. /**
  3707. * Adds a user-tag value.
  3708. *
  3709. * @param mixed $tag
  3710. * @param int $user_id
  3711. * @param int $field_id field id of the tag
  3712. *
  3713. * @return bool True if the tag was inserted or updated. False otherwise.
  3714. * The return value doesn't take into account *values* added to the tag.
  3715. * Only the creation/update of the tag field itself.
  3716. */
  3717. public static function add_tag($tag, $user_id, $field_id)
  3718. {
  3719. // database table definition
  3720. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  3721. $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
  3722. $tag = trim(Database::escape_string($tag));
  3723. $user_id = (int) $user_id;
  3724. $field_id = (int) $field_id;
  3725. $tag_id = self::get_tag_id($tag, $field_id);
  3726. /* IMPORTANT
  3727. * @todo we don't create tags with numbers
  3728. *
  3729. */
  3730. if (is_numeric($tag)) {
  3731. //the form is sending an id this means that the user select it from the list so it MUST exists
  3732. /* $new_tag_id = self::get_tag_id_from_id($tag,$field_id);
  3733. if ($new_tag_id !== false) {
  3734. $sql = "UPDATE $table_user_tag SET count = count + 1 WHERE id = $new_tag_id";
  3735. $result = Database::query($sql);
  3736. $last_insert_id = $new_tag_id;
  3737. } else {
  3738. $sql = "INSERT INTO $table_user_tag (tag, field_id,count) VALUES ('$tag','$field_id', count + 1)";
  3739. $result = Database::query($sql);
  3740. $last_insert_id = Database::insert_id();
  3741. } */
  3742. }
  3743. //this is a new tag
  3744. if ($tag_id == 0) {
  3745. //the tag doesn't exist
  3746. $sql = "INSERT INTO $table_user_tag (tag, field_id,count) VALUES ('$tag','$field_id', count + 1)";
  3747. Database::query($sql);
  3748. $last_insert_id = Database::insert_id();
  3749. } else {
  3750. //the tag exists we update it
  3751. $sql = "UPDATE $table_user_tag SET count = count + 1 WHERE id = $tag_id";
  3752. Database::query($sql);
  3753. $last_insert_id = $tag_id;
  3754. }
  3755. if (!empty($last_insert_id) && ($last_insert_id != 0)) {
  3756. //we insert the relationship user-tag
  3757. $sql = "SELECT tag_id FROM $table_user_tag_values
  3758. WHERE user_id = $user_id AND tag_id = $last_insert_id ";
  3759. $result = Database::query($sql);
  3760. //if the relationship does not exist we create it
  3761. if (Database::num_rows($result) == 0) {
  3762. $sql = "INSERT INTO $table_user_tag_values SET user_id = $user_id, tag_id = $last_insert_id";
  3763. Database::query($sql);
  3764. }
  3765. return true;
  3766. }
  3767. return false;
  3768. }
  3769. /**
  3770. * Deletes an user tag.
  3771. *
  3772. * @param int $user_id
  3773. * @param int $field_id
  3774. */
  3775. public static function delete_user_tags($user_id, $field_id)
  3776. {
  3777. // database table definition
  3778. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  3779. $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
  3780. $user_id = (int) $user_id;
  3781. $tags = self::get_user_tags($user_id, $field_id);
  3782. if (is_array($tags) && count($tags) > 0) {
  3783. foreach ($tags as $key => $tag) {
  3784. if ($tag['count'] > '0') {
  3785. $sql = "UPDATE $table_user_tag SET count = count - 1 WHERE id = $key ";
  3786. Database::query($sql);
  3787. }
  3788. $sql = "DELETE FROM $table_user_tag_values
  3789. WHERE user_id = $user_id AND tag_id = $key";
  3790. Database::query($sql);
  3791. }
  3792. }
  3793. }
  3794. /**
  3795. * Process the tag list comes from the UserManager::update_extra_field_value() function.
  3796. *
  3797. * @param array $tags the tag list that will be added
  3798. * @param int $user_id
  3799. * @param int $field_id
  3800. *
  3801. * @return bool
  3802. */
  3803. public static function process_tags($tags, $user_id, $field_id)
  3804. {
  3805. // We loop the tags and add it to the DB
  3806. if (is_array($tags)) {
  3807. foreach ($tags as $tag) {
  3808. self::add_tag($tag, $user_id, $field_id);
  3809. }
  3810. } else {
  3811. self::add_tag($tags, $user_id, $field_id);
  3812. }
  3813. return true;
  3814. }
  3815. /**
  3816. * Returns a list of all administrators.
  3817. *
  3818. * @return array
  3819. */
  3820. public static function get_all_administrators()
  3821. {
  3822. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  3823. $table_admin = Database::get_main_table(TABLE_MAIN_ADMIN);
  3824. $tbl_url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  3825. $access_url_id = api_get_current_access_url_id();
  3826. if (api_get_multiple_access_url()) {
  3827. $sql = "SELECT admin.user_id, username, firstname, lastname, email, active
  3828. FROM $tbl_url_rel_user as url
  3829. INNER JOIN $table_admin as admin
  3830. ON (admin.user_id=url.user_id)
  3831. INNER JOIN $table_user u
  3832. ON (u.id=admin.user_id)
  3833. WHERE access_url_id ='".$access_url_id."'";
  3834. } else {
  3835. $sql = "SELECT admin.user_id, username, firstname, lastname, email, active
  3836. FROM $table_admin as admin
  3837. INNER JOIN $table_user u
  3838. ON (u.id=admin.user_id)";
  3839. }
  3840. $result = Database::query($sql);
  3841. $return = [];
  3842. if (Database::num_rows($result) > 0) {
  3843. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3844. $return[$row['user_id']] = $row;
  3845. }
  3846. }
  3847. return $return;
  3848. }
  3849. /**
  3850. * Search an user (tags, first name, last name and email ).
  3851. *
  3852. * @param string $tag
  3853. * @param int $field_id field id of the tag
  3854. * @param int $from where to start in the query
  3855. * @param int $number_of_items
  3856. * @param bool $getCount get count or not
  3857. *
  3858. * @return array
  3859. */
  3860. public static function get_all_user_tags(
  3861. $tag,
  3862. $field_id = 0,
  3863. $from = 0,
  3864. $number_of_items = 10,
  3865. $getCount = false
  3866. ) {
  3867. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  3868. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  3869. $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
  3870. $access_url_rel_user_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  3871. $field_id = intval($field_id);
  3872. $from = intval($from);
  3873. $number_of_items = intval($number_of_items);
  3874. $where_field = "";
  3875. $where_extra_fields = self::get_search_form_where_extra_fields();
  3876. if ($field_id != 0) {
  3877. $where_field = " field_id = $field_id AND ";
  3878. }
  3879. // all the information of the field
  3880. if ($getCount) {
  3881. $select = "SELECT count(DISTINCT u.id) count";
  3882. } else {
  3883. $select = "SELECT DISTINCT u.id, u.username, firstname, lastname, email, tag, picture_uri";
  3884. }
  3885. $sql = " $select
  3886. FROM $user_table u
  3887. INNER JOIN $access_url_rel_user_table url_rel_user
  3888. ON (u.id = url_rel_user.user_id)
  3889. LEFT JOIN $table_user_tag_values uv
  3890. ON (u.id AND uv.user_id AND uv.user_id = url_rel_user.user_id)
  3891. LEFT JOIN $table_user_tag ut ON (uv.tag_id = ut.id)
  3892. WHERE
  3893. ($where_field tag LIKE '".Database::escape_string($tag."%")."') OR
  3894. (
  3895. u.firstname LIKE '".Database::escape_string("%".$tag."%")."' OR
  3896. u.lastname LIKE '".Database::escape_string("%".$tag."%")."' OR
  3897. u.username LIKE '".Database::escape_string("%".$tag."%")."' OR
  3898. concat(u.firstname, ' ', u.lastname) LIKE '".Database::escape_string("%".$tag."%")."' OR
  3899. concat(u.lastname, ' ', u.firstname) LIKE '".Database::escape_string("%".$tag."%")."'
  3900. )
  3901. ".(!empty($where_extra_fields) ? $where_extra_fields : '')."
  3902. AND url_rel_user.access_url_id=".api_get_current_access_url_id();
  3903. $keyword_active = true;
  3904. // only active users
  3905. if ($keyword_active) {
  3906. $sql .= " AND u.active='1'";
  3907. }
  3908. // avoid anonymous
  3909. $sql .= " AND u.status <> 6 ";
  3910. $sql .= " ORDER BY username";
  3911. $sql .= " LIMIT $from , $number_of_items";
  3912. $result = Database::query($sql);
  3913. $return = [];
  3914. if (Database::num_rows($result) > 0) {
  3915. if ($getCount) {
  3916. $row = Database::fetch_array($result, 'ASSOC');
  3917. return $row['count'];
  3918. }
  3919. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3920. if (isset($return[$row['id']]) &&
  3921. !empty($return[$row['id']]['tag'])
  3922. ) {
  3923. $url = Display::url(
  3924. $row['tag'],
  3925. api_get_path(WEB_PATH).'main/social/search.php?q='.$row['tag'],
  3926. ['class' => 'tag']
  3927. );
  3928. $row['tag'] = $url;
  3929. }
  3930. $return[$row['id']] = $row;
  3931. }
  3932. }
  3933. return $return;
  3934. }
  3935. /**
  3936. * Get extra filterable user fields (only type select).
  3937. *
  3938. * @return array Array of extra fields as [int => ['name' => ..., 'variable' => ..., 'data' => ...]] (
  3939. * or empty array if no extra field)
  3940. */
  3941. public static function getExtraFilterableFields()
  3942. {
  3943. $extraFieldList = self::get_extra_fields();
  3944. $fields = [];
  3945. if (is_array($extraFieldList)) {
  3946. foreach ($extraFieldList as $extraField) {
  3947. // If is enabled to filter and is a "<select>" field type
  3948. if ($extraField[8] == 1 && $extraField[2] == 4) {
  3949. $fields[] = [
  3950. 'name' => $extraField[3],
  3951. 'variable' => $extraField[1],
  3952. 'data' => $extraField[9],
  3953. ];
  3954. }
  3955. }
  3956. }
  3957. return $fields;
  3958. }
  3959. /**
  3960. * Get extra where clauses for finding users based on extra filterable user fields (type select).
  3961. *
  3962. * @return string With AND clauses based on user's ID which have the values to search in extra user fields
  3963. * (or empty if no extra field exists)
  3964. */
  3965. public static function get_search_form_where_extra_fields()
  3966. {
  3967. $useExtraFields = false;
  3968. $extraFields = self::getExtraFilterableFields();
  3969. $extraFieldResult = [];
  3970. if (is_array($extraFields) && count($extraFields) > 0) {
  3971. foreach ($extraFields as $extraField) {
  3972. $varName = 'field_'.$extraField['variable'];
  3973. if (self::is_extra_field_available($extraField['variable'])) {
  3974. if (isset($_GET[$varName]) && $_GET[$varName] != '0') {
  3975. $useExtraFields = true;
  3976. $extraFieldResult[] = self::get_extra_user_data_by_value(
  3977. $extraField['variable'],
  3978. $_GET[$varName]
  3979. );
  3980. }
  3981. }
  3982. }
  3983. }
  3984. if ($useExtraFields) {
  3985. $finalResult = [];
  3986. if (count($extraFieldResult) > 1) {
  3987. for ($i = 0; $i < count($extraFieldResult) - 1; $i++) {
  3988. if (is_array($extraFieldResult[$i]) && is_array($extraFieldResult[$i + 1])) {
  3989. $finalResult = array_intersect($extraFieldResult[$i], $extraFieldResult[$i + 1]);
  3990. }
  3991. }
  3992. } else {
  3993. $finalResult = $extraFieldResult[0];
  3994. }
  3995. if (is_array($finalResult) && count($finalResult) > 0) {
  3996. $whereFilter = " AND u.id IN ('".implode("','", $finalResult)."') ";
  3997. } else {
  3998. //no results
  3999. $whereFilter = " AND u.id = -1 ";
  4000. }
  4001. return $whereFilter;
  4002. }
  4003. return '';
  4004. }
  4005. /**
  4006. * Show the search form.
  4007. *
  4008. * @param string $query the value of the search box
  4009. *
  4010. * @throws Exception
  4011. *
  4012. * @return string HTML form
  4013. */
  4014. public static function get_search_form($query, $defaultParams = [])
  4015. {
  4016. $searchType = isset($_GET['search_type']) ? $_GET['search_type'] : null;
  4017. $form = new FormValidator(
  4018. 'search_user',
  4019. 'get',
  4020. api_get_path(WEB_PATH).'main/social/search.php',
  4021. '',
  4022. [],
  4023. FormValidator::LAYOUT_HORIZONTAL
  4024. );
  4025. $query = Security::remove_XSS($query);
  4026. if (!empty($query)) {
  4027. $form->addHeader(get_lang('Results').' "'.$query.'"');
  4028. }
  4029. $form->addText(
  4030. 'q',
  4031. get_lang('UsersGroups'),
  4032. false,
  4033. [
  4034. 'id' => 'q',
  4035. ]
  4036. );
  4037. $options = [
  4038. 0 => get_lang('Select'),
  4039. 1 => get_lang('User'),
  4040. 2 => get_lang('Group'),
  4041. ];
  4042. $form->addSelect(
  4043. 'search_type',
  4044. get_lang('Type'),
  4045. $options,
  4046. ['onchange' => 'javascript: extra_field_toogle();', 'id' => 'search_type']
  4047. );
  4048. // Extra fields
  4049. $extraFields = self::getExtraFilterableFields();
  4050. $defaults = [];
  4051. if (is_array($extraFields) && count($extraFields) > 0) {
  4052. foreach ($extraFields as $extraField) {
  4053. $varName = 'field_'.$extraField['variable'];
  4054. $options = [
  4055. 0 => get_lang('Select'),
  4056. ];
  4057. foreach ($extraField['data'] as $option) {
  4058. if (isset($_GET[$varName])) {
  4059. if ($_GET[$varName] == $option[1]) {
  4060. $defaults[$option[1]] = true;
  4061. }
  4062. }
  4063. $options[$option[1]] = $option[1];
  4064. }
  4065. $form->addSelect($varName, $extraField['name'], $options);
  4066. }
  4067. }
  4068. $defaults['search_type'] = (int) $searchType;
  4069. $defaults['q'] = $query;
  4070. if (!empty($defaultParams)) {
  4071. $defaults = array_merge($defaults, $defaultParams);
  4072. }
  4073. $form->setDefaults($defaults);
  4074. $form->addButtonSearch(get_lang('Search'));
  4075. $js = '<script>
  4076. extra_field_toogle();
  4077. function extra_field_toogle() {
  4078. if (jQuery("select[name=search_type]").val() != "1") {
  4079. jQuery(".extra_field").hide();
  4080. } else {
  4081. jQuery(".extra_field").show();
  4082. }
  4083. }
  4084. </script>';
  4085. return $js.$form->returnForm();
  4086. }
  4087. /**
  4088. * Shows the user menu.
  4089. */
  4090. public static function show_menu()
  4091. {
  4092. echo '<div class="actions">';
  4093. echo '<a href="/main/auth/profile.php">'.
  4094. Display::return_icon('profile.png').' '.get_lang('PersonalData').'</a>';
  4095. echo '<a href="/main/messages/inbox.php">'.
  4096. Display::return_icon('inbox.png').' '.get_lang('Inbox').'</a>';
  4097. echo '<a href="/main/messages/outbox.php">'.
  4098. Display::return_icon('outbox.png').' '.get_lang('Outbox').'</a>';
  4099. echo '<span style="float:right; padding-top:7px;">'.
  4100. '<a href="/main/auth/profile.php?show=1">'.
  4101. Display::return_icon('edit.gif').' '.get_lang('Configuration').'</a>';
  4102. echo '</span>';
  4103. echo '</div>';
  4104. }
  4105. /**
  4106. * Allow to register contact to social network.
  4107. *
  4108. * @param int $friend_id user friend id
  4109. * @param int $my_user_id user id
  4110. * @param int $relation_type relation between users see constants definition
  4111. *
  4112. * @return bool
  4113. */
  4114. public static function relate_users($friend_id, $my_user_id, $relation_type)
  4115. {
  4116. $tbl_my_friend = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  4117. $friend_id = (int) $friend_id;
  4118. $my_user_id = (int) $my_user_id;
  4119. $relation_type = (int) $relation_type;
  4120. $sql = 'SELECT COUNT(*) as count FROM '.$tbl_my_friend.'
  4121. WHERE
  4122. friend_user_id='.$friend_id.' AND
  4123. user_id='.$my_user_id.' AND
  4124. relation_type NOT IN('.USER_RELATION_TYPE_RRHH.', '.USER_RELATION_TYPE_BOSS.') ';
  4125. $result = Database::query($sql);
  4126. $row = Database::fetch_array($result, 'ASSOC');
  4127. $current_date = api_get_utc_datetime();
  4128. if ($row['count'] == 0) {
  4129. $sql = 'INSERT INTO '.$tbl_my_friend.'(friend_user_id,user_id,relation_type,last_edit)
  4130. VALUES ('.$friend_id.','.$my_user_id.','.$relation_type.',"'.$current_date.'")';
  4131. Database::query($sql);
  4132. return true;
  4133. }
  4134. $sql = 'SELECT COUNT(*) as count, relation_type FROM '.$tbl_my_friend.'
  4135. WHERE
  4136. friend_user_id='.$friend_id.' AND
  4137. user_id='.$my_user_id.' AND
  4138. relation_type NOT IN('.USER_RELATION_TYPE_RRHH.', '.USER_RELATION_TYPE_BOSS.') ';
  4139. $result = Database::query($sql);
  4140. $row = Database::fetch_array($result, 'ASSOC');
  4141. if ($row['count'] == 1) {
  4142. //only for the case of a RRHH or a Student BOSS
  4143. if ($row['relation_type'] != $relation_type &&
  4144. ($relation_type == USER_RELATION_TYPE_RRHH || $relation_type == USER_RELATION_TYPE_BOSS)
  4145. ) {
  4146. $sql = 'INSERT INTO '.$tbl_my_friend.'(friend_user_id,user_id,relation_type,last_edit)
  4147. VALUES ('.$friend_id.','.$my_user_id.','.$relation_type.',"'.$current_date.'")';
  4148. } else {
  4149. $sql = 'UPDATE '.$tbl_my_friend.' SET relation_type='.$relation_type.'
  4150. WHERE friend_user_id='.$friend_id.' AND user_id='.$my_user_id;
  4151. }
  4152. Database::query($sql);
  4153. return true;
  4154. }
  4155. return false;
  4156. }
  4157. /**
  4158. * Deletes a contact.
  4159. *
  4160. * @param bool $friend_id
  4161. * @param bool $real_removed true will delete ALL friends relationship
  4162. * @param string $with_status_condition
  4163. *
  4164. * @author isaac flores paz <isaac.flores@dokeos.com>
  4165. * @author Julio Montoya <gugli100@gmail.com> Cleaning code
  4166. */
  4167. public static function remove_user_rel_user(
  4168. $friend_id,
  4169. $real_removed = false,
  4170. $with_status_condition = ''
  4171. ) {
  4172. $tbl_my_friend = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  4173. $tbl_my_message = Database::get_main_table(TABLE_MESSAGE);
  4174. $friend_id = (int) $friend_id;
  4175. $user_id = api_get_user_id();
  4176. if ($real_removed) {
  4177. $extra_condition = '';
  4178. if ($with_status_condition != '') {
  4179. $extra_condition = ' AND relation_type = '.intval($with_status_condition);
  4180. }
  4181. $sql = 'DELETE FROM '.$tbl_my_friend.'
  4182. WHERE
  4183. relation_type <> '.USER_RELATION_TYPE_RRHH.' AND
  4184. friend_user_id='.$friend_id.' '.$extra_condition;
  4185. Database::query($sql);
  4186. $sql = 'DELETE FROM '.$tbl_my_friend.'
  4187. WHERE
  4188. relation_type <> '.USER_RELATION_TYPE_RRHH.' AND
  4189. user_id='.$friend_id.' '.$extra_condition;
  4190. Database::query($sql);
  4191. } else {
  4192. $sql = 'SELECT COUNT(*) as count FROM '.$tbl_my_friend.'
  4193. WHERE
  4194. user_id='.$user_id.' AND
  4195. relation_type NOT IN('.USER_RELATION_TYPE_DELETED.', '.USER_RELATION_TYPE_RRHH.') AND
  4196. friend_user_id='.$friend_id;
  4197. $result = Database::query($sql);
  4198. $row = Database::fetch_array($result, 'ASSOC');
  4199. if ($row['count'] == 1) {
  4200. //Delete user rel user
  4201. $sql_i = 'UPDATE '.$tbl_my_friend.' SET relation_type='.USER_RELATION_TYPE_DELETED.'
  4202. WHERE user_id='.$user_id.' AND friend_user_id='.$friend_id;
  4203. $sql_j = 'UPDATE '.$tbl_my_message.' SET msg_status='.MESSAGE_STATUS_INVITATION_DENIED.'
  4204. WHERE
  4205. user_receiver_id='.$user_id.' AND
  4206. user_sender_id='.$friend_id.' AND update_date="0000-00-00 00:00:00" ';
  4207. // Delete user
  4208. $sql_ij = 'UPDATE '.$tbl_my_friend.' SET relation_type='.USER_RELATION_TYPE_DELETED.'
  4209. WHERE user_id='.$friend_id.' AND friend_user_id='.$user_id;
  4210. $sql_ji = 'UPDATE '.$tbl_my_message.' SET msg_status='.MESSAGE_STATUS_INVITATION_DENIED.'
  4211. WHERE
  4212. user_receiver_id='.$friend_id.' AND
  4213. user_sender_id='.$user_id.' AND
  4214. update_date="0000-00-00 00:00:00" ';
  4215. Database::query($sql_i);
  4216. Database::query($sql_j);
  4217. Database::query($sql_ij);
  4218. Database::query($sql_ji);
  4219. }
  4220. }
  4221. // Delete accepted invitations
  4222. $sql = "DELETE FROM $tbl_my_message
  4223. WHERE
  4224. msg_status = ".MESSAGE_STATUS_INVITATION_ACCEPTED." AND
  4225. (
  4226. user_receiver_id = $user_id AND
  4227. user_sender_id = $friend_id
  4228. ) OR
  4229. (
  4230. user_sender_id = $user_id AND
  4231. user_receiver_id = $friend_id
  4232. )
  4233. ";
  4234. Database::query($sql);
  4235. }
  4236. /**
  4237. * @param int $userId
  4238. *
  4239. * @return array
  4240. */
  4241. public static function getDrhListFromUser($userId)
  4242. {
  4243. $tblUser = Database::get_main_table(TABLE_MAIN_USER);
  4244. $tblUserRelUser = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  4245. $tblUserRelAccessUrl = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  4246. $userId = (int) $userId;
  4247. $orderBy = null;
  4248. if (api_is_western_name_order()) {
  4249. $orderBy .= ' ORDER BY firstname, lastname ';
  4250. } else {
  4251. $orderBy .= ' ORDER BY lastname, firstname ';
  4252. }
  4253. $sql = "SELECT u.id, username, u.firstname, u.lastname
  4254. FROM $tblUser u
  4255. INNER JOIN $tblUserRelUser uru ON (uru.friend_user_id = u.id)
  4256. INNER JOIN $tblUserRelAccessUrl a ON (a.user_id = u.id)
  4257. WHERE
  4258. access_url_id = ".api_get_current_access_url_id()." AND
  4259. uru.user_id = '$userId' AND
  4260. relation_type = '".USER_RELATION_TYPE_RRHH."'
  4261. $orderBy
  4262. ";
  4263. $result = Database::query($sql);
  4264. return Database::store_result($result);
  4265. }
  4266. /**
  4267. * get users followed by human resource manager.
  4268. *
  4269. * @param int $userId
  4270. * @param int $userStatus (STUDENT, COURSEMANAGER, etc)
  4271. * @param bool $getOnlyUserId
  4272. * @param bool $getSql
  4273. * @param bool $getCount
  4274. * @param int $from
  4275. * @param int $numberItems
  4276. * @param int $column
  4277. * @param string $direction
  4278. * @param int $active
  4279. * @param string $lastConnectionDate
  4280. *
  4281. * @return array users
  4282. */
  4283. public static function get_users_followed_by_drh(
  4284. $userId,
  4285. $userStatus = 0,
  4286. $getOnlyUserId = false,
  4287. $getSql = false,
  4288. $getCount = false,
  4289. $from = null,
  4290. $numberItems = null,
  4291. $column = null,
  4292. $direction = null,
  4293. $active = null,
  4294. $lastConnectionDate = null
  4295. ) {
  4296. return self::getUsersFollowedByUser(
  4297. $userId,
  4298. $userStatus,
  4299. $getOnlyUserId,
  4300. $getSql,
  4301. $getCount,
  4302. $from,
  4303. $numberItems,
  4304. $column,
  4305. $direction,
  4306. $active,
  4307. $lastConnectionDate,
  4308. DRH
  4309. );
  4310. }
  4311. /**
  4312. * Get users followed by human resource manager.
  4313. *
  4314. * @param int $userId
  4315. * @param int $userStatus Filter users by status (STUDENT, COURSEMANAGER, etc)
  4316. * @param bool $getOnlyUserId
  4317. * @param bool $getSql
  4318. * @param bool $getCount
  4319. * @param int $from
  4320. * @param int $numberItems
  4321. * @param int $column
  4322. * @param string $direction
  4323. * @param int $active
  4324. * @param string $lastConnectionDate
  4325. * @param int $status the function is called by who? COURSEMANAGER, DRH?
  4326. * @param string $keyword
  4327. *
  4328. * @return mixed Users list (array) or the SQL query if $getSQL was set to true
  4329. */
  4330. public static function getUsersFollowedByUser(
  4331. $userId,
  4332. $userStatus = null,
  4333. $getOnlyUserId = false,
  4334. $getSql = false,
  4335. $getCount = false,
  4336. $from = null,
  4337. $numberItems = null,
  4338. $column = null,
  4339. $direction = null,
  4340. $active = null,
  4341. $lastConnectionDate = null,
  4342. $status = null,
  4343. $keyword = null
  4344. ) {
  4345. // Database Table Definitions
  4346. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  4347. $tbl_user_rel_user = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  4348. $tbl_user_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  4349. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  4350. $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  4351. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  4352. $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  4353. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  4354. $userId = (int) $userId;
  4355. $limitCondition = '';
  4356. if (isset($from) && isset($numberItems)) {
  4357. $from = (int) $from;
  4358. $numberItems = (int) $numberItems;
  4359. $limitCondition = "LIMIT $from, $numberItems";
  4360. }
  4361. $column = Database::escape_string($column);
  4362. $direction = in_array(strtolower($direction), ['asc', 'desc']) ? $direction : null;
  4363. $userConditions = '';
  4364. if (!empty($userStatus)) {
  4365. $userConditions .= ' AND u.status = '.intval($userStatus);
  4366. }
  4367. $select = " SELECT DISTINCT u.id user_id, u.username, u.lastname, u.firstname, u.email ";
  4368. if ($getOnlyUserId) {
  4369. $select = " SELECT DISTINCT u.id user_id";
  4370. }
  4371. $masterSelect = "SELECT DISTINCT * FROM ";
  4372. if ($getCount) {
  4373. $masterSelect = "SELECT COUNT(DISTINCT(user_id)) as count FROM ";
  4374. $select = " SELECT DISTINCT(u.id) user_id";
  4375. }
  4376. if (!is_null($active)) {
  4377. $active = intval($active);
  4378. $userConditions .= " AND u.active = $active ";
  4379. }
  4380. if (!empty($keyword)) {
  4381. $keyword = Database::escape_string($keyword);
  4382. $userConditions .= " AND (
  4383. u.username LIKE '%$keyword%' OR
  4384. u.firstname LIKE '%$keyword%' OR
  4385. u.lastname LIKE '%$keyword%' OR
  4386. u.official_code LIKE '%$keyword%' OR
  4387. u.email LIKE '%$keyword%'
  4388. )";
  4389. }
  4390. if (!empty($lastConnectionDate)) {
  4391. $lastConnectionDate = Database::escape_string($lastConnectionDate);
  4392. $userConditions .= " AND u.last_login <= '$lastConnectionDate' ";
  4393. }
  4394. $sessionConditionsCoach = null;
  4395. $sessionConditionsTeacher = null;
  4396. $drhConditions = null;
  4397. $teacherSelect = null;
  4398. switch ($status) {
  4399. case DRH:
  4400. $drhConditions .= " AND
  4401. friend_user_id = '$userId' AND
  4402. relation_type = '".USER_RELATION_TYPE_RRHH."'
  4403. ";
  4404. break;
  4405. case COURSEMANAGER:
  4406. $drhConditions .= " AND
  4407. friend_user_id = '$userId' AND
  4408. relation_type = '".USER_RELATION_TYPE_RRHH."'
  4409. ";
  4410. $sessionConditionsCoach .= " AND
  4411. (s.id_coach = '$userId')
  4412. ";
  4413. $sessionConditionsTeacher .= " AND
  4414. (scu.status = 2 AND scu.user_id = '$userId')
  4415. ";
  4416. $teacherSelect =
  4417. "UNION ALL (
  4418. $select
  4419. FROM $tbl_user u
  4420. INNER JOIN $tbl_session_rel_user sru ON (sru.user_id = u.id)
  4421. WHERE
  4422. (
  4423. sru.session_id IN (
  4424. SELECT DISTINCT(s.id) FROM $tbl_session s INNER JOIN
  4425. $tbl_session_rel_access_url session_rel_access_rel_user
  4426. ON session_rel_access_rel_user.session_id = s.id
  4427. WHERE access_url_id = ".api_get_current_access_url_id()."
  4428. $sessionConditionsCoach
  4429. ) OR sru.session_id IN (
  4430. SELECT DISTINCT(s.id) FROM $tbl_session s
  4431. INNER JOIN $tbl_session_rel_access_url url
  4432. ON (url.session_id = s.id)
  4433. INNER JOIN $tbl_session_rel_course_rel_user scu
  4434. ON (scu.session_id = s.id)
  4435. WHERE access_url_id = ".api_get_current_access_url_id()."
  4436. $sessionConditionsTeacher
  4437. )
  4438. )
  4439. $userConditions
  4440. )
  4441. UNION ALL(
  4442. $select
  4443. FROM $tbl_user u
  4444. INNER JOIN $tbl_course_user cu ON (cu.user_id = u.id)
  4445. WHERE cu.c_id IN (
  4446. SELECT DISTINCT(c_id) FROM $tbl_course_user
  4447. WHERE user_id = $userId AND status = ".COURSEMANAGER."
  4448. )
  4449. $userConditions
  4450. )"
  4451. ;
  4452. break;
  4453. case STUDENT_BOSS:
  4454. $drhConditions = " AND friend_user_id = $userId AND relation_type = ".USER_RELATION_TYPE_BOSS;
  4455. break;
  4456. case HRM_REQUEST:
  4457. $drhConditions .= " AND
  4458. friend_user_id = '$userId' AND
  4459. relation_type = '".USER_RELATION_TYPE_HRM_REQUEST."'
  4460. ";
  4461. break;
  4462. }
  4463. $join = null;
  4464. $sql = " $masterSelect
  4465. (
  4466. (
  4467. $select
  4468. FROM $tbl_user u
  4469. INNER JOIN $tbl_user_rel_user uru ON (uru.user_id = u.id)
  4470. LEFT JOIN $tbl_user_rel_access_url a ON (a.user_id = u.id)
  4471. $join
  4472. WHERE
  4473. access_url_id = ".api_get_current_access_url_id()."
  4474. $drhConditions
  4475. $userConditions
  4476. )
  4477. $teacherSelect
  4478. ) as t1";
  4479. if ($getSql) {
  4480. return $sql;
  4481. }
  4482. if ($getCount) {
  4483. $result = Database::query($sql);
  4484. $row = Database::fetch_array($result);
  4485. return $row['count'];
  4486. }
  4487. $orderBy = null;
  4488. if ($getOnlyUserId == false) {
  4489. if (api_is_western_name_order()) {
  4490. $orderBy .= " ORDER BY firstname, lastname ";
  4491. } else {
  4492. $orderBy .= " ORDER BY lastname, firstname ";
  4493. }
  4494. if (!empty($column) && !empty($direction)) {
  4495. // Fixing order due the UNIONs
  4496. $column = str_replace('u.', '', $column);
  4497. $orderBy = " ORDER BY $column $direction ";
  4498. }
  4499. }
  4500. $sql .= $orderBy;
  4501. $sql .= $limitCondition;
  4502. $result = Database::query($sql);
  4503. $users = [];
  4504. if (Database::num_rows($result) > 0) {
  4505. while ($row = Database::fetch_array($result)) {
  4506. $users[$row['user_id']] = $row;
  4507. }
  4508. }
  4509. return $users;
  4510. }
  4511. /**
  4512. * Subscribes users to human resource manager (Dashboard feature).
  4513. *
  4514. * @param int $hr_dept_id
  4515. * @param array $users_id
  4516. * @param bool $deleteOtherAssignedUsers
  4517. *
  4518. * @return int
  4519. */
  4520. public static function subscribeUsersToHRManager(
  4521. $hr_dept_id,
  4522. $users_id,
  4523. $deleteOtherAssignedUsers = true
  4524. ) {
  4525. return self::subscribeUsersToUser(
  4526. $hr_dept_id,
  4527. $users_id,
  4528. USER_RELATION_TYPE_RRHH,
  4529. false,
  4530. $deleteOtherAssignedUsers
  4531. );
  4532. }
  4533. /**
  4534. * Register request to assign users to HRM.
  4535. *
  4536. * @param int $hrmId The HRM ID
  4537. * @param array $usersId The users IDs
  4538. *
  4539. * @return int
  4540. */
  4541. public static function requestUsersToHRManager($hrmId, $usersId)
  4542. {
  4543. return self::subscribeUsersToUser(
  4544. $hrmId,
  4545. $usersId,
  4546. USER_RELATION_TYPE_HRM_REQUEST,
  4547. false,
  4548. false
  4549. );
  4550. }
  4551. /**
  4552. * Remove the requests for assign a user to a HRM.
  4553. *
  4554. * @param User $hrmId
  4555. * @param array $usersId List of user IDs from whom to remove all relations requests with HRM
  4556. */
  4557. public static function clearHrmRequestsForUser(User $hrmId, $usersId)
  4558. {
  4559. $users = implode(', ', $usersId);
  4560. Database::getManager()
  4561. ->createQuery('
  4562. DELETE FROM ChamiloCoreBundle:UserRelUser uru
  4563. WHERE uru.friendUserId = :hrm_id AND uru.relationType = :relation_type AND uru.userId IN (:users_ids)
  4564. ')
  4565. ->execute(['hrm_id' => $hrmId, 'relation_type' => USER_RELATION_TYPE_HRM_REQUEST, 'users_ids' => $users]);
  4566. }
  4567. /**
  4568. * Add subscribed users to a user by relation type.
  4569. *
  4570. * @param int $userId The user id
  4571. * @param array $subscribedUsersId The id of subscribed users
  4572. * @param string $relationType The relation type
  4573. * @param bool $deleteUsersBeforeInsert
  4574. * @param bool $deleteOtherAssignedUsers
  4575. *
  4576. * @return int
  4577. */
  4578. public static function subscribeUsersToUser(
  4579. $userId,
  4580. $subscribedUsersId,
  4581. $relationType,
  4582. $deleteUsersBeforeInsert = false,
  4583. $deleteOtherAssignedUsers = true
  4584. ) {
  4585. $userRelUserTable = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  4586. $userRelAccessUrlTable = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  4587. $userId = (int) $userId;
  4588. $relationType = (int) $relationType;
  4589. $affectedRows = 0;
  4590. if ($deleteOtherAssignedUsers) {
  4591. if (api_get_multiple_access_url()) {
  4592. // Deleting assigned users to hrm_id
  4593. $sql = "SELECT s.user_id
  4594. FROM $userRelUserTable s
  4595. INNER JOIN $userRelAccessUrlTable a
  4596. ON (a.user_id = s.user_id)
  4597. WHERE
  4598. friend_user_id = $userId AND
  4599. relation_type = $relationType AND
  4600. access_url_id = ".api_get_current_access_url_id();
  4601. } else {
  4602. $sql = "SELECT user_id
  4603. FROM $userRelUserTable
  4604. WHERE
  4605. friend_user_id = $userId AND
  4606. relation_type = $relationType";
  4607. }
  4608. $result = Database::query($sql);
  4609. if (Database::num_rows($result) > 0) {
  4610. while ($row = Database::fetch_array($result)) {
  4611. $sql = "DELETE FROM $userRelUserTable
  4612. WHERE
  4613. user_id = {$row['user_id']} AND
  4614. friend_user_id = $userId AND
  4615. relation_type = $relationType";
  4616. Database::query($sql);
  4617. }
  4618. }
  4619. }
  4620. if ($deleteUsersBeforeInsert) {
  4621. $sql = "DELETE FROM $userRelUserTable
  4622. WHERE
  4623. user_id = $userId AND
  4624. relation_type = $relationType";
  4625. Database::query($sql);
  4626. }
  4627. // Inserting new user list
  4628. if (is_array($subscribedUsersId)) {
  4629. foreach ($subscribedUsersId as $subscribedUserId) {
  4630. $subscribedUserId = (int) $subscribedUserId;
  4631. $sql = "SELECT id
  4632. FROM $userRelUserTable
  4633. WHERE
  4634. user_id = $subscribedUserId AND
  4635. friend_user_id = $userId AND
  4636. relation_type = $relationType";
  4637. $result = Database::query($sql);
  4638. $num = Database::num_rows($result);
  4639. if ($num === 0) {
  4640. $date = api_get_utc_datetime();
  4641. $sql = "INSERT INTO $userRelUserTable (user_id, friend_user_id, relation_type, last_edit)
  4642. VALUES ($subscribedUserId, $userId, $relationType, '$date')";
  4643. $result = Database::query($sql);
  4644. $affectedRows += Database::affected_rows($result);
  4645. }
  4646. }
  4647. }
  4648. return $affectedRows;
  4649. }
  4650. /**
  4651. * This function check if an user is followed by human resources manager.
  4652. *
  4653. * @param int $user_id
  4654. * @param int $hr_dept_id Human resources manager
  4655. *
  4656. * @return bool
  4657. */
  4658. public static function is_user_followed_by_drh($user_id, $hr_dept_id)
  4659. {
  4660. $tbl_user_rel_user = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  4661. $user_id = (int) $user_id;
  4662. $hr_dept_id = (int) $hr_dept_id;
  4663. $result = false;
  4664. $sql = "SELECT user_id FROM $tbl_user_rel_user
  4665. WHERE
  4666. user_id = $user_id AND
  4667. friend_user_id = $hr_dept_id AND
  4668. relation_type = ".USER_RELATION_TYPE_RRHH;
  4669. $rs = Database::query($sql);
  4670. if (Database::num_rows($rs) > 0) {
  4671. $result = true;
  4672. }
  4673. return $result;
  4674. }
  4675. /**
  4676. * Return the user id of teacher or session administrator.
  4677. *
  4678. * @param array $courseInfo
  4679. *
  4680. * @return mixed The user id, or false if the session ID was negative
  4681. */
  4682. public static function get_user_id_of_course_admin_or_session_admin($courseInfo)
  4683. {
  4684. $session = api_get_session_id();
  4685. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  4686. $table_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  4687. $table_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  4688. if (empty($courseInfo)) {
  4689. return false;
  4690. }
  4691. $courseId = $courseInfo['real_id'];
  4692. if ($session == 0 || is_null($session)) {
  4693. $sql = 'SELECT u.id uid FROM '.$table_user.' u
  4694. INNER JOIN '.$table_course_user.' ru
  4695. ON ru.user_id = u.id
  4696. WHERE
  4697. ru.status = 1 AND
  4698. ru.c_id = "'.$courseId.'" ';
  4699. $rs = Database::query($sql);
  4700. $num_rows = Database::num_rows($rs);
  4701. if ($num_rows == 1) {
  4702. $row = Database::fetch_array($rs);
  4703. return $row['uid'];
  4704. } else {
  4705. $my_num_rows = $num_rows;
  4706. $my_user_id = Database::result($rs, $my_num_rows - 1, 'uid');
  4707. return $my_user_id;
  4708. }
  4709. } elseif ($session > 0) {
  4710. $sql = 'SELECT u.id uid FROM '.$table_user.' u
  4711. INNER JOIN '.$table_session_course_user.' sru
  4712. ON sru.user_id=u.id
  4713. WHERE
  4714. sru.c_id="'.$courseId.'" AND
  4715. sru.status=2';
  4716. $rs = Database::query($sql);
  4717. $row = Database::fetch_array($rs);
  4718. return $row['uid'];
  4719. }
  4720. return false;
  4721. }
  4722. /**
  4723. * Determines if a user is a gradebook certified.
  4724. *
  4725. * @param int $cat_id The category id of gradebook
  4726. * @param int $user_id The user id
  4727. *
  4728. * @return bool
  4729. */
  4730. public static function is_user_certified($cat_id, $user_id)
  4731. {
  4732. $cat_id = (int) $cat_id;
  4733. $user_id = (int) $user_id;
  4734. $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
  4735. $sql = 'SELECT path_certificate
  4736. FROM '.$table.'
  4737. WHERE
  4738. cat_id = "'.$cat_id.'" AND
  4739. user_id = "'.$user_id.'"';
  4740. $rs = Database::query($sql);
  4741. $row = Database::fetch_array($rs);
  4742. if ($row['path_certificate'] == '' || is_null($row['path_certificate'])) {
  4743. return false;
  4744. }
  4745. return true;
  4746. }
  4747. /**
  4748. * Gets the info about a gradebook certificate for a user by course.
  4749. *
  4750. * @param string $course_code The course code
  4751. * @param int $user_id The user id
  4752. *
  4753. * @return array if there is not information return false
  4754. */
  4755. public static function get_info_gradebook_certificate($course_code, $user_id)
  4756. {
  4757. $tbl_grade_certificate = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
  4758. $tbl_grade_category = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  4759. $session_id = api_get_session_id();
  4760. if (empty($session_id)) {
  4761. $session_condition = ' AND (session_id = "" OR session_id = 0 OR session_id IS NULL )';
  4762. } else {
  4763. $session_condition = " AND session_id = $session_id";
  4764. }
  4765. $sql = 'SELECT * FROM '.$tbl_grade_certificate.'
  4766. WHERE cat_id = (
  4767. SELECT id FROM '.$tbl_grade_category.'
  4768. WHERE
  4769. course_code = "'.Database::escape_string($course_code).'" '.$session_condition.'
  4770. LIMIT 1
  4771. ) AND user_id='.intval($user_id);
  4772. $rs = Database::query($sql);
  4773. if (Database::num_rows($rs) > 0) {
  4774. $row = Database::fetch_array($rs, 'ASSOC');
  4775. $score = $row['score_certificate'];
  4776. $category_id = $row['cat_id'];
  4777. $cat = Category::load($category_id);
  4778. $displayscore = ScoreDisplay::instance();
  4779. if (isset($cat) && $displayscore->is_custom()) {
  4780. $grade = $displayscore->display_score(
  4781. [$score, $cat[0]->get_weight()],
  4782. SCORE_DIV_PERCENT_WITH_CUSTOM
  4783. );
  4784. } else {
  4785. $grade = $displayscore->display_score(
  4786. [$score, $cat[0]->get_weight()]
  4787. );
  4788. }
  4789. $row['grade'] = $grade;
  4790. return $row;
  4791. }
  4792. return false;
  4793. }
  4794. /**
  4795. * This function check if the user is a coach inside session course.
  4796. *
  4797. * @param int $user_id User id
  4798. * @param int $courseId
  4799. * @param int $session_id
  4800. *
  4801. * @return bool True if the user is a coach
  4802. */
  4803. public static function is_session_course_coach($user_id, $courseId, $session_id)
  4804. {
  4805. $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  4806. // Protect data
  4807. $user_id = intval($user_id);
  4808. $courseId = intval($courseId);
  4809. $session_id = intval($session_id);
  4810. $result = false;
  4811. $sql = "SELECT session_id FROM $table
  4812. WHERE
  4813. session_id = $session_id AND
  4814. c_id = $courseId AND
  4815. user_id = $user_id AND
  4816. status = 2 ";
  4817. $res = Database::query($sql);
  4818. if (Database::num_rows($res) > 0) {
  4819. $result = true;
  4820. }
  4821. return $result;
  4822. }
  4823. /**
  4824. * This function returns an icon path that represents the favicon of the website of which the url given.
  4825. * Defaults to the current Chamilo favicon.
  4826. *
  4827. * @param string $url1 URL of website where to look for favicon.ico
  4828. * @param string $url2 Optional second URL of website where to look for favicon.ico
  4829. *
  4830. * @return string Path of icon to load
  4831. */
  4832. public static function get_favicon_from_url($url1, $url2 = null)
  4833. {
  4834. $icon_link = '';
  4835. $url = $url1;
  4836. if (empty($url1)) {
  4837. $url = $url2;
  4838. if (empty($url)) {
  4839. $url = api_get_access_url(api_get_current_access_url_id());
  4840. $url = $url[0];
  4841. }
  4842. }
  4843. if (!empty($url)) {
  4844. $pieces = parse_url($url);
  4845. $icon_link = $pieces['scheme'].'://'.$pieces['host'].'/favicon.ico';
  4846. }
  4847. return $icon_link;
  4848. }
  4849. /**
  4850. * @param User $user
  4851. */
  4852. public static function add_user_as_admin(User $user)
  4853. {
  4854. $table_admin = Database::get_main_table(TABLE_MAIN_ADMIN);
  4855. if ($user) {
  4856. $userId = $user->getId();
  4857. if (!self::is_admin($userId)) {
  4858. $sql = "INSERT INTO $table_admin SET user_id = $userId";
  4859. Database::query($sql);
  4860. }
  4861. $user->addRole('ROLE_SUPER_ADMIN');
  4862. self::getManager()->updateUser($user, true);
  4863. }
  4864. }
  4865. /**
  4866. * @param int $userId
  4867. */
  4868. public static function remove_user_admin($userId)
  4869. {
  4870. $table_admin = Database::get_main_table(TABLE_MAIN_ADMIN);
  4871. $userId = (int) $userId;
  4872. if (self::is_admin($userId)) {
  4873. $sql = "DELETE FROM $table_admin WHERE user_id = $userId";
  4874. Database::query($sql);
  4875. }
  4876. }
  4877. /**
  4878. * @param string $from
  4879. * @param string $to
  4880. */
  4881. public static function update_all_user_languages($from, $to)
  4882. {
  4883. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  4884. $from = Database::escape_string($from);
  4885. $to = Database::escape_string($to);
  4886. if (!empty($to) && !empty($from)) {
  4887. $sql = "UPDATE $table_user SET language = '$to'
  4888. WHERE language = '$from'";
  4889. Database::query($sql);
  4890. }
  4891. }
  4892. /**
  4893. * Subscribe boss to students.
  4894. *
  4895. * @param int $bossId The boss id
  4896. * @param array $usersId The users array
  4897. *
  4898. * @return int Affected rows
  4899. */
  4900. public static function subscribeBossToUsers($bossId, $usersId)
  4901. {
  4902. return self::subscribeUsersToUser(
  4903. $bossId,
  4904. $usersId,
  4905. USER_RELATION_TYPE_BOSS
  4906. );
  4907. }
  4908. /**
  4909. * @param int $userId
  4910. *
  4911. * @return bool
  4912. */
  4913. public static function removeAllBossFromStudent($userId)
  4914. {
  4915. $userId = (int) $userId;
  4916. if (empty($userId)) {
  4917. return false;
  4918. }
  4919. $userRelUserTable = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  4920. $sql = "DELETE FROM $userRelUserTable
  4921. WHERE user_id = $userId AND relation_type = ".USER_RELATION_TYPE_BOSS;
  4922. Database::query($sql);
  4923. return true;
  4924. }
  4925. /**
  4926. * Subscribe boss to students, if $bossList is empty then the boss list will be empty too.
  4927. *
  4928. * @param int $studentId
  4929. * @param array $bossList
  4930. * @param bool $sendNotification
  4931. *
  4932. * @return mixed Affected rows or false on failure
  4933. */
  4934. public static function subscribeUserToBossList(
  4935. $studentId,
  4936. $bossList,
  4937. $sendNotification = false
  4938. ) {
  4939. $inserted = 0;
  4940. if (!empty($bossList)) {
  4941. sort($bossList);
  4942. $studentId = (int) $studentId;
  4943. $studentInfo = api_get_user_info($studentId);
  4944. if (empty($studentInfo)) {
  4945. return false;
  4946. }
  4947. $previousBossList = self::getStudentBossList($studentId);
  4948. $previousBossList = !empty($previousBossList) ? array_column($previousBossList, 'boss_id') : [];
  4949. sort($previousBossList);
  4950. // Boss list is the same, nothing changed.
  4951. if ($bossList == $previousBossList) {
  4952. return false;
  4953. }
  4954. $userRelUserTable = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  4955. self::removeAllBossFromStudent($studentId);
  4956. foreach ($bossList as $bossId) {
  4957. $bossId = (int) $bossId;
  4958. $sql = "INSERT IGNORE INTO $userRelUserTable (user_id, friend_user_id, relation_type)
  4959. VALUES ($studentId, $bossId, ".USER_RELATION_TYPE_BOSS.")";
  4960. $insertId = Database::query($sql);
  4961. if ($insertId) {
  4962. if ($sendNotification) {
  4963. $name = $studentInfo['complete_name'];
  4964. $url = api_get_path(WEB_CODE_PATH).'mySpace/myStudents.php?student='.$studentId;
  4965. $url = Display::url($url, $url);
  4966. $subject = sprintf(get_lang('UserXHasBeenAssignedToBoss'), $name);
  4967. $message = sprintf(get_lang('UserXHasBeenAssignedToBossWithUrlX'), $name, $url);
  4968. MessageManager::send_message_simple(
  4969. $bossId,
  4970. $subject,
  4971. $message
  4972. );
  4973. }
  4974. $inserted++;
  4975. }
  4976. }
  4977. } else {
  4978. self::removeAllBossFromStudent($studentId);
  4979. }
  4980. return $inserted;
  4981. }
  4982. /**
  4983. * Get users followed by student boss.
  4984. *
  4985. * @param int $userId
  4986. * @param int $userStatus (STUDENT, COURSEMANAGER, etc)
  4987. * @param bool $getOnlyUserId
  4988. * @param bool $getSql
  4989. * @param bool $getCount
  4990. * @param int $from
  4991. * @param int $numberItems
  4992. * @param int $column
  4993. * @param string $direction
  4994. * @param int $active
  4995. * @param string $lastConnectionDate
  4996. *
  4997. * @return array users
  4998. */
  4999. public static function getUsersFollowedByStudentBoss(
  5000. $userId,
  5001. $userStatus = 0,
  5002. $getOnlyUserId = false,
  5003. $getSql = false,
  5004. $getCount = false,
  5005. $from = null,
  5006. $numberItems = null,
  5007. $column = null,
  5008. $direction = null,
  5009. $active = null,
  5010. $lastConnectionDate = null
  5011. ) {
  5012. return self::getUsersFollowedByUser(
  5013. $userId,
  5014. $userStatus,
  5015. $getOnlyUserId,
  5016. $getSql,
  5017. $getCount,
  5018. $from,
  5019. $numberItems,
  5020. $column,
  5021. $direction,
  5022. $active,
  5023. $lastConnectionDate,
  5024. STUDENT_BOSS
  5025. );
  5026. }
  5027. /**
  5028. * @return array
  5029. */
  5030. public static function getOfficialCodeGrouped()
  5031. {
  5032. $user = Database::get_main_table(TABLE_MAIN_USER);
  5033. $sql = "SELECT DISTINCT official_code
  5034. FROM $user
  5035. GROUP BY official_code";
  5036. $result = Database::query($sql);
  5037. $values = Database::store_result($result, 'ASSOC');
  5038. $result = [];
  5039. foreach ($values as $value) {
  5040. $result[$value['official_code']] = $value['official_code'];
  5041. }
  5042. return $result;
  5043. }
  5044. /**
  5045. * @param string $officialCode
  5046. *
  5047. * @return array
  5048. */
  5049. public static function getUsersByOfficialCode($officialCode)
  5050. {
  5051. $user = Database::get_main_table(TABLE_MAIN_USER);
  5052. $officialCode = Database::escape_string($officialCode);
  5053. $sql = "SELECT DISTINCT id
  5054. FROM $user
  5055. WHERE official_code = '$officialCode'
  5056. ";
  5057. $result = Database::query($sql);
  5058. $users = [];
  5059. while ($row = Database::fetch_array($result)) {
  5060. $users[] = $row['id'];
  5061. }
  5062. return $users;
  5063. }
  5064. /**
  5065. * Calc the expended time (in seconds) by a user in a course.
  5066. *
  5067. * @param int $userId The user id
  5068. * @param int $courseId The course id
  5069. * @param int $sessionId Optional. The session id
  5070. * @param string $from Optional. From date
  5071. * @param string $until Optional. Until date
  5072. *
  5073. * @return int The time
  5074. */
  5075. public static function getTimeSpentInCourses(
  5076. $userId,
  5077. $courseId,
  5078. $sessionId = 0,
  5079. $from = '',
  5080. $until = ''
  5081. ) {
  5082. $userId = (int) $userId;
  5083. $sessionId = (int) $sessionId;
  5084. $trackCourseAccessTable = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  5085. $whereConditions = [
  5086. 'user_id = ? ' => $userId,
  5087. 'AND c_id = ? ' => $courseId,
  5088. 'AND session_id = ? ' => $sessionId,
  5089. ];
  5090. if (!empty($from) && !empty($until)) {
  5091. $whereConditions["AND (login_course_date >= '?' "] = $from;
  5092. $whereConditions["AND logout_course_date <= DATE_ADD('?', INTERVAL 1 DAY)) "] = $until;
  5093. }
  5094. $trackResult = Database::select(
  5095. 'SUM(UNIX_TIMESTAMP(logout_course_date) - UNIX_TIMESTAMP(login_course_date)) as total_time',
  5096. $trackCourseAccessTable,
  5097. [
  5098. 'where' => $whereConditions,
  5099. ],
  5100. 'first'
  5101. );
  5102. if ($trackResult != false) {
  5103. return $trackResult['total_time'] ? $trackResult['total_time'] : 0;
  5104. }
  5105. return 0;
  5106. }
  5107. /**
  5108. * Get the boss user ID from a followed user id.
  5109. *
  5110. * @param $userId
  5111. *
  5112. * @return bool
  5113. */
  5114. public static function getFirstStudentBoss($userId)
  5115. {
  5116. $userId = (int) $userId;
  5117. if ($userId > 0) {
  5118. $userRelTable = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  5119. $row = Database::select(
  5120. 'DISTINCT friend_user_id AS boss_id',
  5121. $userRelTable,
  5122. [
  5123. 'where' => [
  5124. 'user_id = ? AND relation_type = ? LIMIT 1' => [
  5125. $userId,
  5126. USER_RELATION_TYPE_BOSS,
  5127. ],
  5128. ],
  5129. ]
  5130. );
  5131. if (!empty($row)) {
  5132. return $row[0]['boss_id'];
  5133. }
  5134. }
  5135. return false;
  5136. }
  5137. /**
  5138. * Get the boss user ID from a followed user id.
  5139. *
  5140. * @param int $userId student id
  5141. *
  5142. * @return array
  5143. */
  5144. public static function getStudentBossList($userId)
  5145. {
  5146. $userId = (int) $userId;
  5147. if ($userId > 0) {
  5148. $userRelTable = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  5149. $result = Database::select(
  5150. 'DISTINCT friend_user_id AS boss_id',
  5151. $userRelTable,
  5152. [
  5153. 'where' => [
  5154. 'user_id = ? AND relation_type = ? ' => [
  5155. $userId,
  5156. USER_RELATION_TYPE_BOSS,
  5157. ],
  5158. ],
  5159. ]
  5160. );
  5161. return $result;
  5162. }
  5163. return [];
  5164. }
  5165. /**
  5166. * @param int $bossId
  5167. * @param int $studentId
  5168. *
  5169. * @return bool
  5170. */
  5171. public static function userIsBossOfStudent($bossId, $studentId)
  5172. {
  5173. $result = false;
  5174. $bossList = self::getStudentBossList($studentId);
  5175. if (!empty($bossList)) {
  5176. $bossList = array_column($bossList, 'boss_id');
  5177. if (in_array($bossId, $bossList)) {
  5178. $result = true;
  5179. }
  5180. }
  5181. return $result;
  5182. }
  5183. /**
  5184. * Displays the name of the user and makes the link to the user profile.
  5185. *
  5186. * @param array $userInfo
  5187. *
  5188. * @return string
  5189. */
  5190. public static function getUserProfileLink($userInfo)
  5191. {
  5192. if (isset($userInfo) && isset($userInfo['user_id'])) {
  5193. return Display::url(
  5194. $userInfo['complete_name_with_username'],
  5195. $userInfo['profile_url']
  5196. );
  5197. }
  5198. return get_lang('Anonymous');
  5199. }
  5200. /**
  5201. * Get users whose name matches $firstname and $lastname.
  5202. *
  5203. * @param string $firstname Firstname to search
  5204. * @param string $lastname Lastname to search
  5205. *
  5206. * @return array The user list
  5207. */
  5208. public static function getUsersByName($firstname, $lastname)
  5209. {
  5210. $firstname = Database::escape_string($firstname);
  5211. $lastname = Database::escape_string($lastname);
  5212. $userTable = Database::get_main_table(TABLE_MAIN_USER);
  5213. $sql = <<<SQL
  5214. SELECT id, username, lastname, firstname
  5215. FROM $userTable
  5216. WHERE
  5217. firstname LIKE '$firstname%' AND
  5218. lastname LIKE '$lastname%'
  5219. SQL;
  5220. $result = Database::query($sql);
  5221. $users = [];
  5222. while ($resultData = Database::fetch_object($result)) {
  5223. $users[] = $resultData;
  5224. }
  5225. return $users;
  5226. }
  5227. /**
  5228. * @param int $optionSelected
  5229. *
  5230. * @return string
  5231. */
  5232. public static function getUserSubscriptionTab($optionSelected = 1)
  5233. {
  5234. $allowAdmin = api_get_setting('allow_user_course_subscription_by_course_admin');
  5235. if (($allowAdmin === 'true' && api_is_allowed_to_edit()) ||
  5236. api_is_platform_admin()
  5237. ) {
  5238. $userPath = api_get_path(WEB_CODE_PATH).'user/';
  5239. $headers = [
  5240. [
  5241. 'url' => $userPath.'user.php?'.api_get_cidreq().'&type='.STUDENT,
  5242. 'content' => get_lang('Students'),
  5243. ],
  5244. [
  5245. 'url' => $userPath.'user.php?'.api_get_cidreq().'&type='.COURSEMANAGER,
  5246. 'content' => get_lang('Teachers'),
  5247. ],
  5248. /*[
  5249. 'url' => $userPath.'subscribe_user.php?'.api_get_cidreq(),
  5250. 'content' => get_lang('Students'),
  5251. ],
  5252. [
  5253. 'url' => $userPath.'subscribe_user.php?type=teacher&'.api_get_cidreq(),
  5254. 'content' => get_lang('Teachers'),
  5255. ],*/
  5256. [
  5257. 'url' => api_get_path(WEB_CODE_PATH).'group/group.php?'.api_get_cidreq(),
  5258. 'content' => get_lang('Groups'),
  5259. ],
  5260. [
  5261. 'url' => $userPath.'class.php?'.api_get_cidreq(),
  5262. 'content' => get_lang('Classes'),
  5263. ],
  5264. ];
  5265. return Display::tabsOnlyLink($headers, $optionSelected);
  5266. }
  5267. return '';
  5268. }
  5269. /**
  5270. * Make sure this function is protected because it does NOT check password!
  5271. *
  5272. * This function defines globals.
  5273. *
  5274. * @param int $userId
  5275. * @param bool $checkIfUserCanLoginAs
  5276. *
  5277. * @return bool
  5278. *
  5279. * @author Evie Embrechts
  5280. * @author Yannick Warnier <yannick.warnier@dokeos.com>
  5281. */
  5282. public static function loginAsUser($userId, $checkIfUserCanLoginAs = true)
  5283. {
  5284. $userId = (int) $userId;
  5285. $userInfo = api_get_user_info($userId);
  5286. // Check if the user is allowed to 'login_as'
  5287. $canLoginAs = true;
  5288. if ($checkIfUserCanLoginAs) {
  5289. $canLoginAs = api_can_login_as($userId);
  5290. }
  5291. if (!$canLoginAs || empty($userInfo)) {
  5292. return false;
  5293. }
  5294. if ($userId) {
  5295. $logInfo = [
  5296. 'tool' => 'logout',
  5297. 'tool_id' => 0,
  5298. 'tool_id_detail' => 0,
  5299. 'action' => '',
  5300. 'info' => 'Change user (login as)',
  5301. ];
  5302. Event::registerLog($logInfo);
  5303. // Logout the current user
  5304. self::loginDelete(api_get_user_id());
  5305. Session::erase('_user');
  5306. Session::erase('is_platformAdmin');
  5307. Session::erase('is_allowedCreateCourse');
  5308. Session::erase('_uid');
  5309. // Cleaning session variables
  5310. $_user['firstName'] = $userInfo['firstname'];
  5311. $_user['lastName'] = $userInfo['lastname'];
  5312. $_user['mail'] = $userInfo['email'];
  5313. $_user['official_code'] = $userInfo['official_code'];
  5314. $_user['picture_uri'] = $userInfo['picture_uri'];
  5315. $_user['user_id'] = $userId;
  5316. $_user['id'] = $userId;
  5317. $_user['status'] = $userInfo['status'];
  5318. // Filling session variables with new data
  5319. Session::write('_uid', $userId);
  5320. Session::write('_user', $userInfo);
  5321. Session::write('is_platformAdmin', (bool) self::is_admin($userId));
  5322. Session::write('is_allowedCreateCourse', $userInfo['status'] == 1);
  5323. // will be useful later to know if the user is actually an admin or not (example reporting)
  5324. Session::write('login_as', true);
  5325. $logInfo = [
  5326. 'tool' => 'login',
  5327. 'tool_id' => 0,
  5328. 'tool_id_detail' => 0,
  5329. 'info' => $userId,
  5330. ];
  5331. Event::registerLog($logInfo);
  5332. return true;
  5333. }
  5334. return false;
  5335. }
  5336. /**
  5337. * Remove all login records from the track_e_online stats table,
  5338. * for the given user ID.
  5339. *
  5340. * @param int $userId User ID
  5341. */
  5342. public static function loginDelete($userId)
  5343. {
  5344. $online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
  5345. $userId = (int) $userId;
  5346. $query = "DELETE FROM $online_table WHERE login_user_id = $userId";
  5347. Database::query($query);
  5348. }
  5349. /**
  5350. * Login as first admin user registered in the platform.
  5351. *
  5352. * @return array
  5353. */
  5354. public static function logInAsFirstAdmin()
  5355. {
  5356. $adminList = self::get_all_administrators();
  5357. if (!empty($adminList)) {
  5358. $userInfo = current($adminList);
  5359. if (!empty($userInfo)) {
  5360. $result = self::loginAsUser($userInfo['user_id'], false);
  5361. if ($result && api_is_platform_admin()) {
  5362. return api_get_user_info();
  5363. }
  5364. }
  5365. }
  5366. return [];
  5367. }
  5368. /**
  5369. * Check if user is teacher of a student based in their courses.
  5370. *
  5371. * @param $teacherId
  5372. * @param $studentId
  5373. *
  5374. * @return array
  5375. */
  5376. public static function getCommonCoursesBetweenTeacherAndStudent($teacherId, $studentId)
  5377. {
  5378. $courses = CourseManager::getCoursesFollowedByUser(
  5379. $teacherId,
  5380. COURSEMANAGER
  5381. );
  5382. if (empty($courses)) {
  5383. return false;
  5384. }
  5385. $coursesFromUser = CourseManager::get_courses_list_by_user_id($studentId);
  5386. if (empty($coursesFromUser)) {
  5387. return false;
  5388. }
  5389. $coursesCodeList = array_column($courses, 'code');
  5390. $coursesCodeFromUserList = array_column($coursesFromUser, 'code');
  5391. $commonCourses = array_intersect($coursesCodeList, $coursesCodeFromUserList);
  5392. $commonCourses = array_filter($commonCourses);
  5393. if (!empty($commonCourses)) {
  5394. return $commonCourses;
  5395. }
  5396. return [];
  5397. }
  5398. /**
  5399. * @param int $teacherId
  5400. * @param int $studentId
  5401. *
  5402. * @return bool
  5403. */
  5404. public static function isTeacherOfStudent($teacherId, $studentId)
  5405. {
  5406. $courses = self::getCommonCoursesBetweenTeacherAndStudent(
  5407. $teacherId,
  5408. $studentId
  5409. );
  5410. if (!empty($courses)) {
  5411. return true;
  5412. }
  5413. return false;
  5414. }
  5415. /**
  5416. * Send user confirmation mail.
  5417. *
  5418. * @param User $user
  5419. *
  5420. * @throws Exception
  5421. */
  5422. public static function sendUserConfirmationMail(User $user)
  5423. {
  5424. $uniqueId = api_get_unique_id();
  5425. $user->setConfirmationToken($uniqueId);
  5426. Database::getManager()->persist($user);
  5427. Database::getManager()->flush();
  5428. $url = api_get_path(WEB_CODE_PATH).'auth/user_mail_confirmation.php?token='.$uniqueId;
  5429. // Check if the user was originally set for an automated subscription to a course or session
  5430. $courseCodeToRedirect = Session::read('course_redirect');
  5431. $sessionToRedirect = Session::read('session_redirect');
  5432. if (!empty($courseCodeToRedirect)) {
  5433. $url .= '&c='.$courseCodeToRedirect;
  5434. }
  5435. if (!empty($sessionToRedirect)) {
  5436. $url .= '&s='.$sessionToRedirect;
  5437. }
  5438. $mailSubject = get_lang('RegistrationConfirmation');
  5439. $mailBody = get_lang('RegistrationConfirmationEmailMessage')
  5440. .PHP_EOL
  5441. .Display::url($url, $url);
  5442. api_mail_html(
  5443. self::formatUserFullName($user),
  5444. $user->getEmail(),
  5445. $mailSubject,
  5446. $mailBody
  5447. );
  5448. Display::addFlash(Display::return_message(get_lang('CheckYourEmailAndFollowInstructions')));
  5449. }
  5450. /**
  5451. * Anonymize a user. Replace personal info by anonymous info.
  5452. *
  5453. * @param int $userId User id
  5454. * @param bool $deleteIP Whether to replace the IP address in logs tables by 127.0.0.1 or to leave as is
  5455. *
  5456. * @throws \Exception
  5457. *
  5458. * @return bool
  5459. * @assert (0) === false
  5460. */
  5461. public static function anonymize($userId, $deleteIP = true)
  5462. {
  5463. global $debug;
  5464. $userId = (int) $userId;
  5465. if (empty($userId)) {
  5466. return false;
  5467. }
  5468. $em = Database::getManager();
  5469. $user = api_get_user_entity($userId);
  5470. $uniqueId = uniqid('anon', true);
  5471. $user
  5472. ->setFirstname($uniqueId)
  5473. ->setLastname($uniqueId)
  5474. ->setBiography('')
  5475. ->setAddress('')
  5476. ->setCurriculumItems(null)
  5477. ->setDateOfBirth(null)
  5478. ->setCompetences('')
  5479. ->setDiplomas('')
  5480. ->setOpenarea('')
  5481. ->setTeach('')
  5482. ->setProductions(null)
  5483. ->setOpenid('')
  5484. ->setEmailCanonical($uniqueId.'@example.com')
  5485. ->setEmail($uniqueId.'@example.com')
  5486. ->setUsername($uniqueId)
  5487. ->setUsernameCanonical($uniqueId)
  5488. ->setPhone('')
  5489. ->setOfficialCode('')
  5490. ;
  5491. self::deleteUserPicture($userId);
  5492. self::cleanUserRequestsOfRemoval($userId);
  5493. // The IP address is a border-case personal data, as it does
  5494. // not directly allow for personal identification (it is not
  5495. // a completely safe value in most countries - the IP could
  5496. // be used by neighbours and crackers)
  5497. if ($deleteIP) {
  5498. $substitute = '127.0.0.1';
  5499. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
  5500. $sql = "UPDATE $table set user_ip = '$substitute' WHERE access_user_id = $userId";
  5501. $res = Database::query($sql);
  5502. if ($res === false && $debug > 0) {
  5503. error_log("Could not anonymize IP address for user $userId ($sql)");
  5504. }
  5505. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  5506. $sql = "UPDATE $table set user_ip = '$substitute' WHERE user_id = $userId";
  5507. $res = Database::query($sql);
  5508. if ($res === false && $debug > 0) {
  5509. error_log("Could not anonymize IP address for user $userId ($sql)");
  5510. }
  5511. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  5512. $sql = "UPDATE $table set user_ip = '$substitute' WHERE exe_user_id = $userId";
  5513. $res = Database::query($sql);
  5514. if ($res === false && $debug > 0) {
  5515. error_log("Could not anonymize IP address for user $userId ($sql)");
  5516. }
  5517. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  5518. $sql = "UPDATE $table set user_ip = '$substitute' WHERE login_user_id = $userId";
  5519. $res = Database::query($sql);
  5520. if ($res === false && $debug > 0) {
  5521. error_log("Could not anonymize IP address for user $userId ($sql)");
  5522. }
  5523. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
  5524. $sql = "UPDATE $table set user_ip = '$substitute' WHERE login_user_id = $userId";
  5525. $res = Database::query($sql);
  5526. if ($res === false && $debug > 0) {
  5527. error_log("Could not anonymize IP address for user $userId ($sql)");
  5528. }
  5529. $table = Database::get_course_table(TABLE_WIKI);
  5530. $sql = "UPDATE $table set user_ip = '$substitute' WHERE user_id = $userId";
  5531. $res = Database::query($sql);
  5532. if ($res === false && $debug > 0) {
  5533. error_log("Could not anonymize IP address for user $userId ($sql)");
  5534. }
  5535. $table = Database::get_main_table(TABLE_TICKET_MESSAGE);
  5536. $sql = "UPDATE $table set ip_address = '$substitute' WHERE sys_insert_user_id = $userId";
  5537. $res = Database::query($sql);
  5538. if ($res === false && $debug > 0) {
  5539. error_log("Could not anonymize IP address for user $userId ($sql)");
  5540. }
  5541. $table = Database::get_course_table(TABLE_WIKI);
  5542. $sql = "UPDATE $table set user_ip = '$substitute' WHERE user_id = $userId";
  5543. $res = Database::query($sql);
  5544. if ($res === false && $debug > 0) {
  5545. error_log("Could not anonymize IP address for user $userId ($sql)");
  5546. }
  5547. }
  5548. $em->persist($user);
  5549. $em->flush($user);
  5550. Event::addEvent(LOG_USER_ANONYMIZE, LOG_USER_ID, $userId);
  5551. return true;
  5552. }
  5553. /**
  5554. * @param int $userId
  5555. *
  5556. * @throws Exception
  5557. *
  5558. * @return string
  5559. */
  5560. public static function anonymizeUserWithVerification($userId)
  5561. {
  5562. $allowDelete = api_get_configuration_value('allow_delete_user_for_session_admin');
  5563. $message = '';
  5564. if (api_is_platform_admin() ||
  5565. ($allowDelete && api_is_session_admin())
  5566. ) {
  5567. $userToUpdateInfo = api_get_user_info($userId);
  5568. $currentUserId = api_get_user_id();
  5569. if ($userToUpdateInfo &&
  5570. api_global_admin_can_edit_admin($userId, null, $allowDelete)
  5571. ) {
  5572. if ($userId != $currentUserId &&
  5573. self::anonymize($userId)
  5574. ) {
  5575. $message = Display::return_message(
  5576. sprintf(get_lang('UserXAnonymized'), $userToUpdateInfo['complete_name_with_username']),
  5577. 'confirmation'
  5578. );
  5579. } else {
  5580. $message = Display::return_message(
  5581. sprintf(get_lang('CannotAnonymizeUserX'), $userToUpdateInfo['complete_name_with_username']),
  5582. 'error'
  5583. );
  5584. }
  5585. } else {
  5586. $message = Display::return_message(
  5587. sprintf(get_lang('NoPermissionToAnonymizeUserX'), $userToUpdateInfo['complete_name_with_username']),
  5588. 'error'
  5589. );
  5590. }
  5591. }
  5592. return $message;
  5593. }
  5594. /**
  5595. * @param int $userId
  5596. *
  5597. * @throws Exception
  5598. *
  5599. * @return string
  5600. */
  5601. public static function deleteUserWithVerification($userId)
  5602. {
  5603. $allowDelete = api_get_configuration_value('allow_delete_user_for_session_admin');
  5604. $message = Display::return_message(get_lang('CannotDeleteUser'), 'error');
  5605. $userToUpdateInfo = api_get_user_info($userId);
  5606. // User must exist.
  5607. if (empty($userToUpdateInfo)) {
  5608. return $message;
  5609. }
  5610. $currentUserId = api_get_user_id();
  5611. // Cannot delete myself.
  5612. if ($userId == $currentUserId) {
  5613. return $message;
  5614. }
  5615. if (api_is_platform_admin() ||
  5616. ($allowDelete && api_is_session_admin())
  5617. ) {
  5618. if (api_global_admin_can_edit_admin($userId, null, $allowDelete)) {
  5619. if (self::delete_user($userId)) {
  5620. $message = Display::return_message(
  5621. get_lang('UserDeleted').': '.$userToUpdateInfo['complete_name_with_username'],
  5622. 'confirmation'
  5623. );
  5624. } else {
  5625. $message = Display::return_message(get_lang('CannotDeleteUserBecauseOwnsCourse'), 'error');
  5626. }
  5627. }
  5628. }
  5629. return $message;
  5630. }
  5631. /**
  5632. * @return array
  5633. */
  5634. public static function createDataPrivacyExtraFields()
  5635. {
  5636. self::create_extra_field(
  5637. 'request_for_legal_agreement_consent_removal_justification',
  5638. 1, //text
  5639. 'Request for legal agreement consent removal justification ',
  5640. ''
  5641. );
  5642. self::create_extra_field(
  5643. 'request_for_delete_account_justification',
  5644. 1, //text
  5645. 'Request for delete account justification',
  5646. ''
  5647. );
  5648. $extraFieldId = self::create_extra_field(
  5649. 'request_for_legal_agreement_consent_removal',
  5650. 1, //text
  5651. 'Request for legal agreement consent removal',
  5652. ''
  5653. );
  5654. $extraFieldIdDeleteAccount = self::create_extra_field(
  5655. 'request_for_delete_account',
  5656. 1, //text
  5657. 'Request for delete user account',
  5658. ''
  5659. );
  5660. return [
  5661. 'delete_account_extra_field' => $extraFieldIdDeleteAccount,
  5662. 'delete_legal' => $extraFieldId,
  5663. ];
  5664. }
  5665. /**
  5666. * @param int $userId
  5667. */
  5668. public static function cleanUserRequestsOfRemoval($userId)
  5669. {
  5670. $userId = (int) $userId;
  5671. $extraFieldValue = new ExtraFieldValue('user');
  5672. $extraFieldsToDelete = [
  5673. 'legal_accept',
  5674. 'request_for_legal_agreement_consent_removal',
  5675. 'request_for_legal_agreement_consent_removal_justification',
  5676. 'request_for_delete_account_justification', // just in case delete also this
  5677. 'request_for_delete_account',
  5678. ];
  5679. foreach ($extraFieldsToDelete as $variable) {
  5680. $value = $extraFieldValue->get_values_by_handler_and_field_variable(
  5681. $userId,
  5682. $variable
  5683. );
  5684. if ($value && isset($value['id'])) {
  5685. $extraFieldValue->delete($value['id']);
  5686. }
  5687. }
  5688. }
  5689. /**
  5690. * @param array $userInfo
  5691. * @param int $searchYear
  5692. *
  5693. * @throws Exception
  5694. *
  5695. * @return array
  5696. */
  5697. public static function getSubscribedSessionsByYear(array $userInfo, $searchYear)
  5698. {
  5699. $timezone = new DateTimeZone(api_get_timezone());
  5700. $sessions = [];
  5701. if (DRH == $userInfo['status']) {
  5702. $sessions = SessionManager::get_sessions_followed_by_drh($userInfo['id']);
  5703. } elseif (api_is_platform_admin(true)) {
  5704. $sessions = SessionManager::getSessionsForAdmin($userInfo['id']);
  5705. } else {
  5706. $sessionsByCategory = self::get_sessions_by_category($userInfo['id'], false, true, true);
  5707. $sessionsByCategory = array_column($sessionsByCategory, 'sessions');
  5708. foreach ($sessionsByCategory as $sessionsInCategory) {
  5709. $sessions = array_merge($sessions, $sessionsInCategory);
  5710. }
  5711. }
  5712. $sessions = array_map(
  5713. function ($sessionInfo) {
  5714. if (!isset($sessionInfo['session_id'])) {
  5715. $sessionInfo['session_id'] = $sessionInfo['id'];
  5716. }
  5717. if (!isset($sessionInfo['session_name'])) {
  5718. $sessionInfo['session_name'] = $sessionInfo['name'];
  5719. }
  5720. return $sessionInfo;
  5721. },
  5722. $sessions
  5723. );
  5724. $calendarSessions = [];
  5725. foreach ($sessions as $sessionInfo) {
  5726. if (!empty($sessionInfo['duration'])) {
  5727. $courseAccess = CourseManager::getFirstCourseAccessPerSessionAndUser(
  5728. $sessionInfo['session_id'],
  5729. $userInfo['id']
  5730. );
  5731. if (empty($courseAccess)) {
  5732. continue;
  5733. }
  5734. $firstAcessDate = new DateTime(api_get_local_time($courseAccess['login_course_date']), $timezone);
  5735. $lastAccessDate = clone $firstAcessDate;
  5736. $lastAccessDate->modify("+{$sessionInfo['duration']} days");
  5737. $firstAccessYear = (int) $firstAcessDate->format('Y');
  5738. $lastAccessYear = (int) $lastAccessDate->format('Y');
  5739. if ($firstAccessYear <= $searchYear && $lastAccessYear >= $searchYear) {
  5740. $calendarSessions[$sessionInfo['session_id']] = [
  5741. 'name' => $sessionInfo['session_name'],
  5742. 'access_start_date' => $firstAcessDate->format('Y-m-d h:i:s'),
  5743. 'access_end_date' => $lastAccessDate->format('Y-m-d h:i:s'),
  5744. ];
  5745. }
  5746. continue;
  5747. }
  5748. $accessStartDate = !empty($sessionInfo['access_start_date'])
  5749. ? new DateTime(api_get_local_time($sessionInfo['access_start_date']), $timezone)
  5750. : null;
  5751. $accessEndDate = !empty($sessionInfo['access_end_date'])
  5752. ? new DateTime(api_get_local_time($sessionInfo['access_end_date']), $timezone)
  5753. : null;
  5754. $accessStartYear = $accessStartDate ? (int) $accessStartDate->format('Y') : 0;
  5755. $accessEndYear = $accessEndDate ? (int) $accessEndDate->format('Y') : 0;
  5756. $isValid = false;
  5757. if ($accessStartYear && $accessEndYear) {
  5758. if ($accessStartYear <= $searchYear && $accessEndYear >= $searchYear) {
  5759. $isValid = true;
  5760. }
  5761. }
  5762. if ($accessStartYear && !$accessEndYear) {
  5763. if ($accessStartYear == $searchYear) {
  5764. $isValid = true;
  5765. }
  5766. }
  5767. if (!$accessStartYear && $accessEndYear) {
  5768. if ($accessEndYear == $searchYear) {
  5769. $isValid = true;
  5770. }
  5771. }
  5772. if ($isValid) {
  5773. $calendarSessions[$sessionInfo['session_id']] = [
  5774. 'name' => $sessionInfo['session_name'],
  5775. 'access_start_date' => $accessStartDate ? $accessStartDate->format('Y-m-d h:i:s') : null,
  5776. 'access_end_date' => $accessEndDate ? $accessEndDate->format('Y-m-d h:i:s') : null,
  5777. ];
  5778. }
  5779. }
  5780. return $calendarSessions;
  5781. }
  5782. /**
  5783. * Get sessions info for planification calendar.
  5784. *
  5785. * @param array $sessionsList Session list from UserManager::getSubscribedSessionsByYear
  5786. * @param int $searchYear
  5787. *
  5788. * @throws Exception
  5789. *
  5790. * @return array
  5791. */
  5792. public static function getSessionsCalendarByYear(array $sessionsList, $searchYear)
  5793. {
  5794. $timezone = new DateTimeZone(api_get_timezone());
  5795. $calendar = [];
  5796. foreach ($sessionsList as $sessionId => $sessionInfo) {
  5797. $startDate = $sessionInfo['access_start_date']
  5798. ? new DateTime(api_get_local_time($sessionInfo['access_start_date']), $timezone)
  5799. : null;
  5800. $endDate = $sessionInfo['access_end_date']
  5801. ? new DateTime(api_get_local_time($sessionInfo['access_end_date']), $timezone)
  5802. : null;
  5803. $startYear = $startDate ? (int) $startDate->format('Y') : 0;
  5804. $startWeekYear = $startDate ? (int) $startDate->format('o') : 0;
  5805. $startWeek = $startDate ? (int) $startDate->format('W') : 0;
  5806. $endYear = $endDate ? (int) $endDate->format('Y') : 0;
  5807. $endWeekYear = $endDate ? (int) $endDate->format('o') : 0;
  5808. $endWeek = $endDate ? (int) $endDate->format('W') : 0;
  5809. $start = $startWeekYear < $searchYear ? 0 : $startWeek - 1;
  5810. $duration = $endWeekYear > $searchYear ? 52 - $start : $endWeek - $start;
  5811. $calendar[] = [
  5812. 'id' => $sessionId,
  5813. 'name' => $sessionInfo['name'],
  5814. 'human_date' => SessionManager::convertSessionDateToString($startDate, $endDate, false, true),
  5815. 'start_in_last_year' => $startYear < $searchYear,
  5816. 'end_in_next_year' => $endYear > $searchYear,
  5817. 'no_start' => !$startWeek,
  5818. 'no_end' => !$endWeek,
  5819. 'start' => $start,
  5820. 'duration' => $duration > 0 ? $duration : 1,
  5821. ];
  5822. }
  5823. usort(
  5824. $calendar,
  5825. function ($sA, $sB) {
  5826. if ($sA['start'] == $sB['start']) {
  5827. return 0;
  5828. }
  5829. if ($sA['start'] < $sB['start']) {
  5830. return -1;
  5831. }
  5832. return 1;
  5833. }
  5834. );
  5835. return $calendar;
  5836. }
  5837. /**
  5838. * Return the user's full name. Optionally with the username.
  5839. *
  5840. * @param User $user
  5841. * @param bool $includeUsername Optional. By default username is not included.
  5842. *
  5843. * @return string
  5844. */
  5845. public static function formatUserFullName(User $user, $includeUsername = false)
  5846. {
  5847. $fullName = api_get_person_name($user->getFirstname(), $user->getLastname());
  5848. if ($includeUsername && api_get_configuration_value('hide_username_with_complete_name') !== true) {
  5849. $username = $user->getUsername();
  5850. return "$fullName ($username)";
  5851. }
  5852. return $fullName;
  5853. }
  5854. /**
  5855. * @param int $userId
  5856. *
  5857. * @return array
  5858. */
  5859. public static function getUserCareers($userId)
  5860. {
  5861. $table = Database::get_main_table(TABLE_MAIN_USER_CAREER);
  5862. $tableCareer = Database::get_main_table(TABLE_CAREER);
  5863. $userId = (int) $userId;
  5864. $sql = "SELECT c.id, c.name
  5865. FROM $table uc
  5866. INNER JOIN $tableCareer c
  5867. ON uc.career_id = c.id
  5868. WHERE user_id = $userId
  5869. ORDER BY uc.created_at
  5870. ";
  5871. $result = Database::query($sql);
  5872. return Database::store_result($result, 'ASSOC');
  5873. }
  5874. /**
  5875. * @param int $userId
  5876. * @param int $careerId
  5877. */
  5878. public static function addUserCareer($userId, $careerId)
  5879. {
  5880. if (!api_get_configuration_value('allow_career_users')) {
  5881. return false;
  5882. }
  5883. if (self::userHasCareer($userId, $careerId) === false) {
  5884. $params = ['user_id' => $userId, 'career_id' => $careerId, 'created_at' => api_get_utc_datetime(), 'updated_at' => api_get_utc_datetime()];
  5885. $table = Database::get_main_table(TABLE_MAIN_USER_CAREER);
  5886. Database::insert($table, $params);
  5887. }
  5888. return true;
  5889. }
  5890. /**
  5891. * @param int $userCareerId
  5892. * @param array $data
  5893. *
  5894. * @return bool
  5895. */
  5896. public static function updateUserCareer($userCareerId, $data)
  5897. {
  5898. if (!api_get_configuration_value('allow_career_users')) {
  5899. return false;
  5900. }
  5901. $params = ['extra_data' => $data, 'updated_at' => api_get_utc_datetime()];
  5902. $table = Database::get_main_table(TABLE_MAIN_USER_CAREER);
  5903. Database::update(
  5904. $table,
  5905. $params,
  5906. ['id = ?' => (int) $userCareerId]
  5907. );
  5908. return true;
  5909. }
  5910. /**
  5911. * @param int $userId
  5912. * @param int $careerId
  5913. *
  5914. * @return array
  5915. */
  5916. public static function getUserCareer($userId, $careerId)
  5917. {
  5918. $userId = (int) $userId;
  5919. $careerId = (int) $careerId;
  5920. $table = Database::get_main_table(TABLE_MAIN_USER_CAREER);
  5921. $sql = "SELECT * FROM $table WHERE user_id = $userId AND career_id = $careerId";
  5922. $result = Database::query($sql);
  5923. return Database::fetch_array($result, 'ASSOC');
  5924. }
  5925. /**
  5926. * @param int $userId
  5927. * @param int $careerId
  5928. *
  5929. * @return bool
  5930. */
  5931. public static function userHasCareer($userId, $careerId)
  5932. {
  5933. $userId = (int) $userId;
  5934. $careerId = (int) $careerId;
  5935. $table = Database::get_main_table(TABLE_MAIN_USER_CAREER);
  5936. $sql = "SELECT id FROM $table WHERE user_id = $userId AND career_id = $careerId";
  5937. $result = Database::query($sql);
  5938. return Database::num_rows($result) > 0;
  5939. }
  5940. /**
  5941. * @return EncoderFactory
  5942. */
  5943. private static function getEncoderFactory()
  5944. {
  5945. $encryption = self::getPasswordEncryption();
  5946. $encoders = [
  5947. 'Chamilo\\UserBundle\\Entity\\User' => new \Chamilo\UserBundle\Security\Encoder($encryption),
  5948. ];
  5949. $encoderFactory = new EncoderFactory($encoders);
  5950. return $encoderFactory;
  5951. }
  5952. /**
  5953. * @param User $user
  5954. *
  5955. * @return \Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface
  5956. */
  5957. private static function getEncoder(User $user)
  5958. {
  5959. $encoderFactory = self::getEncoderFactory();
  5960. return $encoderFactory->getEncoder($user);
  5961. }
  5962. /**
  5963. * Disables or enables a user.
  5964. *
  5965. * @param int $user_id
  5966. * @param int $active Enable or disable
  5967. *
  5968. * @return bool True on success, false on failure
  5969. * @assert (-1,0) === false
  5970. * @assert (1,1) === true
  5971. */
  5972. private static function change_active_state($user_id, $active)
  5973. {
  5974. $user_id = (int) $user_id;
  5975. $active = (int) $active;
  5976. if (empty($user_id)) {
  5977. return false;
  5978. }
  5979. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  5980. $sql = "UPDATE $table_user SET active = '$active' WHERE id = $user_id";
  5981. $r = Database::query($sql);
  5982. $ev = LOG_USER_DISABLE;
  5983. if ($active == 1) {
  5984. $ev = LOG_USER_ENABLE;
  5985. }
  5986. if ($r !== false) {
  5987. Event::addEvent($ev, LOG_USER_ID, $user_id);
  5988. }
  5989. return $r;
  5990. }
  5991. /**
  5992. * Get either a Gravatar URL or complete image tag for a specified email address.
  5993. *
  5994. * @param string $email The email address
  5995. * @param int $s Size in pixels, defaults to 80px [ 1 - 2048 ]
  5996. * @param string $d Default imageset to use [ 404 | mm | identicon | monsterid | wavatar ]
  5997. * @param string $r Maximum rating (inclusive) [ g | pg | r | x ]
  5998. * @param bool $img True to return a complete IMG tag False for just the URL
  5999. * @param array $atts Optional, additional key/value attributes to include in the IMG tag
  6000. *
  6001. * @return string containing either just a URL or a complete image tag
  6002. * @source http://gravatar.com/site/implement/images/php/
  6003. */
  6004. private static function getGravatar(
  6005. $email,
  6006. $s = 80,
  6007. $d = 'mm',
  6008. $r = 'g',
  6009. $img = false,
  6010. $atts = []
  6011. ) {
  6012. $url = 'http://www.gravatar.com/avatar/';
  6013. if (!empty($_SERVER['HTTPS'])) {
  6014. $url = 'https://secure.gravatar.com/avatar/';
  6015. }
  6016. $url .= md5(strtolower(trim($email)));
  6017. $url .= "?s=$s&d=$d&r=$r";
  6018. if ($img) {
  6019. $url = '<img src="'.$url.'"';
  6020. foreach ($atts as $key => $val) {
  6021. $url .= ' '.$key.'="'.$val.'"';
  6022. }
  6023. $url .= ' />';
  6024. }
  6025. return $url;
  6026. }
  6027. }