usermanager.lib.php 208 KB

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