Privileges.php 198 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660
  1. <?php
  2. /* vim: set expandtab sw=4 ts=4 sts=4: */
  3. /**
  4. * set of functions with the Privileges section in pma
  5. *
  6. * @package PhpMyAdmin
  7. */
  8. declare(strict_types=1);
  9. namespace PhpMyAdmin\Server;
  10. use PhpMyAdmin\Core;
  11. use PhpMyAdmin\DatabaseInterface;
  12. use PhpMyAdmin\Display\ChangePassword;
  13. use PhpMyAdmin\Message;
  14. use PhpMyAdmin\Relation;
  15. use PhpMyAdmin\RelationCleanup;
  16. use PhpMyAdmin\Response;
  17. use PhpMyAdmin\Template;
  18. use PhpMyAdmin\Url;
  19. use PhpMyAdmin\Util;
  20. /**
  21. * Privileges class
  22. *
  23. * @package PhpMyAdmin
  24. */
  25. class Privileges
  26. {
  27. /**
  28. * @var Template
  29. */
  30. public $template;
  31. /**
  32. * @var RelationCleanup
  33. */
  34. private $relationCleanup;
  35. /**
  36. * @var DatabaseInterface
  37. */
  38. public $dbi;
  39. /**
  40. * @var Relation
  41. */
  42. public $relation;
  43. /**
  44. * Privileges constructor.
  45. *
  46. * @param Template $template Template object
  47. * @param DatabaseInterface $dbi DatabaseInterface object
  48. * @param Relation $relation Relation object
  49. * @param RelationCleanup $relationCleanup RelationCleanup object
  50. */
  51. public function __construct(
  52. Template $template,
  53. $dbi,
  54. Relation $relation,
  55. RelationCleanup $relationCleanup
  56. ) {
  57. $this->template = $template;
  58. $this->dbi = $dbi;
  59. $this->relation = $relation;
  60. $this->relationCleanup = $relationCleanup;
  61. }
  62. /**
  63. * Get Html for User Group Dialog
  64. *
  65. * @param string $username username
  66. * @param bool $is_menuswork Is menuswork set in configuration
  67. *
  68. * @return string html
  69. */
  70. public function getHtmlForUserGroupDialog($username, $is_menuswork)
  71. {
  72. $html = '';
  73. if (! empty($_GET['edit_user_group_dialog']) && $is_menuswork) {
  74. $dialog = $this->getHtmlToChooseUserGroup($username);
  75. $response = Response::getInstance();
  76. if ($response->isAjax()) {
  77. $response->addJSON('message', $dialog);
  78. exit;
  79. } else {
  80. $html .= $dialog;
  81. }
  82. }
  83. return $html;
  84. }
  85. /**
  86. * Escapes wildcard in a database+table specification
  87. * before using it in a GRANT statement.
  88. *
  89. * Escaping a wildcard character in a GRANT is only accepted at the global
  90. * or database level, not at table level; this is why I remove
  91. * the escaping character. Internally, in mysql.tables_priv.Db there are
  92. * no escaping (for example test_db) but in mysql.db you'll see test\_db
  93. * for a db-specific privilege.
  94. *
  95. * @param string $dbname Database name
  96. * @param string $tablename Table name
  97. *
  98. * @return string the escaped (if necessary) database.table
  99. */
  100. public function wildcardEscapeForGrant($dbname, $tablename)
  101. {
  102. if (strlen($dbname) === 0) {
  103. $db_and_table = '*.*';
  104. } else {
  105. if (strlen($tablename) > 0) {
  106. $db_and_table = Util::backquote(
  107. Util::unescapeMysqlWildcards($dbname)
  108. )
  109. . '.' . Util::backquote($tablename);
  110. } else {
  111. $db_and_table = Util::backquote($dbname) . '.*';
  112. }
  113. }
  114. return $db_and_table;
  115. }
  116. /**
  117. * Generates a condition on the user name
  118. *
  119. * @param string $initial the user's initial
  120. *
  121. * @return string the generated condition
  122. */
  123. public function rangeOfUsers($initial = '')
  124. {
  125. // strtolower() is used because the User field
  126. // might be BINARY, so LIKE would be case sensitive
  127. if ($initial === null || $initial === '') {
  128. return '';
  129. }
  130. $ret = " WHERE `User` LIKE '"
  131. . $this->dbi->escapeString($initial) . "%'"
  132. . " OR `User` LIKE '"
  133. . $this->dbi->escapeString(mb_strtolower($initial))
  134. . "%'";
  135. return $ret;
  136. } // end function
  137. /**
  138. * Formats privilege name for a display
  139. *
  140. * @param array $privilege Privilege information
  141. * @param boolean $html Whether to use HTML
  142. *
  143. * @return string
  144. */
  145. public function formatPrivilege(array $privilege, $html)
  146. {
  147. if ($html) {
  148. return '<dfn title="' . $privilege[2] . '">'
  149. . $privilege[1] . '</dfn>';
  150. }
  151. return $privilege[1];
  152. }
  153. /**
  154. * Parses privileges into an array, it modifies the array
  155. *
  156. * @param array $row Results row from
  157. *
  158. * @return void
  159. */
  160. public function fillInTablePrivileges(array &$row)
  161. {
  162. $row1 = $this->dbi->fetchSingleRow(
  163. 'SHOW COLUMNS FROM `mysql`.`tables_priv` LIKE \'Table_priv\';',
  164. 'ASSOC'
  165. );
  166. // note: in MySQL 5.0.3 we get "Create View', 'Show view';
  167. // the View for Create is spelled with uppercase V
  168. // the view for Show is spelled with lowercase v
  169. // and there is a space between the words
  170. $av_grants = explode(
  171. '\',\'',
  172. mb_substr(
  173. $row1['Type'],
  174. mb_strpos($row1['Type'], '(') + 2,
  175. mb_strpos($row1['Type'], ')')
  176. - mb_strpos($row1['Type'], '(') - 3
  177. )
  178. );
  179. $users_grants = explode(',', $row['Table_priv']);
  180. foreach ($av_grants as $current_grant) {
  181. $row[$current_grant . '_priv']
  182. = in_array($current_grant, $users_grants) ? 'Y' : 'N';
  183. }
  184. unset($row['Table_priv']);
  185. }
  186. /**
  187. * Extracts the privilege information of a priv table row
  188. *
  189. * @param array|null $row the row
  190. * @param boolean $enableHTML add <dfn> tag with tooltips
  191. * @param boolean $tablePrivs whether row contains table privileges
  192. *
  193. * @global resource $user_link the database connection
  194. *
  195. * @return array
  196. */
  197. public function extractPrivInfo($row = null, $enableHTML = false, $tablePrivs = false)
  198. {
  199. if ($tablePrivs) {
  200. $grants = $this->getTableGrantsArray();
  201. } else {
  202. $grants = $this->getGrantsArray();
  203. }
  204. if ($row !== null && isset($row['Table_priv'])) {
  205. $this->fillInTablePrivileges($row);
  206. }
  207. $privs = [];
  208. $allPrivileges = true;
  209. foreach ($grants as $current_grant) {
  210. if (($row !== null && isset($row[$current_grant[0]]))
  211. || ($row === null && isset($GLOBALS[$current_grant[0]]))
  212. ) {
  213. if (($row !== null && $row[$current_grant[0]] == 'Y')
  214. || ($row === null
  215. && ($GLOBALS[$current_grant[0]] == 'Y'
  216. || (is_array($GLOBALS[$current_grant[0]])
  217. && count($GLOBALS[$current_grant[0]]) == $_REQUEST['column_count']
  218. && empty($GLOBALS[$current_grant[0] . '_none']))))
  219. ) {
  220. $privs[] = $this->formatPrivilege($current_grant, $enableHTML);
  221. } elseif (! empty($GLOBALS[$current_grant[0]])
  222. && is_array($GLOBALS[$current_grant[0]])
  223. && empty($GLOBALS[$current_grant[0] . '_none'])
  224. ) {
  225. // Required for proper escaping of ` (backtick) in a column name
  226. $grant_cols = array_map(
  227. function ($val) {
  228. return Util::backquote($val);
  229. },
  230. $GLOBALS[$current_grant[0]]
  231. );
  232. $privs[] = $this->formatPrivilege($current_grant, $enableHTML)
  233. . ' (' . implode(', ', $grant_cols) . ')';
  234. } else {
  235. $allPrivileges = false;
  236. }
  237. }
  238. }
  239. if (empty($privs)) {
  240. if ($enableHTML) {
  241. $privs[] = '<dfn title="' . __('No privileges.') . '">USAGE</dfn>';
  242. } else {
  243. $privs[] = 'USAGE';
  244. }
  245. } elseif ($allPrivileges
  246. && (! isset($_POST['grant_count']) || count($privs) == $_POST['grant_count'])
  247. ) {
  248. if ($enableHTML) {
  249. $privs = ['<dfn title="'
  250. . __('Includes all privileges except GRANT.')
  251. . '">ALL PRIVILEGES</dfn>',
  252. ];
  253. } else {
  254. $privs = ['ALL PRIVILEGES'];
  255. }
  256. }
  257. return $privs;
  258. }
  259. /**
  260. * Returns an array of table grants and their descriptions
  261. *
  262. * @return array array of table grants
  263. */
  264. public function getTableGrantsArray()
  265. {
  266. return [
  267. [
  268. 'Delete',
  269. 'DELETE',
  270. $GLOBALS['strPrivDescDelete'],
  271. ],
  272. [
  273. 'Create',
  274. 'CREATE',
  275. $GLOBALS['strPrivDescCreateTbl'],
  276. ],
  277. [
  278. 'Drop',
  279. 'DROP',
  280. $GLOBALS['strPrivDescDropTbl'],
  281. ],
  282. [
  283. 'Index',
  284. 'INDEX',
  285. $GLOBALS['strPrivDescIndex'],
  286. ],
  287. [
  288. 'Alter',
  289. 'ALTER',
  290. $GLOBALS['strPrivDescAlter'],
  291. ],
  292. [
  293. 'Create View',
  294. 'CREATE_VIEW',
  295. $GLOBALS['strPrivDescCreateView'],
  296. ],
  297. [
  298. 'Show view',
  299. 'SHOW_VIEW',
  300. $GLOBALS['strPrivDescShowView'],
  301. ],
  302. [
  303. 'Trigger',
  304. 'TRIGGER',
  305. $GLOBALS['strPrivDescTrigger'],
  306. ],
  307. ];
  308. }
  309. /**
  310. * Get the grants array which contains all the privilege types
  311. * and relevant grant messages
  312. *
  313. * @return array
  314. */
  315. public function getGrantsArray()
  316. {
  317. return [
  318. [
  319. 'Select_priv',
  320. 'SELECT',
  321. __('Allows reading data.'),
  322. ],
  323. [
  324. 'Insert_priv',
  325. 'INSERT',
  326. __('Allows inserting and replacing data.'),
  327. ],
  328. [
  329. 'Update_priv',
  330. 'UPDATE',
  331. __('Allows changing data.'),
  332. ],
  333. [
  334. 'Delete_priv',
  335. 'DELETE',
  336. __('Allows deleting data.'),
  337. ],
  338. [
  339. 'Create_priv',
  340. 'CREATE',
  341. __('Allows creating new databases and tables.'),
  342. ],
  343. [
  344. 'Drop_priv',
  345. 'DROP',
  346. __('Allows dropping databases and tables.'),
  347. ],
  348. [
  349. 'Reload_priv',
  350. 'RELOAD',
  351. __('Allows reloading server settings and flushing the server\'s caches.'),
  352. ],
  353. [
  354. 'Shutdown_priv',
  355. 'SHUTDOWN',
  356. __('Allows shutting down the server.'),
  357. ],
  358. [
  359. 'Process_priv',
  360. 'PROCESS',
  361. __('Allows viewing processes of all users.'),
  362. ],
  363. [
  364. 'File_priv',
  365. 'FILE',
  366. __('Allows importing data from and exporting data into files.'),
  367. ],
  368. [
  369. 'References_priv',
  370. 'REFERENCES',
  371. __('Has no effect in this MySQL version.'),
  372. ],
  373. [
  374. 'Index_priv',
  375. 'INDEX',
  376. __('Allows creating and dropping indexes.'),
  377. ],
  378. [
  379. 'Alter_priv',
  380. 'ALTER',
  381. __('Allows altering the structure of existing tables.'),
  382. ],
  383. [
  384. 'Show_db_priv',
  385. 'SHOW DATABASES',
  386. __('Gives access to the complete list of databases.'),
  387. ],
  388. [
  389. 'Super_priv',
  390. 'SUPER',
  391. __(
  392. 'Allows connecting, even if maximum number of connections '
  393. . 'is reached; required for most administrative operations '
  394. . 'like setting global variables or killing threads of other users.'
  395. ),
  396. ],
  397. [
  398. 'Create_tmp_table_priv',
  399. 'CREATE TEMPORARY TABLES',
  400. __('Allows creating temporary tables.'),
  401. ],
  402. [
  403. 'Lock_tables_priv',
  404. 'LOCK TABLES',
  405. __('Allows locking tables for the current thread.'),
  406. ],
  407. [
  408. 'Repl_slave_priv',
  409. 'REPLICATION SLAVE',
  410. __('Needed for the replication slaves.'),
  411. ],
  412. [
  413. 'Repl_client_priv',
  414. 'REPLICATION CLIENT',
  415. __('Allows the user to ask where the slaves / masters are.'),
  416. ],
  417. [
  418. 'Create_view_priv',
  419. 'CREATE VIEW',
  420. __('Allows creating new views.'),
  421. ],
  422. [
  423. 'Event_priv',
  424. 'EVENT',
  425. __('Allows to set up events for the event scheduler.'),
  426. ],
  427. [
  428. 'Trigger_priv',
  429. 'TRIGGER',
  430. __('Allows creating and dropping triggers.'),
  431. ],
  432. // for table privs:
  433. [
  434. 'Create View_priv',
  435. 'CREATE VIEW',
  436. __('Allows creating new views.'),
  437. ],
  438. [
  439. 'Show_view_priv',
  440. 'SHOW VIEW',
  441. __('Allows performing SHOW CREATE VIEW queries.'),
  442. ],
  443. // for table privs:
  444. [
  445. 'Show view_priv',
  446. 'SHOW VIEW',
  447. __('Allows performing SHOW CREATE VIEW queries.'),
  448. ],
  449. [
  450. 'Delete_history_priv',
  451. 'DELETE HISTORY',
  452. $GLOBALS['strPrivDescDeleteHistoricalRows'],
  453. ],
  454. [
  455. 'Delete versioning rows_priv',
  456. 'DELETE HISTORY',
  457. $GLOBALS['strPrivDescDeleteHistoricalRows'],
  458. ],
  459. [
  460. 'Create_routine_priv',
  461. 'CREATE ROUTINE',
  462. __('Allows creating stored routines.'),
  463. ],
  464. [
  465. 'Alter_routine_priv',
  466. 'ALTER ROUTINE',
  467. __('Allows altering and dropping stored routines.'),
  468. ],
  469. [
  470. 'Create_user_priv',
  471. 'CREATE USER',
  472. __('Allows creating, dropping and renaming user accounts.'),
  473. ],
  474. [
  475. 'Execute_priv',
  476. 'EXECUTE',
  477. __('Allows executing stored routines.'),
  478. ],
  479. ];
  480. }
  481. /**
  482. * Displays on which column(s) a table-specific privilege is granted
  483. *
  484. * @param array $columns columns array
  485. * @param array $row first row from result or boolean false
  486. * @param string $name_for_select privilege types - Select_priv, Insert_priv
  487. * Update_priv, References_priv
  488. * @param string $priv_for_header privilege for header
  489. * @param string $name privilege name: insert, select, update, references
  490. * @param string $name_for_dfn name for dfn
  491. * @param string $name_for_current name for current
  492. *
  493. * @return string html snippet
  494. */
  495. public function getHtmlForColumnPrivileges(
  496. array $columns,
  497. array $row,
  498. $name_for_select,
  499. $priv_for_header,
  500. $name,
  501. $name_for_dfn,
  502. $name_for_current
  503. ) {
  504. return $this->template->render('server/privileges/column_privileges', [
  505. 'columns' => $columns,
  506. 'row' => $row,
  507. 'name_for_select' => $name_for_select,
  508. 'priv_for_header' => $priv_for_header,
  509. 'name' => $name,
  510. 'name_for_dfn' => $name_for_dfn,
  511. 'name_for_current' => $name_for_current,
  512. ]);
  513. }
  514. /**
  515. * Get sql query for display privileges table
  516. *
  517. * @param string $db the database
  518. * @param string $table the table
  519. * @param string $username username for database connection
  520. * @param string $hostname hostname for database connection
  521. *
  522. * @return string sql query
  523. */
  524. public function getSqlQueryForDisplayPrivTable($db, $table, $username, $hostname)
  525. {
  526. if ($db == '*') {
  527. return "SELECT * FROM `mysql`.`user`"
  528. . " WHERE `User` = '" . $this->dbi->escapeString($username) . "'"
  529. . " AND `Host` = '" . $this->dbi->escapeString($hostname) . "';";
  530. } elseif ($table == '*') {
  531. return "SELECT * FROM `mysql`.`db`"
  532. . " WHERE `User` = '" . $this->dbi->escapeString($username) . "'"
  533. . " AND `Host` = '" . $this->dbi->escapeString($hostname) . "'"
  534. . " AND '" . $this->dbi->escapeString(Util::unescapeMysqlWildcards($db)) . "'"
  535. . " LIKE `Db`;";
  536. }
  537. return "SELECT `Table_priv`"
  538. . " FROM `mysql`.`tables_priv`"
  539. . " WHERE `User` = '" . $this->dbi->escapeString($username) . "'"
  540. . " AND `Host` = '" . $this->dbi->escapeString($hostname) . "'"
  541. . " AND `Db` = '" . $this->dbi->escapeString(Util::unescapeMysqlWildcards($db)) . "'"
  542. . " AND `Table_name` = '" . $this->dbi->escapeString($table) . "';";
  543. }
  544. /**
  545. * Displays a dropdown to select the user group
  546. * with menu items configured to each of them.
  547. *
  548. * @param string $username username
  549. *
  550. * @return string html to select the user group
  551. */
  552. public function getHtmlToChooseUserGroup($username)
  553. {
  554. $cfgRelation = $this->relation->getRelationsParam();
  555. $groupTable = Util::backquote($cfgRelation['db'])
  556. . "." . Util::backquote($cfgRelation['usergroups']);
  557. $userTable = Util::backquote($cfgRelation['db'])
  558. . "." . Util::backquote($cfgRelation['users']);
  559. $userGroup = '';
  560. if (isset($GLOBALS['username'])) {
  561. $sql_query = "SELECT `usergroup` FROM " . $userTable
  562. . " WHERE `username` = '" . $this->dbi->escapeString($username) . "'";
  563. $userGroup = $this->dbi->fetchValue(
  564. $sql_query,
  565. 0,
  566. 0,
  567. DatabaseInterface::CONNECT_CONTROL
  568. );
  569. }
  570. $allUserGroups = ['' => ''];
  571. $sql_query = "SELECT DISTINCT `usergroup` FROM " . $groupTable;
  572. $result = $this->relation->queryAsControlUser($sql_query, false);
  573. if ($result) {
  574. while ($row = $this->dbi->fetchRow($result)) {
  575. $allUserGroups[$row[0]] = $row[0];
  576. }
  577. }
  578. $this->dbi->freeResult($result);
  579. return $this->template->render('server/privileges/choose_user_group', [
  580. 'all_user_groups' => $allUserGroups,
  581. 'user_group' => $userGroup,
  582. 'params' => ['username' => $username],
  583. ]);
  584. }
  585. /**
  586. * Sets the user group from request values
  587. *
  588. * @param string $username username
  589. * @param string $userGroup user group to set
  590. *
  591. * @return void
  592. */
  593. public function setUserGroup($username, $userGroup)
  594. {
  595. $userGroup = $userGroup === null ? '' : $userGroup;
  596. $cfgRelation = $this->relation->getRelationsParam();
  597. if (empty($cfgRelation['db']) || empty($cfgRelation['users']) || empty($cfgRelation['usergroups'])) {
  598. return;
  599. }
  600. $userTable = Util::backquote($cfgRelation['db'])
  601. . "." . Util::backquote($cfgRelation['users']);
  602. $sql_query = "SELECT `usergroup` FROM " . $userTable
  603. . " WHERE `username` = '" . $this->dbi->escapeString($username) . "'";
  604. $oldUserGroup = $this->dbi->fetchValue(
  605. $sql_query,
  606. 0,
  607. 0,
  608. DatabaseInterface::CONNECT_CONTROL
  609. );
  610. if ($oldUserGroup === false) {
  611. $upd_query = "INSERT INTO " . $userTable . "(`username`, `usergroup`)"
  612. . " VALUES ('" . $this->dbi->escapeString($username) . "', "
  613. . "'" . $this->dbi->escapeString($userGroup) . "')";
  614. } else {
  615. if (empty($userGroup)) {
  616. $upd_query = "DELETE FROM " . $userTable
  617. . " WHERE `username`='" . $this->dbi->escapeString($username) . "'";
  618. } elseif ($oldUserGroup != $userGroup) {
  619. $upd_query = "UPDATE " . $userTable
  620. . " SET `usergroup`='" . $this->dbi->escapeString($userGroup) . "'"
  621. . " WHERE `username`='" . $this->dbi->escapeString($username) . "'";
  622. }
  623. }
  624. if (isset($upd_query)) {
  625. $this->relation->queryAsControlUser($upd_query);
  626. }
  627. }
  628. /**
  629. * Displays the privileges form table
  630. *
  631. * @param string $db the database
  632. * @param string $table the table
  633. * @param boolean $submit whether to display the submit button or not
  634. *
  635. * @global array $cfg the phpMyAdmin configuration
  636. * @global resource $user_link the database connection
  637. *
  638. * @return string html snippet
  639. */
  640. public function getHtmlToDisplayPrivilegesTable(
  641. $db = '*',
  642. $table = '*',
  643. $submit = true
  644. ) {
  645. $html_output = '';
  646. $sql_query = '';
  647. if ($db == '*') {
  648. $table = '*';
  649. }
  650. $username = '';
  651. $hostname = '';
  652. if (isset($GLOBALS['username'])) {
  653. $username = $GLOBALS['username'];
  654. $hostname = $GLOBALS['hostname'];
  655. $sql_query = $this->getSqlQueryForDisplayPrivTable(
  656. $db,
  657. $table,
  658. $username,
  659. $hostname
  660. );
  661. $row = $this->dbi->fetchSingleRow($sql_query);
  662. }
  663. if (empty($row)) {
  664. if ($table == '*' && $this->dbi->isSuperuser()) {
  665. $row = [];
  666. if ($db == '*') {
  667. $sql_query = 'SHOW COLUMNS FROM `mysql`.`user`;';
  668. } elseif ($table == '*') {
  669. $sql_query = 'SHOW COLUMNS FROM `mysql`.`db`;';
  670. }
  671. $res = $this->dbi->query($sql_query);
  672. while ($row1 = $this->dbi->fetchRow($res)) {
  673. if (mb_substr($row1[0], 0, 4) == 'max_') {
  674. $row[$row1[0]] = 0;
  675. } elseif (mb_substr($row1[0], 0, 5) == 'x509_'
  676. || mb_substr($row1[0], 0, 4) == 'ssl_'
  677. ) {
  678. $row[$row1[0]] = '';
  679. } else {
  680. $row[$row1[0]] = 'N';
  681. }
  682. }
  683. $this->dbi->freeResult($res);
  684. } elseif ($table == '*') {
  685. $row = [];
  686. } else {
  687. $row = ['Table_priv' => ''];
  688. }
  689. }
  690. if (isset($row['Table_priv'])) {
  691. $this->fillInTablePrivileges($row);
  692. // get columns
  693. $res = $this->dbi->tryQuery(
  694. 'SHOW COLUMNS FROM '
  695. . Util::backquote(
  696. Util::unescapeMysqlWildcards($db)
  697. )
  698. . '.' . Util::backquote($table) . ';'
  699. );
  700. $columns = [];
  701. if ($res) {
  702. while ($row1 = $this->dbi->fetchRow($res)) {
  703. $columns[$row1[0]] = [
  704. 'Select' => false,
  705. 'Insert' => false,
  706. 'Update' => false,
  707. 'References' => false,
  708. ];
  709. }
  710. $this->dbi->freeResult($res);
  711. }
  712. unset($res, $row1);
  713. }
  714. // table-specific privileges
  715. if (! empty($columns)) {
  716. $html_output .= $this->getHtmlForTableSpecificPrivileges(
  717. $username,
  718. $hostname,
  719. $db,
  720. $table,
  721. $columns,
  722. $row
  723. );
  724. } else {
  725. // global or db-specific
  726. $html_output .= $this->getHtmlForGlobalOrDbSpecificPrivs($db, $table, $row);
  727. }
  728. $html_output .= '</fieldset>' . "\n";
  729. if ($submit) {
  730. $html_output .= '<fieldset id="fieldset_user_privtable_footer" '
  731. . 'class="tblFooters">' . "\n"
  732. . '<input type="hidden" name="update_privs" value="1">' . "\n"
  733. . '<input class="btn btn-primary" type="submit" value="' . __('Go') . '">' . "\n"
  734. . '</fieldset>' . "\n";
  735. }
  736. return $html_output;
  737. } // end of the 'PMA_displayPrivTable()' function
  738. /**
  739. * Get HTML for "Require"
  740. *
  741. * @param array $row privilege array
  742. *
  743. * @return string html snippet
  744. */
  745. public function getHtmlForRequires(array $row)
  746. {
  747. $specified = (isset($row['ssl_type']) && $row['ssl_type'] == 'SPECIFIED');
  748. $require_options = [
  749. [
  750. 'name' => 'ssl_type',
  751. 'value' => 'NONE',
  752. 'description' => __(
  753. 'Does not require SSL-encrypted connections.'
  754. ),
  755. 'label' => 'REQUIRE NONE',
  756. 'checked' => isset($row['ssl_type'])
  757. && ($row['ssl_type'] == 'NONE'
  758. || $row['ssl_type'] == '')
  759. ? 'checked="checked"'
  760. : '',
  761. 'disabled' => false,
  762. 'radio' => true,
  763. ],
  764. [
  765. 'name' => 'ssl_type',
  766. 'value' => 'ANY',
  767. 'description' => __(
  768. 'Requires SSL-encrypted connections.'
  769. ),
  770. 'label' => 'REQUIRE SSL',
  771. 'checked' => isset($row['ssl_type']) && ($row['ssl_type'] == 'ANY')
  772. ? 'checked="checked"'
  773. : '',
  774. 'disabled' => false,
  775. 'radio' => true,
  776. ],
  777. [
  778. 'name' => 'ssl_type',
  779. 'value' => 'X509',
  780. 'description' => __(
  781. 'Requires a valid X509 certificate.'
  782. ),
  783. 'label' => 'REQUIRE X509',
  784. 'checked' => isset($row['ssl_type']) && ($row['ssl_type'] == 'X509')
  785. ? 'checked="checked"'
  786. : '',
  787. 'disabled' => false,
  788. 'radio' => true,
  789. ],
  790. [
  791. 'name' => 'ssl_type',
  792. 'value' => 'SPECIFIED',
  793. 'description' => '',
  794. 'label' => 'SPECIFIED',
  795. 'checked' => $specified ? 'checked="checked"' : '',
  796. 'disabled' => false,
  797. 'radio' => true,
  798. ],
  799. [
  800. 'name' => 'ssl_cipher',
  801. 'value' => isset($row['ssl_cipher'])
  802. ? htmlspecialchars($row['ssl_cipher']) : '',
  803. 'description' => __(
  804. 'Requires that a specific cipher method be used for a connection.'
  805. ),
  806. 'label' => 'REQUIRE CIPHER',
  807. 'checked' => '',
  808. 'disabled' => ! $specified,
  809. 'radio' => false,
  810. ],
  811. [
  812. 'name' => 'x509_issuer',
  813. 'value' => isset($row['x509_issuer'])
  814. ? htmlspecialchars($row['x509_issuer']) : '',
  815. 'description' => __(
  816. 'Requires that a valid X509 certificate issued by this CA be presented.'
  817. ),
  818. 'label' => 'REQUIRE ISSUER',
  819. 'checked' => '',
  820. 'disabled' => ! $specified,
  821. 'radio' => false,
  822. ],
  823. [
  824. 'name' => 'x509_subject',
  825. 'value' => isset($row['x509_subject'])
  826. ? htmlspecialchars($row['x509_subject']) : '',
  827. 'description' => __(
  828. 'Requires that a valid X509 certificate with this subject be presented.'
  829. ),
  830. 'label' => 'REQUIRE SUBJECT',
  831. 'checked' => '',
  832. 'disabled' => ! $specified,
  833. 'radio' => false,
  834. ],
  835. ];
  836. return $this->template->render('server/privileges/require_options', [
  837. 'require_options' => $require_options,
  838. ]);
  839. }
  840. /**
  841. * Get HTML for "Resource limits"
  842. *
  843. * @param array $row first row from result or boolean false
  844. *
  845. * @return string html snippet
  846. */
  847. public function getHtmlForResourceLimits(array $row)
  848. {
  849. $limits = [
  850. [
  851. 'input_name' => 'max_questions',
  852. 'name_main' => 'MAX QUERIES PER HOUR',
  853. 'value' => isset($row['max_questions']) ? $row['max_questions'] : '0',
  854. 'description' => __(
  855. 'Limits the number of queries the user may send to the server per hour.'
  856. ),
  857. ],
  858. [
  859. 'input_name' => 'max_updates',
  860. 'name_main' => 'MAX UPDATES PER HOUR',
  861. 'value' => isset($row['max_updates']) ? $row['max_updates'] : '0',
  862. 'description' => __(
  863. 'Limits the number of commands that change any table '
  864. . 'or database the user may execute per hour.'
  865. ),
  866. ],
  867. [
  868. 'input_name' => 'max_connections',
  869. 'name_main' => 'MAX CONNECTIONS PER HOUR',
  870. 'value' => isset($row['max_connections']) ? $row['max_connections'] : '0',
  871. 'description' => __(
  872. 'Limits the number of new connections the user may open per hour.'
  873. ),
  874. ],
  875. [
  876. 'input_name' => 'max_user_connections',
  877. 'name_main' => 'MAX USER_CONNECTIONS',
  878. 'value' => isset($row['max_user_connections']) ?
  879. $row['max_user_connections'] : '0',
  880. 'description' => __(
  881. 'Limits the number of simultaneous connections '
  882. . 'the user may have.'
  883. ),
  884. ],
  885. ];
  886. return $this->template->render('server/privileges/resource_limits', [
  887. 'limits' => $limits,
  888. ]);
  889. }
  890. /**
  891. * Get the HTML snippet for routine specific privileges
  892. *
  893. * @param string $username username for database connection
  894. * @param string $hostname hostname for database connection
  895. * @param string $db the database
  896. * @param string $routine the routine
  897. * @param string $url_dbname url encoded db name
  898. *
  899. * @return string
  900. */
  901. public function getHtmlForRoutineSpecificPrivileges(
  902. $username,
  903. $hostname,
  904. $db,
  905. $routine,
  906. $url_dbname
  907. ) {
  908. $header = $this->getHtmlHeaderForUserProperties(
  909. false,
  910. $url_dbname,
  911. $db,
  912. $username,
  913. $hostname,
  914. $routine,
  915. 'routine'
  916. );
  917. $sql = "SELECT `Proc_priv`"
  918. . " FROM `mysql`.`procs_priv`"
  919. . " WHERE `User` = '" . $this->dbi->escapeString($username) . "'"
  920. . " AND `Host` = '" . $this->dbi->escapeString($hostname) . "'"
  921. . " AND `Db` = '"
  922. . $this->dbi->escapeString(Util::unescapeMysqlWildcards($db)) . "'"
  923. . " AND `Routine_name` LIKE '" . $this->dbi->escapeString($routine) . "';";
  924. $res = $this->dbi->fetchValue($sql);
  925. $privs = $this->parseProcPriv($res);
  926. $routineArray = [$this->getTriggerPrivilegeTable()];
  927. $privTableNames = [__('Routine')];
  928. $privCheckboxes = $this->getHtmlForGlobalPrivTableWithCheckboxes(
  929. $routineArray,
  930. $privTableNames,
  931. $privs
  932. );
  933. return $this->template->render('server/privileges/edit_routine_privileges', [
  934. 'username' => $username,
  935. 'hostname' => $hostname,
  936. 'database' => $db,
  937. 'routine' => $routine,
  938. 'grant_count' => count($privs),
  939. 'priv_checkboxes' => $privCheckboxes,
  940. 'header' => $header,
  941. ]);
  942. }
  943. /**
  944. * Get routine privilege table as an array
  945. *
  946. * @return array privilege type array
  947. */
  948. public function getTriggerPrivilegeTable()
  949. {
  950. $routinePrivTable = [
  951. [
  952. 'Grant',
  953. 'GRANT',
  954. __(
  955. 'Allows user to give to other users or remove from other users '
  956. . 'privileges that user possess on this routine.'
  957. ),
  958. ],
  959. [
  960. 'Alter_routine',
  961. 'ALTER ROUTINE',
  962. __('Allows altering and dropping this routine.'),
  963. ],
  964. [
  965. 'Execute',
  966. 'EXECUTE',
  967. __('Allows executing this routine.'),
  968. ],
  969. ];
  970. return $routinePrivTable;
  971. }
  972. /**
  973. * Get the HTML snippet for table specific privileges
  974. *
  975. * @param string $username username for database connection
  976. * @param string $hostname hostname for database connection
  977. * @param string $db the database
  978. * @param string $table the table
  979. * @param array $columns columns array
  980. * @param array $row current privileges row
  981. *
  982. * @return string
  983. */
  984. public function getHtmlForTableSpecificPrivileges(
  985. $username,
  986. $hostname,
  987. $db,
  988. $table,
  989. array $columns,
  990. array $row
  991. ) {
  992. $res = $this->dbi->query(
  993. 'SELECT `Column_name`, `Column_priv`'
  994. . ' FROM `mysql`.`columns_priv`'
  995. . ' WHERE `User`'
  996. . ' = \'' . $this->dbi->escapeString($username) . "'"
  997. . ' AND `Host`'
  998. . ' = \'' . $this->dbi->escapeString($hostname) . "'"
  999. . ' AND `Db`'
  1000. . ' = \'' . $this->dbi->escapeString(
  1001. Util::unescapeMysqlWildcards($db)
  1002. ) . "'"
  1003. . ' AND `Table_name`'
  1004. . ' = \'' . $this->dbi->escapeString($table) . '\';'
  1005. );
  1006. while ($row1 = $this->dbi->fetchRow($res)) {
  1007. $row1[1] = explode(',', $row1[1]);
  1008. foreach ($row1[1] as $current) {
  1009. $columns[$row1[0]][$current] = true;
  1010. }
  1011. }
  1012. $this->dbi->freeResult($res);
  1013. unset($res, $row1, $current);
  1014. $html_output = '<input type="hidden" name="grant_count" '
  1015. . 'value="' . count($row) . '">' . "\n"
  1016. . '<input type="hidden" name="column_count" '
  1017. . 'value="' . count($columns) . '">' . "\n"
  1018. . '<fieldset id="fieldset_user_priv">' . "\n"
  1019. . '<legend data-submenu-label="' . __('Table') . '">' . __('Table-specific privileges')
  1020. . '</legend>'
  1021. . '<p><small><i>'
  1022. . __('Note: MySQL privilege names are expressed in English.')
  1023. . '</i></small></p>';
  1024. // privs that are attached to a specific column
  1025. $html_output .= $this->getHtmlForAttachedPrivilegesToTableSpecificColumn(
  1026. $columns,
  1027. $row
  1028. );
  1029. // privs that are not attached to a specific column
  1030. $html_output .= '<div class="item">' . "\n"
  1031. . $this->getHtmlForNotAttachedPrivilegesToTableSpecificColumn($row)
  1032. . '</div>' . "\n";
  1033. // for Safari 2.0.2
  1034. $html_output .= '<div class="clearfloat"></div>' . "\n";
  1035. return $html_output;
  1036. }
  1037. /**
  1038. * Get HTML snippet for privileges that are attached to a specific column
  1039. *
  1040. * @param array $columns columns array
  1041. * @param array $row first row from result or boolean false
  1042. *
  1043. * @return string
  1044. */
  1045. public function getHtmlForAttachedPrivilegesToTableSpecificColumn(array $columns, array $row)
  1046. {
  1047. $html_output = $this->getHtmlForColumnPrivileges(
  1048. $columns,
  1049. $row,
  1050. 'Select_priv',
  1051. 'SELECT',
  1052. 'select',
  1053. __('Allows reading data.'),
  1054. 'Select'
  1055. );
  1056. $html_output .= $this->getHtmlForColumnPrivileges(
  1057. $columns,
  1058. $row,
  1059. 'Insert_priv',
  1060. 'INSERT',
  1061. 'insert',
  1062. __('Allows inserting and replacing data.'),
  1063. 'Insert'
  1064. );
  1065. $html_output .= $this->getHtmlForColumnPrivileges(
  1066. $columns,
  1067. $row,
  1068. 'Update_priv',
  1069. 'UPDATE',
  1070. 'update',
  1071. __('Allows changing data.'),
  1072. 'Update'
  1073. );
  1074. $html_output .= $this->getHtmlForColumnPrivileges(
  1075. $columns,
  1076. $row,
  1077. 'References_priv',
  1078. 'REFERENCES',
  1079. 'references',
  1080. __('Has no effect in this MySQL version.'),
  1081. 'References'
  1082. );
  1083. return $html_output;
  1084. }
  1085. /**
  1086. * Get HTML for privileges that are not attached to a specific column
  1087. *
  1088. * @param array $row first row from result or boolean false
  1089. *
  1090. * @return string
  1091. */
  1092. public function getHtmlForNotAttachedPrivilegesToTableSpecificColumn(array $row)
  1093. {
  1094. $html_output = '';
  1095. foreach ($row as $current_grant => $current_grant_value) {
  1096. $grant_type = substr($current_grant, 0, -5);
  1097. if (in_array($grant_type, ['Select', 'Insert', 'Update', 'References'])
  1098. ) {
  1099. continue;
  1100. }
  1101. // make a substitution to match the messages variables;
  1102. // also we must substitute the grant we get, because we can't generate
  1103. // a form variable containing blanks (those would get changed to
  1104. // an underscore when receiving the POST)
  1105. if ($current_grant == 'Create View_priv') {
  1106. $tmp_current_grant = 'CreateView_priv';
  1107. $current_grant = 'Create_view_priv';
  1108. } elseif ($current_grant == 'Show view_priv') {
  1109. $tmp_current_grant = 'ShowView_priv';
  1110. $current_grant = 'Show_view_priv';
  1111. } elseif ($current_grant == 'Delete versioning rows_priv') {
  1112. $tmp_current_grant = 'DeleteHistoricalRows_priv';
  1113. $current_grant = 'Delete_history_priv';
  1114. } else {
  1115. $tmp_current_grant = $current_grant;
  1116. }
  1117. $html_output .= '<div class="item">' . "\n"
  1118. . '<input type="checkbox"'
  1119. . ' name="' . $current_grant . '" id="checkbox_' . $current_grant
  1120. . '" value="Y" '
  1121. . ($current_grant_value == 'Y' ? 'checked="checked" ' : '')
  1122. . 'title="';
  1123. $privGlobalName = 'strPrivDesc'
  1124. . mb_substr(
  1125. $tmp_current_grant,
  1126. 0,
  1127. mb_strlen($tmp_current_grant) - 5
  1128. );
  1129. $html_output .= (isset($GLOBALS[$privGlobalName])
  1130. ? $GLOBALS[$privGlobalName]
  1131. : $GLOBALS[$privGlobalName . 'Tbl']
  1132. )
  1133. . '">' . "\n";
  1134. $privGlobalName1 = 'strPrivDesc'
  1135. . mb_substr(
  1136. $tmp_current_grant,
  1137. 0,
  1138. - 5
  1139. );
  1140. $html_output .= '<label for="checkbox_' . $current_grant
  1141. . '"><code><dfn title="'
  1142. . (isset($GLOBALS[$privGlobalName1])
  1143. ? $GLOBALS[$privGlobalName1]
  1144. : $GLOBALS[$privGlobalName1 . 'Tbl']
  1145. )
  1146. . '">'
  1147. . mb_strtoupper(
  1148. mb_substr(
  1149. $current_grant,
  1150. 0,
  1151. -5
  1152. )
  1153. )
  1154. . '</dfn></code></label>' . "\n"
  1155. . '</div>' . "\n";
  1156. } // end foreach ()
  1157. return $html_output;
  1158. }
  1159. /**
  1160. * Get HTML for global or database specific privileges
  1161. *
  1162. * @param string $db the database
  1163. * @param string $table the table
  1164. * @param array $row first row from result or boolean false
  1165. *
  1166. * @return string
  1167. */
  1168. public function getHtmlForGlobalOrDbSpecificPrivs($db, $table, array $row)
  1169. {
  1170. $privTable_names = [
  1171. 0 => __('Data'),
  1172. 1 => __('Structure'),
  1173. 2 => __('Administration'),
  1174. ];
  1175. $privTable = [];
  1176. $privTable[0] = $this->getDataPrivilegeTable($db);
  1177. $privTable[1] = $this->getStructurePrivilegeTable($table, $row);
  1178. $privTable[2] = $this->getAdministrationPrivilegeTable($db);
  1179. $html_output = '<input type="hidden" name="grant_count" value="'
  1180. . (count($privTable[0])
  1181. + count($privTable[1])
  1182. + count($privTable[2])
  1183. - (isset($row['Grant_priv']) ? 1 : 0)
  1184. )
  1185. . '">';
  1186. if ($db == '*') {
  1187. $legend = __('Global privileges');
  1188. $menu_label = __('Global');
  1189. } elseif ($table == '*') {
  1190. $legend = __('Database-specific privileges');
  1191. $menu_label = __('Database');
  1192. } else {
  1193. $legend = __('Table-specific privileges');
  1194. $menu_label = __('Table');
  1195. }
  1196. $html_output .= '<fieldset id="fieldset_user_global_rights">'
  1197. . '<legend data-submenu-label="' . $menu_label . '">' . $legend
  1198. . '<input type="checkbox" id="addUsersForm_checkall" '
  1199. . 'class="checkall_box" title="' . __('Check all') . '"> '
  1200. . '<label for="addUsersForm_checkall">' . __('Check all') . '</label> '
  1201. . '</legend>'
  1202. . '<p><small><i>'
  1203. . __('Note: MySQL privilege names are expressed in English.')
  1204. . '</i></small></p>';
  1205. // Output the Global privilege tables with checkboxes
  1206. $html_output .= $this->getHtmlForGlobalPrivTableWithCheckboxes(
  1207. $privTable,
  1208. $privTable_names,
  1209. $row
  1210. );
  1211. // The "Resource limits" box is not displayed for db-specific privs
  1212. if ($db == '*') {
  1213. $html_output .= $this->getHtmlForResourceLimits($row);
  1214. $html_output .= $this->getHtmlForRequires($row);
  1215. }
  1216. // for Safari 2.0.2
  1217. $html_output .= '<div class="clearfloat"></div>';
  1218. return $html_output;
  1219. }
  1220. /**
  1221. * Get data privilege table as an array
  1222. *
  1223. * @param string $db the database
  1224. *
  1225. * @return array data privilege table
  1226. */
  1227. public function getDataPrivilegeTable($db)
  1228. {
  1229. $data_privTable = [
  1230. [
  1231. 'Select',
  1232. 'SELECT',
  1233. __('Allows reading data.'),
  1234. ],
  1235. [
  1236. 'Insert',
  1237. 'INSERT',
  1238. __('Allows inserting and replacing data.'),
  1239. ],
  1240. [
  1241. 'Update',
  1242. 'UPDATE',
  1243. __('Allows changing data.'),
  1244. ],
  1245. [
  1246. 'Delete',
  1247. 'DELETE',
  1248. __('Allows deleting data.'),
  1249. ],
  1250. ];
  1251. if ($db == '*') {
  1252. $data_privTable[]
  1253. = [
  1254. 'File',
  1255. 'FILE',
  1256. __('Allows importing data from and exporting data into files.'),
  1257. ];
  1258. }
  1259. return $data_privTable;
  1260. }
  1261. /**
  1262. * Get structure privilege table as an array
  1263. *
  1264. * @param string $table the table
  1265. * @param array $row first row from result or boolean false
  1266. *
  1267. * @return array structure privilege table
  1268. */
  1269. public function getStructurePrivilegeTable($table, array $row)
  1270. {
  1271. $structure_privTable = [
  1272. [
  1273. 'Create',
  1274. 'CREATE',
  1275. $table == '*'
  1276. ? __('Allows creating new databases and tables.')
  1277. : __('Allows creating new tables.'),
  1278. ],
  1279. [
  1280. 'Alter',
  1281. 'ALTER',
  1282. __('Allows altering the structure of existing tables.'),
  1283. ],
  1284. [
  1285. 'Index',
  1286. 'INDEX',
  1287. __('Allows creating and dropping indexes.'),
  1288. ],
  1289. [
  1290. 'Drop',
  1291. 'DROP',
  1292. $table == '*'
  1293. ? __('Allows dropping databases and tables.')
  1294. : __('Allows dropping tables.'),
  1295. ],
  1296. [
  1297. 'Create_tmp_table',
  1298. 'CREATE TEMPORARY TABLES',
  1299. __('Allows creating temporary tables.'),
  1300. ],
  1301. [
  1302. 'Show_view',
  1303. 'SHOW VIEW',
  1304. __('Allows performing SHOW CREATE VIEW queries.'),
  1305. ],
  1306. [
  1307. 'Create_routine',
  1308. 'CREATE ROUTINE',
  1309. __('Allows creating stored routines.'),
  1310. ],
  1311. [
  1312. 'Alter_routine',
  1313. 'ALTER ROUTINE',
  1314. __('Allows altering and dropping stored routines.'),
  1315. ],
  1316. [
  1317. 'Execute',
  1318. 'EXECUTE',
  1319. __('Allows executing stored routines.'),
  1320. ],
  1321. ];
  1322. // this one is for a db-specific priv: Create_view_priv
  1323. if (isset($row['Create_view_priv'])) {
  1324. $structure_privTable[] = [
  1325. 'Create_view',
  1326. 'CREATE VIEW',
  1327. __('Allows creating new views.'),
  1328. ];
  1329. }
  1330. // this one is for a table-specific priv: Create View_priv
  1331. if (isset($row['Create View_priv'])) {
  1332. $structure_privTable[] = [
  1333. 'Create View',
  1334. 'CREATE VIEW',
  1335. __('Allows creating new views.'),
  1336. ];
  1337. }
  1338. if (isset($row['Event_priv'])) {
  1339. // MySQL 5.1.6
  1340. $structure_privTable[] = [
  1341. 'Event',
  1342. 'EVENT',
  1343. __('Allows to set up events for the event scheduler.'),
  1344. ];
  1345. $structure_privTable[] = [
  1346. 'Trigger',
  1347. 'TRIGGER',
  1348. __('Allows creating and dropping triggers.'),
  1349. ];
  1350. }
  1351. return $structure_privTable;
  1352. }
  1353. /**
  1354. * Get administration privilege table as an array
  1355. *
  1356. * @param string $db the table
  1357. *
  1358. * @return array administration privilege table
  1359. */
  1360. public function getAdministrationPrivilegeTable($db)
  1361. {
  1362. if ($db == '*') {
  1363. $adminPrivTable = [
  1364. [
  1365. 'Grant',
  1366. 'GRANT',
  1367. __(
  1368. 'Allows adding users and privileges '
  1369. . 'without reloading the privilege tables.'
  1370. ),
  1371. ],
  1372. ];
  1373. $adminPrivTable[] = [
  1374. 'Super',
  1375. 'SUPER',
  1376. __(
  1377. 'Allows connecting, even if maximum number '
  1378. . 'of connections is reached; required for '
  1379. . 'most administrative operations like '
  1380. . 'setting global variables or killing threads of other users.'
  1381. ),
  1382. ];
  1383. $adminPrivTable[] = [
  1384. 'Process',
  1385. 'PROCESS',
  1386. __('Allows viewing processes of all users.'),
  1387. ];
  1388. $adminPrivTable[] = [
  1389. 'Reload',
  1390. 'RELOAD',
  1391. __('Allows reloading server settings and flushing the server\'s caches.'),
  1392. ];
  1393. $adminPrivTable[] = [
  1394. 'Shutdown',
  1395. 'SHUTDOWN',
  1396. __('Allows shutting down the server.'),
  1397. ];
  1398. $adminPrivTable[] = [
  1399. 'Show_db',
  1400. 'SHOW DATABASES',
  1401. __('Gives access to the complete list of databases.'),
  1402. ];
  1403. } else {
  1404. $adminPrivTable = [
  1405. [
  1406. 'Grant',
  1407. 'GRANT',
  1408. __(
  1409. 'Allows user to give to other users or remove from other'
  1410. . ' users the privileges that user possess yourself.'
  1411. ),
  1412. ],
  1413. ];
  1414. }
  1415. $adminPrivTable[] = [
  1416. 'Lock_tables',
  1417. 'LOCK TABLES',
  1418. __('Allows locking tables for the current thread.'),
  1419. ];
  1420. $adminPrivTable[] = [
  1421. 'References',
  1422. 'REFERENCES',
  1423. __('Has no effect in this MySQL version.'),
  1424. ];
  1425. if ($db == '*') {
  1426. $adminPrivTable[] = [
  1427. 'Repl_client',
  1428. 'REPLICATION CLIENT',
  1429. __('Allows the user to ask where the slaves / masters are.'),
  1430. ];
  1431. $adminPrivTable[] = [
  1432. 'Repl_slave',
  1433. 'REPLICATION SLAVE',
  1434. __('Needed for the replication slaves.'),
  1435. ];
  1436. $adminPrivTable[] = [
  1437. 'Create_user',
  1438. 'CREATE USER',
  1439. __('Allows creating, dropping and renaming user accounts.'),
  1440. ];
  1441. }
  1442. return $adminPrivTable;
  1443. }
  1444. /**
  1445. * Get HTML snippet for global privileges table with check boxes
  1446. *
  1447. * @param array $privTable privileges table array
  1448. * @param array $privTableNames names of the privilege tables
  1449. * (Data, Structure, Administration)
  1450. * @param array $row first row from result or boolean false
  1451. *
  1452. * @return string
  1453. */
  1454. public function getHtmlForGlobalPrivTableWithCheckboxes(
  1455. array $privTable,
  1456. array $privTableNames,
  1457. array $row
  1458. ) {
  1459. return $this->template->render('server/privileges/global_priv_table', [
  1460. 'priv_table' => $privTable,
  1461. 'priv_table_names' => $privTableNames,
  1462. 'row' => $row,
  1463. ]);
  1464. }
  1465. /**
  1466. * Gets the currently active authentication plugins
  1467. *
  1468. * @param string $orig_auth_plugin Default Authentication plugin
  1469. * @param string $mode are we creating a new user or are we just
  1470. * changing one?
  1471. * (allowed values: 'new', 'edit', 'change_pw')
  1472. * @param string $versions Is MySQL version newer or older than 5.5.7
  1473. *
  1474. * @return string
  1475. */
  1476. public function getHtmlForAuthPluginsDropdown(
  1477. $orig_auth_plugin,
  1478. $mode = 'new',
  1479. $versions = 'new'
  1480. ) {
  1481. $select_id = 'select_authentication_plugin'
  1482. . ($mode == 'change_pw' ? '_cp' : '');
  1483. if ($versions == 'new') {
  1484. $active_auth_plugins = $this->getActiveAuthPlugins();
  1485. if (isset($active_auth_plugins['mysql_old_password'])) {
  1486. unset($active_auth_plugins['mysql_old_password']);
  1487. }
  1488. } else {
  1489. $active_auth_plugins = [
  1490. 'mysql_native_password' => __('Native MySQL authentication'),
  1491. ];
  1492. }
  1493. $html_output = Util::getDropdown(
  1494. 'authentication_plugin',
  1495. $active_auth_plugins,
  1496. $orig_auth_plugin,
  1497. $select_id
  1498. );
  1499. return $html_output;
  1500. }
  1501. /**
  1502. * Gets the currently active authentication plugins
  1503. *
  1504. * @return array array of plugin names and descriptions
  1505. */
  1506. public function getActiveAuthPlugins()
  1507. {
  1508. $get_plugins_query = "SELECT `PLUGIN_NAME`, `PLUGIN_DESCRIPTION`"
  1509. . " FROM `information_schema`.`PLUGINS` "
  1510. . "WHERE `PLUGIN_TYPE` = 'AUTHENTICATION';";
  1511. $resultset = $this->dbi->query($get_plugins_query);
  1512. $result = [];
  1513. while ($row = $this->dbi->fetchAssoc($resultset)) {
  1514. // if description is known, enable its translation
  1515. if ('mysql_native_password' == $row['PLUGIN_NAME']) {
  1516. $row['PLUGIN_DESCRIPTION'] = __('Native MySQL authentication');
  1517. } elseif ('sha256_password' == $row['PLUGIN_NAME']) {
  1518. $row['PLUGIN_DESCRIPTION'] = __('SHA256 password authentication');
  1519. }
  1520. $result[$row['PLUGIN_NAME']] = $row['PLUGIN_DESCRIPTION'];
  1521. }
  1522. return $result;
  1523. }
  1524. /**
  1525. * Displays the fields used by the "new user" form as well as the
  1526. * "change login information / copy user" form.
  1527. *
  1528. * @param string $mode are we creating a new user or are we just
  1529. * changing one? (allowed values: 'new', 'change')
  1530. * @param string $username User name
  1531. * @param string $hostname Host name
  1532. *
  1533. * @global array $cfg the phpMyAdmin configuration
  1534. * @global resource $user_link the database connection
  1535. *
  1536. * @return string a HTML snippet
  1537. */
  1538. public function getHtmlForLoginInformationFields(
  1539. $mode = 'new',
  1540. $username = null,
  1541. $hostname = null
  1542. ) {
  1543. list($username_length, $hostname_length) = $this->getUsernameAndHostnameLength();
  1544. if (isset($GLOBALS['username']) && strlen($GLOBALS['username']) === 0) {
  1545. $GLOBALS['pred_username'] = 'any';
  1546. }
  1547. $html_output = '<fieldset id="fieldset_add_user_login">' . "\n"
  1548. . '<legend>' . __('Login Information') . '</legend>' . "\n"
  1549. . '<div class="item">' . "\n"
  1550. . '<label for="select_pred_username">' . "\n"
  1551. . ' ' . __('User name:') . "\n"
  1552. . '</label>' . "\n"
  1553. . '<span class="options">' . "\n";
  1554. $html_output .= '<select name="pred_username" id="select_pred_username" '
  1555. . 'title="' . __('User name') . '">' . "\n";
  1556. $html_output .= '<option value="any"'
  1557. . (isset($GLOBALS['pred_username']) && $GLOBALS['pred_username'] == 'any'
  1558. ? ' selected="selected"'
  1559. : '') . '>'
  1560. . __('Any user')
  1561. . '</option>' . "\n";
  1562. $html_output .= '<option value="userdefined"'
  1563. . (! isset($GLOBALS['pred_username'])
  1564. || $GLOBALS['pred_username'] == 'userdefined'
  1565. ? ' selected="selected"'
  1566. : '') . '>'
  1567. . __('Use text field')
  1568. . ':</option>' . "\n";
  1569. $html_output .= '</select>' . "\n"
  1570. . '</span>' . "\n";
  1571. $html_output .= '<input type="text" name="username" id="pma_username" class="autofocus"'
  1572. . ' maxlength="' . $username_length . '" title="' . __('User name') . '"'
  1573. . (empty($GLOBALS['username'])
  1574. ? ''
  1575. : ' value="' . htmlspecialchars(
  1576. isset($GLOBALS['new_username'])
  1577. ? $GLOBALS['new_username']
  1578. : $GLOBALS['username']
  1579. ) . '"'
  1580. )
  1581. . (! isset($GLOBALS['pred_username'])
  1582. || $GLOBALS['pred_username'] == 'userdefined'
  1583. ? 'required="required"'
  1584. : '') . '>' . "\n";
  1585. $html_output .= '<div id="user_exists_warning"'
  1586. . ' name="user_exists_warning" class="hide">'
  1587. . Message::notice(
  1588. __(
  1589. 'An account already exists with the same username '
  1590. . 'but possibly a different hostname.'
  1591. )
  1592. )->getDisplay()
  1593. . '</div>';
  1594. $html_output .= '</div>';
  1595. $html_output .= '<div class="item">' . "\n"
  1596. . '<label for="select_pred_hostname">' . "\n"
  1597. . ' ' . __('Host name:') . "\n"
  1598. . '</label>' . "\n";
  1599. $html_output .= '<span class="options">' . "\n"
  1600. . ' <select name="pred_hostname" id="select_pred_hostname" '
  1601. . 'title="' . __('Host name') . '"' . "\n";
  1602. $_current_user = $this->dbi->fetchValue('SELECT USER();');
  1603. if (! empty($_current_user)) {
  1604. $thishost = str_replace(
  1605. "'",
  1606. '',
  1607. mb_substr(
  1608. $_current_user,
  1609. mb_strrpos($_current_user, '@') + 1
  1610. )
  1611. );
  1612. if ($thishost != 'localhost' && $thishost != '127.0.0.1') {
  1613. $html_output .= ' data-thishost="' . htmlspecialchars($thishost) . '" ';
  1614. } else {
  1615. unset($thishost);
  1616. }
  1617. }
  1618. $html_output .= '>' . "\n";
  1619. unset($_current_user);
  1620. // when we start editing a user, $GLOBALS['pred_hostname'] is not defined
  1621. if (! isset($GLOBALS['pred_hostname']) && isset($GLOBALS['hostname'])) {
  1622. switch (mb_strtolower($GLOBALS['hostname'])) {
  1623. case 'localhost':
  1624. case '127.0.0.1':
  1625. $GLOBALS['pred_hostname'] = 'localhost';
  1626. break;
  1627. case '%':
  1628. $GLOBALS['pred_hostname'] = 'any';
  1629. break;
  1630. default:
  1631. $GLOBALS['pred_hostname'] = 'userdefined';
  1632. break;
  1633. }
  1634. }
  1635. $html_output .= '<option value="any"'
  1636. . (isset($GLOBALS['pred_hostname'])
  1637. && $GLOBALS['pred_hostname'] == 'any'
  1638. ? ' selected="selected"'
  1639. : '') . '>'
  1640. . __('Any host')
  1641. . '</option>' . "\n"
  1642. . '<option value="localhost"'
  1643. . (isset($GLOBALS['pred_hostname'])
  1644. && $GLOBALS['pred_hostname'] == 'localhost'
  1645. ? ' selected="selected"'
  1646. : '') . '>'
  1647. . __('Local')
  1648. . '</option>' . "\n";
  1649. if (! empty($thishost)) {
  1650. $html_output .= '<option value="thishost"'
  1651. . (isset($GLOBALS['pred_hostname'])
  1652. && $GLOBALS['pred_hostname'] == 'thishost'
  1653. ? ' selected="selected"'
  1654. : '') . '>'
  1655. . __('This Host')
  1656. . '</option>' . "\n";
  1657. }
  1658. unset($thishost);
  1659. $html_output .= '<option value="hosttable"'
  1660. . (isset($GLOBALS['pred_hostname'])
  1661. && $GLOBALS['pred_hostname'] == 'hosttable'
  1662. ? ' selected="selected"'
  1663. : '') . '>'
  1664. . __('Use Host Table')
  1665. . '</option>' . "\n";
  1666. $html_output .= '<option value="userdefined"'
  1667. . (isset($GLOBALS['pred_hostname'])
  1668. && $GLOBALS['pred_hostname'] == 'userdefined'
  1669. ? ' selected="selected"'
  1670. : '') . '>'
  1671. . __('Use text field:') . '</option>' . "\n"
  1672. . '</select>' . "\n"
  1673. . '</span>' . "\n";
  1674. $html_output .= '<input type="text" name="hostname" id="pma_hostname" maxlength="'
  1675. . $hostname_length . '" value="'
  1676. // use default value of '%' to match with the default 'Any host'
  1677. . htmlspecialchars(isset($GLOBALS['hostname']) ? $GLOBALS['hostname'] : '%')
  1678. . '" title="' . __('Host name') . '" '
  1679. . (isset($GLOBALS['pred_hostname'])
  1680. && $GLOBALS['pred_hostname'] == 'userdefined'
  1681. ? 'required="required"'
  1682. : '')
  1683. . '>' . "\n"
  1684. . Util::showHint(
  1685. __(
  1686. 'When Host table is used, this field is ignored '
  1687. . 'and values stored in Host table are used instead.'
  1688. )
  1689. )
  1690. . '</div>' . "\n";
  1691. $html_output .= '<div class="item">' . "\n"
  1692. . '<label for="select_pred_password">' . "\n"
  1693. . ' ' . __('Password:') . "\n"
  1694. . '</label>' . "\n"
  1695. . '<span class="options">' . "\n"
  1696. . '<select name="pred_password" id="select_pred_password" title="'
  1697. . __('Password') . '">' . "\n"
  1698. . ($mode == 'change' ? '<option value="keep" selected="selected">'
  1699. . __('Do not change the password')
  1700. . '</option>' . "\n" : '')
  1701. . '<option value="none"';
  1702. if (isset($GLOBALS['username']) && $mode != 'change') {
  1703. $html_output .= ' selected="selected"';
  1704. }
  1705. $html_output .= '>' . __('No Password') . '</option>' . "\n"
  1706. . '<option value="userdefined"'
  1707. . (isset($GLOBALS['username']) ? '' : ' selected="selected"') . '>'
  1708. . __('Use text field')
  1709. . ':</option>' . "\n"
  1710. . '</select>' . "\n"
  1711. . '</span>' . "\n"
  1712. . '<input type="password" id="text_pma_pw" name="pma_pw" '
  1713. . 'title="' . __('Password') . '" '
  1714. . (isset($GLOBALS['username']) ? '' : 'required="required"')
  1715. . '>' . "\n"
  1716. . '<span>Strength:</span> '
  1717. . '<meter max="4" id="password_strength_meter" name="pw_meter"></meter> '
  1718. . '<span id="password_strength" name="pw_strength"></span>' . "\n"
  1719. . '</div>' . "\n";
  1720. $html_output .= '<div class="item" '
  1721. . 'id="div_element_before_generate_password">' . "\n"
  1722. . '<label for="text_pma_pw2">' . "\n"
  1723. . ' ' . __('Re-type:') . "\n"
  1724. . '</label>' . "\n"
  1725. . '<span class="options">&nbsp;</span>' . "\n"
  1726. . '<input type="password" name="pma_pw2" id="text_pma_pw2" '
  1727. . 'title="' . __('Re-type') . '" '
  1728. . (isset($GLOBALS['username']) ? '' : 'required="required"')
  1729. . '>' . "\n"
  1730. . '</div>' . "\n"
  1731. . '<div class="item" id="authentication_plugin_div">'
  1732. . '<label for="select_authentication_plugin" >';
  1733. $serverType = Util::getServerType();
  1734. $serverVersion = $this->dbi->getVersion();
  1735. $orig_auth_plugin = $this->getCurrentAuthenticationPlugin(
  1736. $mode,
  1737. $username,
  1738. $hostname
  1739. );
  1740. if (($serverType == 'MySQL'
  1741. && $serverVersion >= 50507)
  1742. || ($serverType == 'MariaDB'
  1743. && $serverVersion >= 50200)
  1744. ) {
  1745. $html_output .= __('Authentication Plugin')
  1746. . '</label><span class="options">&nbsp;</span>' . "\n";
  1747. $auth_plugin_dropdown = $this->getHtmlForAuthPluginsDropdown(
  1748. $orig_auth_plugin,
  1749. $mode,
  1750. 'new'
  1751. );
  1752. } else {
  1753. $html_output .= __('Password Hashing Method')
  1754. . '</label><span class="options">&nbsp;</span>' . "\n";
  1755. $auth_plugin_dropdown = $this->getHtmlForAuthPluginsDropdown(
  1756. $orig_auth_plugin,
  1757. $mode,
  1758. 'old'
  1759. );
  1760. }
  1761. $html_output .= $auth_plugin_dropdown;
  1762. $html_output .= '<div'
  1763. . ($orig_auth_plugin != 'sha256_password' ? ' class="hide"' : '')
  1764. . ' id="ssl_reqd_warning">'
  1765. . Message::notice(
  1766. __(
  1767. 'This method requires using an \'<i>SSL connection</i>\' '
  1768. . 'or an \'<i>unencrypted connection that encrypts the password '
  1769. . 'using RSA</i>\'; while connecting to the server.'
  1770. )
  1771. . Util::showMySQLDocu('sha256-authentication-plugin')
  1772. )
  1773. ->getDisplay()
  1774. . '</div>';
  1775. $html_output .= '</div>' . "\n"
  1776. // Generate password added here via jQuery
  1777. . '</fieldset>' . "\n";
  1778. return $html_output;
  1779. }
  1780. /**
  1781. * Get username and hostname length
  1782. *
  1783. * @return array username length and hostname length
  1784. */
  1785. public function getUsernameAndHostnameLength()
  1786. {
  1787. /* Fallback values */
  1788. $username_length = 16;
  1789. $hostname_length = 41;
  1790. /* Try to get real lengths from the database */
  1791. $fields_info = $this->dbi->fetchResult(
  1792. 'SELECT COLUMN_NAME, CHARACTER_MAXIMUM_LENGTH '
  1793. . 'FROM information_schema.columns '
  1794. . "WHERE table_schema = 'mysql' AND table_name = 'user' "
  1795. . "AND COLUMN_NAME IN ('User', 'Host')"
  1796. );
  1797. foreach ($fields_info as $val) {
  1798. if ($val['COLUMN_NAME'] == 'User') {
  1799. $username_length = $val['CHARACTER_MAXIMUM_LENGTH'];
  1800. } elseif ($val['COLUMN_NAME'] == 'Host') {
  1801. $hostname_length = $val['CHARACTER_MAXIMUM_LENGTH'];
  1802. }
  1803. }
  1804. return [
  1805. $username_length,
  1806. $hostname_length,
  1807. ];
  1808. }
  1809. /**
  1810. * Get current authentication plugin in use - for a user or globally
  1811. *
  1812. * @param string $mode are we creating a new user or are we just
  1813. * changing one? (allowed values: 'new', 'change')
  1814. * @param string $username User name
  1815. * @param string $hostname Host name
  1816. *
  1817. * @return string authentication plugin in use
  1818. */
  1819. public function getCurrentAuthenticationPlugin(
  1820. $mode = 'new',
  1821. $username = null,
  1822. $hostname = null
  1823. ) {
  1824. /* Fallback (standard) value */
  1825. $authentication_plugin = 'mysql_native_password';
  1826. $serverVersion = $this->dbi->getVersion();
  1827. if (isset($username) && isset($hostname)
  1828. && $mode == 'change'
  1829. ) {
  1830. $row = $this->dbi->fetchSingleRow(
  1831. 'SELECT `plugin` FROM `mysql`.`user` WHERE `User` = "'
  1832. . $GLOBALS['dbi']->escapeString($username)
  1833. . '" AND `Host` = "'
  1834. . $GLOBALS['dbi']->escapeString($hostname)
  1835. . '" LIMIT 1'
  1836. );
  1837. // Table 'mysql'.'user' may not exist for some previous
  1838. // versions of MySQL - in that case consider fallback value
  1839. if (is_array($row) && isset($row['plugin'])) {
  1840. $authentication_plugin = $row['plugin'];
  1841. }
  1842. } elseif ($mode == 'change') {
  1843. list($username, $hostname) = $this->dbi->getCurrentUserAndHost();
  1844. $row = $this->dbi->fetchSingleRow(
  1845. 'SELECT `plugin` FROM `mysql`.`user` WHERE `User` = "'
  1846. . $GLOBALS['dbi']->escapeString($username)
  1847. . '" AND `Host` = "'
  1848. . $GLOBALS['dbi']->escapeString($hostname)
  1849. . '"'
  1850. );
  1851. if (is_array($row) && isset($row['plugin'])) {
  1852. $authentication_plugin = $row['plugin'];
  1853. }
  1854. } elseif ($serverVersion >= 50702) {
  1855. $row = $this->dbi->fetchSingleRow(
  1856. 'SELECT @@default_authentication_plugin'
  1857. );
  1858. $authentication_plugin = is_array($row) ? $row['@@default_authentication_plugin'] : null;
  1859. }
  1860. return $authentication_plugin;
  1861. }
  1862. /**
  1863. * Returns all the grants for a certain user on a certain host
  1864. * Used in the export privileges for all users section
  1865. *
  1866. * @param string $user User name
  1867. * @param string $host Host name
  1868. *
  1869. * @return string containing all the grants text
  1870. */
  1871. public function getGrants($user, $host)
  1872. {
  1873. $grants = $this->dbi->fetchResult(
  1874. "SHOW GRANTS FOR '"
  1875. . $this->dbi->escapeString($user) . "'@'"
  1876. . $this->dbi->escapeString($host) . "'"
  1877. );
  1878. $response = '';
  1879. foreach ($grants as $one_grant) {
  1880. $response .= $one_grant . ";\n\n";
  1881. }
  1882. return $response;
  1883. }
  1884. /**
  1885. * Update password and get message for password updating
  1886. *
  1887. * @param string $err_url error url
  1888. * @param string $username username
  1889. * @param string $hostname hostname
  1890. *
  1891. * @return Message success or error message after updating password
  1892. */
  1893. public function updatePassword($err_url, $username, $hostname)
  1894. {
  1895. // similar logic in user_password.php
  1896. $message = null;
  1897. if (empty($_POST['nopass'])
  1898. && isset($_POST['pma_pw'])
  1899. && isset($_POST['pma_pw2'])
  1900. ) {
  1901. if ($_POST['pma_pw'] != $_POST['pma_pw2']) {
  1902. $message = Message::error(__('The passwords aren\'t the same!'));
  1903. } elseif (empty($_POST['pma_pw']) || empty($_POST['pma_pw2'])) {
  1904. $message = Message::error(__('The password is empty!'));
  1905. }
  1906. }
  1907. // here $nopass could be == 1
  1908. if ($message === null) {
  1909. $hashing_function = 'PASSWORD';
  1910. $serverType = Util::getServerType();
  1911. $serverVersion = $this->dbi->getVersion();
  1912. $authentication_plugin
  1913. = (isset($_POST['authentication_plugin'])
  1914. ? $_POST['authentication_plugin']
  1915. : $this->getCurrentAuthenticationPlugin(
  1916. 'change',
  1917. $username,
  1918. $hostname
  1919. ));
  1920. // Use 'ALTER USER ...' syntax for MySQL 5.7.6+
  1921. if ($serverType == 'MySQL'
  1922. && $serverVersion >= 50706
  1923. ) {
  1924. if ($authentication_plugin != 'mysql_old_password') {
  1925. $query_prefix = "ALTER USER '"
  1926. . $this->dbi->escapeString($username)
  1927. . "'@'" . $this->dbi->escapeString($hostname) . "'"
  1928. . " IDENTIFIED WITH "
  1929. . $authentication_plugin
  1930. . " BY '";
  1931. } else {
  1932. $query_prefix = "ALTER USER '"
  1933. . $this->dbi->escapeString($username)
  1934. . "'@'" . $this->dbi->escapeString($hostname) . "'"
  1935. . " IDENTIFIED BY '";
  1936. }
  1937. // in $sql_query which will be displayed, hide the password
  1938. $sql_query = $query_prefix . "*'";
  1939. $local_query = $query_prefix
  1940. . $this->dbi->escapeString($_POST['pma_pw']) . "'";
  1941. } elseif ($serverType == 'MariaDB' && $serverVersion >= 10000) {
  1942. // MariaDB uses "SET PASSWORD" syntax to change user password.
  1943. // On Galera cluster only DDL queries are replicated, since
  1944. // users are stored in MyISAM storage engine.
  1945. $query_prefix = "SET PASSWORD FOR '"
  1946. . $this->dbi->escapeString($username)
  1947. . "'@'" . $this->dbi->escapeString($hostname) . "'"
  1948. . " = PASSWORD ('";
  1949. $sql_query = $local_query = $query_prefix
  1950. . $this->dbi->escapeString($_POST['pma_pw']) . "')";
  1951. } elseif ($serverType == 'MariaDB'
  1952. && $serverVersion >= 50200
  1953. && $this->dbi->isSuperuser()
  1954. ) {
  1955. // Use 'UPDATE `mysql`.`user` ...' Syntax for MariaDB 5.2+
  1956. if ($authentication_plugin == 'mysql_native_password') {
  1957. // Set the hashing method used by PASSWORD()
  1958. // to be 'mysql_native_password' type
  1959. $this->dbi->tryQuery('SET old_passwords = 0;');
  1960. } elseif ($authentication_plugin == 'sha256_password') {
  1961. // Set the hashing method used by PASSWORD()
  1962. // to be 'sha256_password' type
  1963. $this->dbi->tryQuery('SET `old_passwords` = 2;');
  1964. }
  1965. $hashedPassword = $this->getHashedPassword($_POST['pma_pw']);
  1966. $sql_query = 'SET PASSWORD FOR \''
  1967. . $this->dbi->escapeString($username)
  1968. . '\'@\'' . $this->dbi->escapeString($hostname) . '\' = '
  1969. . ($_POST['pma_pw'] == ''
  1970. ? '\'\''
  1971. : $hashing_function . '(\''
  1972. . preg_replace('@.@s', '*', $_POST['pma_pw']) . '\')');
  1973. $local_query = "UPDATE `mysql`.`user` SET "
  1974. . " `authentication_string` = '" . $hashedPassword
  1975. . "', `Password` = '', "
  1976. . " `plugin` = '" . $authentication_plugin . "'"
  1977. . " WHERE `User` = '" . $GLOBALS['dbi']->escapeString($username)
  1978. . "' AND Host = '" . $GLOBALS['dbi']->escapeString($hostname) . "';";
  1979. } else {
  1980. // USE 'SET PASSWORD ...' syntax for rest of the versions
  1981. // Backup the old value, to be reset later
  1982. $row = $this->dbi->fetchSingleRow(
  1983. 'SELECT @@old_passwords;'
  1984. );
  1985. $orig_value = $row['@@old_passwords'];
  1986. $update_plugin_query = "UPDATE `mysql`.`user` SET"
  1987. . " `plugin` = '" . $authentication_plugin . "'"
  1988. . " WHERE `User` = '" . $GLOBALS['dbi']->escapeString($username)
  1989. . "' AND Host = '" . $GLOBALS['dbi']->escapeString($hostname) . "';";
  1990. // Update the plugin for the user
  1991. if (! $this->dbi->tryQuery($update_plugin_query)) {
  1992. Util::mysqlDie(
  1993. $this->dbi->getError(),
  1994. $update_plugin_query,
  1995. false,
  1996. $err_url
  1997. );
  1998. }
  1999. $this->dbi->tryQuery("FLUSH PRIVILEGES;");
  2000. if ($authentication_plugin == 'mysql_native_password') {
  2001. // Set the hashing method used by PASSWORD()
  2002. // to be 'mysql_native_password' type
  2003. $this->dbi->tryQuery('SET old_passwords = 0;');
  2004. } elseif ($authentication_plugin == 'sha256_password') {
  2005. // Set the hashing method used by PASSWORD()
  2006. // to be 'sha256_password' type
  2007. $this->dbi->tryQuery('SET `old_passwords` = 2;');
  2008. }
  2009. $sql_query = 'SET PASSWORD FOR \''
  2010. . $this->dbi->escapeString($username)
  2011. . '\'@\'' . $this->dbi->escapeString($hostname) . '\' = '
  2012. . ($_POST['pma_pw'] == ''
  2013. ? '\'\''
  2014. : $hashing_function . '(\''
  2015. . preg_replace('@.@s', '*', $_POST['pma_pw']) . '\')');
  2016. $local_query = 'SET PASSWORD FOR \''
  2017. . $this->dbi->escapeString($username)
  2018. . '\'@\'' . $this->dbi->escapeString($hostname) . '\' = '
  2019. . ($_POST['pma_pw'] == '' ? '\'\'' : $hashing_function
  2020. . '(\'' . $this->dbi->escapeString($_POST['pma_pw']) . '\')');
  2021. }
  2022. if (! $this->dbi->tryQuery($local_query)) {
  2023. Util::mysqlDie(
  2024. $this->dbi->getError(),
  2025. $sql_query,
  2026. false,
  2027. $err_url
  2028. );
  2029. }
  2030. // Flush privileges after successful password change
  2031. $this->dbi->tryQuery("FLUSH PRIVILEGES;");
  2032. $message = Message::success(
  2033. __('The password for %s was changed successfully.')
  2034. );
  2035. $message->addParam('\'' . $username . '\'@\'' . $hostname . '\'');
  2036. if (isset($orig_value)) {
  2037. $this->dbi->tryQuery(
  2038. 'SET `old_passwords` = ' . $orig_value . ';'
  2039. );
  2040. }
  2041. }
  2042. return $message;
  2043. }
  2044. /**
  2045. * Revokes privileges and get message and SQL query for privileges revokes
  2046. *
  2047. * @param string $dbname database name
  2048. * @param string $tablename table name
  2049. * @param string $username username
  2050. * @param string $hostname host name
  2051. * @param string $itemType item type
  2052. *
  2053. * @return array ($message, $sql_query)
  2054. */
  2055. public function getMessageAndSqlQueryForPrivilegesRevoke(
  2056. $dbname,
  2057. $tablename,
  2058. $username,
  2059. $hostname,
  2060. $itemType
  2061. ) {
  2062. $db_and_table = $this->wildcardEscapeForGrant($dbname, $tablename);
  2063. $sql_query0 = 'REVOKE ALL PRIVILEGES ON ' . $itemType . ' ' . $db_and_table
  2064. . ' FROM \''
  2065. . $this->dbi->escapeString($username) . '\'@\''
  2066. . $this->dbi->escapeString($hostname) . '\';';
  2067. $sql_query1 = 'REVOKE GRANT OPTION ON ' . $itemType . ' ' . $db_and_table
  2068. . ' FROM \'' . $this->dbi->escapeString($username) . '\'@\''
  2069. . $this->dbi->escapeString($hostname) . '\';';
  2070. $this->dbi->query($sql_query0);
  2071. if (! $this->dbi->tryQuery($sql_query1)) {
  2072. // this one may fail, too...
  2073. $sql_query1 = '';
  2074. }
  2075. $sql_query = $sql_query0 . ' ' . $sql_query1;
  2076. $message = Message::success(
  2077. __('You have revoked the privileges for %s.')
  2078. );
  2079. $message->addParam('\'' . $username . '\'@\'' . $hostname . '\'');
  2080. return [
  2081. $message,
  2082. $sql_query,
  2083. ];
  2084. }
  2085. /**
  2086. * Get REQUIRE cluase
  2087. *
  2088. * @return string REQUIRE clause
  2089. */
  2090. public function getRequireClause()
  2091. {
  2092. $arr = isset($_POST['ssl_type']) ? $_POST : $GLOBALS;
  2093. if (isset($arr['ssl_type']) && $arr['ssl_type'] == 'SPECIFIED') {
  2094. $require = [];
  2095. if (! empty($arr['ssl_cipher'])) {
  2096. $require[] = "CIPHER '"
  2097. . $this->dbi->escapeString($arr['ssl_cipher']) . "'";
  2098. }
  2099. if (! empty($arr['x509_issuer'])) {
  2100. $require[] = "ISSUER '"
  2101. . $this->dbi->escapeString($arr['x509_issuer']) . "'";
  2102. }
  2103. if (! empty($arr['x509_subject'])) {
  2104. $require[] = "SUBJECT '"
  2105. . $this->dbi->escapeString($arr['x509_subject']) . "'";
  2106. }
  2107. if (count($require)) {
  2108. $require_clause = " REQUIRE " . implode(" AND ", $require);
  2109. } else {
  2110. $require_clause = " REQUIRE NONE";
  2111. }
  2112. } elseif (isset($arr['ssl_type']) && $arr['ssl_type'] == 'X509') {
  2113. $require_clause = " REQUIRE X509";
  2114. } elseif (isset($arr['ssl_type']) && $arr['ssl_type'] == 'ANY') {
  2115. $require_clause = " REQUIRE SSL";
  2116. } else {
  2117. $require_clause = " REQUIRE NONE";
  2118. }
  2119. return $require_clause;
  2120. }
  2121. /**
  2122. * Get a WITH clause for 'update privileges' and 'add user'
  2123. *
  2124. * @return string
  2125. */
  2126. public function getWithClauseForAddUserAndUpdatePrivs()
  2127. {
  2128. $sql_query = '';
  2129. if (((isset($_POST['Grant_priv']) && $_POST['Grant_priv'] == 'Y')
  2130. || (isset($GLOBALS['Grant_priv']) && $GLOBALS['Grant_priv'] == 'Y'))
  2131. && ! ((Util::getServerType() == 'MySQL' || Util::getServerType() == 'Percona Server')
  2132. && $this->dbi->getVersion() >= 80011)
  2133. ) {
  2134. $sql_query .= ' GRANT OPTION';
  2135. }
  2136. if (isset($_POST['max_questions']) || isset($GLOBALS['max_questions'])) {
  2137. $max_questions = isset($_POST['max_questions'])
  2138. ? (int) $_POST['max_questions'] : (int) $GLOBALS['max_questions'];
  2139. $max_questions = max(0, $max_questions);
  2140. $sql_query .= ' MAX_QUERIES_PER_HOUR ' . $max_questions;
  2141. }
  2142. if (isset($_POST['max_connections']) || isset($GLOBALS['max_connections'])) {
  2143. $max_connections = isset($_POST['max_connections'])
  2144. ? (int) $_POST['max_connections'] : (int) $GLOBALS['max_connections'];
  2145. $max_connections = max(0, $max_connections);
  2146. $sql_query .= ' MAX_CONNECTIONS_PER_HOUR ' . $max_connections;
  2147. }
  2148. if (isset($_POST['max_updates']) || isset($GLOBALS['max_updates'])) {
  2149. $max_updates = isset($_POST['max_updates'])
  2150. ? (int) $_POST['max_updates'] : (int) $GLOBALS['max_updates'];
  2151. $max_updates = max(0, $max_updates);
  2152. $sql_query .= ' MAX_UPDATES_PER_HOUR ' . $max_updates;
  2153. }
  2154. if (isset($_POST['max_user_connections'])
  2155. || isset($GLOBALS['max_user_connections'])
  2156. ) {
  2157. $max_user_connections = isset($_POST['max_user_connections'])
  2158. ? (int) $_POST['max_user_connections']
  2159. : (int) $GLOBALS['max_user_connections'];
  2160. $max_user_connections = max(0, $max_user_connections);
  2161. $sql_query .= ' MAX_USER_CONNECTIONS ' . $max_user_connections;
  2162. }
  2163. return (! empty($sql_query) ? ' WITH' . $sql_query : '');
  2164. }
  2165. /**
  2166. * Get HTML for addUsersForm, This function call if isset($_GET['adduser'])
  2167. *
  2168. * @param string $dbname database name
  2169. *
  2170. * @return string HTML for addUserForm
  2171. */
  2172. public function getHtmlForAddUser($dbname)
  2173. {
  2174. $html_output = '<h2>' . "\n"
  2175. . Util::getIcon('b_usradd') . __('Add user account') . "\n"
  2176. . '</h2>' . "\n"
  2177. . '<form name="usersForm" id="addUsersForm"'
  2178. . ' onsubmit="return checkAddUser(this);"'
  2179. . ' action="server_privileges.php" method="post" autocomplete="off" >' . "\n"
  2180. . Url::getHiddenInputs('', '')
  2181. . $this->getHtmlForLoginInformationFields('new');
  2182. $html_output .= '<fieldset id="fieldset_add_user_database">' . "\n"
  2183. . '<legend>' . __('Database for user account') . '</legend>' . "\n";
  2184. $html_output .= $this->template->render('checkbox', [
  2185. 'html_field_name' => 'createdb-1',
  2186. 'label' => __('Create database with same name and grant all privileges.'),
  2187. 'checked' => false,
  2188. 'onclick' => false,
  2189. 'html_field_id' => 'createdb-1',
  2190. ]);
  2191. $html_output .= '<br>' . "\n";
  2192. $html_output .= $this->template->render('checkbox', [
  2193. 'html_field_name' => 'createdb-2',
  2194. 'label' => __('Grant all privileges on wildcard name (username\\_%).'),
  2195. 'checked' => false,
  2196. 'onclick' => false,
  2197. 'html_field_id' => 'createdb-2',
  2198. ]);
  2199. $html_output .= '<br>' . "\n";
  2200. if (! empty($dbname)) {
  2201. $html_output .= $this->template->render('checkbox', [
  2202. 'html_field_name' => 'createdb-3',
  2203. 'label' => sprintf(__('Grant all privileges on database %s.'), htmlspecialchars($dbname)),
  2204. 'checked' => true,
  2205. 'onclick' => false,
  2206. 'html_field_id' => 'createdb-3',
  2207. ]);
  2208. $html_output .= '<input type="hidden" name="dbname" value="'
  2209. . htmlspecialchars($dbname) . '">' . "\n";
  2210. $html_output .= '<br>' . "\n";
  2211. }
  2212. $html_output .= '</fieldset>' . "\n";
  2213. if ($GLOBALS['is_grantuser']) {
  2214. $html_output .= $this->getHtmlToDisplayPrivilegesTable('*', '*', false);
  2215. }
  2216. $html_output .= '<fieldset id="fieldset_add_user_footer" class="tblFooters">'
  2217. . "\n"
  2218. . '<input type="hidden" name="adduser_submit" value="1">' . "\n"
  2219. . '<input class="btn btn-primary" type="submit" id="adduser_submit" value="' . __('Go') . '">'
  2220. . "\n"
  2221. . '</fieldset>' . "\n"
  2222. . '</form>' . "\n";
  2223. return $html_output;
  2224. }
  2225. /**
  2226. * Get the list of privileges and list of compared privileges as strings
  2227. * and return a array that contains both strings
  2228. *
  2229. * @return array $list_of_privileges, $list_of_compared_privileges
  2230. */
  2231. public function getListOfPrivilegesAndComparedPrivileges()
  2232. {
  2233. $list_of_privileges
  2234. = '`User`, '
  2235. . '`Host`, '
  2236. . '`Select_priv`, '
  2237. . '`Insert_priv`, '
  2238. . '`Update_priv`, '
  2239. . '`Delete_priv`, '
  2240. . '`Create_priv`, '
  2241. . '`Drop_priv`, '
  2242. . '`Grant_priv`, '
  2243. . '`Index_priv`, '
  2244. . '`Alter_priv`, '
  2245. . '`References_priv`, '
  2246. . '`Create_tmp_table_priv`, '
  2247. . '`Lock_tables_priv`, '
  2248. . '`Create_view_priv`, '
  2249. . '`Show_view_priv`, '
  2250. . '`Create_routine_priv`, '
  2251. . '`Alter_routine_priv`, '
  2252. . '`Execute_priv`';
  2253. $listOfComparedPrivs
  2254. = '`Select_priv` = \'N\''
  2255. . ' AND `Insert_priv` = \'N\''
  2256. . ' AND `Update_priv` = \'N\''
  2257. . ' AND `Delete_priv` = \'N\''
  2258. . ' AND `Create_priv` = \'N\''
  2259. . ' AND `Drop_priv` = \'N\''
  2260. . ' AND `Grant_priv` = \'N\''
  2261. . ' AND `References_priv` = \'N\''
  2262. . ' AND `Create_tmp_table_priv` = \'N\''
  2263. . ' AND `Lock_tables_priv` = \'N\''
  2264. . ' AND `Create_view_priv` = \'N\''
  2265. . ' AND `Show_view_priv` = \'N\''
  2266. . ' AND `Create_routine_priv` = \'N\''
  2267. . ' AND `Alter_routine_priv` = \'N\''
  2268. . ' AND `Execute_priv` = \'N\'';
  2269. $list_of_privileges .=
  2270. ', `Event_priv`, '
  2271. . '`Trigger_priv`';
  2272. $listOfComparedPrivs .=
  2273. ' AND `Event_priv` = \'N\''
  2274. . ' AND `Trigger_priv` = \'N\'';
  2275. return [
  2276. $list_of_privileges,
  2277. $listOfComparedPrivs,
  2278. ];
  2279. }
  2280. /**
  2281. * Get the HTML for routine based privileges
  2282. *
  2283. * @param string $db database name
  2284. * @param string $index_checkbox starting index for rows to be added
  2285. *
  2286. * @return string
  2287. */
  2288. public function getHtmlTableBodyForSpecificDbRoutinePrivs($db, $index_checkbox)
  2289. {
  2290. $sql_query = 'SELECT * FROM `mysql`.`procs_priv` WHERE Db = \'' . $this->dbi->escapeString($db) . '\';';
  2291. $res = $this->dbi->query($sql_query);
  2292. $html_output = '';
  2293. while ($row = $this->dbi->fetchAssoc($res)) {
  2294. $html_output .= '<tr>';
  2295. $html_output .= '<td';
  2296. $value = htmlspecialchars($row['User'] . '&amp;#27;' . $row['Host']);
  2297. $html_output .= '>';
  2298. $html_output .= '<input type="checkbox" class="checkall" '
  2299. . 'name="selected_usr[]" '
  2300. . 'id="checkbox_sel_users_' . ($index_checkbox++) . '" '
  2301. . 'value="' . $value . '"></td>';
  2302. $html_output .= '<td>' . htmlspecialchars($row['User'])
  2303. . '</td>'
  2304. . '<td>' . htmlspecialchars($row['Host'])
  2305. . '</td>'
  2306. . '<td>routine'
  2307. . '</td>'
  2308. . '<td><code>' . htmlspecialchars($row['Routine_name']) . '</code>'
  2309. . '</td>'
  2310. . '<td>Yes'
  2311. . '</td>';
  2312. $current_user = $row['User'];
  2313. $current_host = $row['Host'];
  2314. $routine = $row['Routine_name'];
  2315. $html_output .= '<td>';
  2316. $specific_db = '';
  2317. $specific_table = '';
  2318. if ($GLOBALS['is_grantuser']) {
  2319. $specific_db = isset($row['Db']) && $row['Db'] != '*'
  2320. ? $row['Db'] : '';
  2321. $specific_table = isset($row['Table_name'])
  2322. && $row['Table_name'] != '*'
  2323. ? $row['Table_name'] : '';
  2324. $html_output .= $this->getUserLink(
  2325. 'edit',
  2326. $current_user,
  2327. $current_host,
  2328. $specific_db,
  2329. $specific_table,
  2330. $routine
  2331. );
  2332. }
  2333. $html_output .= '</td>';
  2334. $html_output .= '<td>';
  2335. $html_output .= $this->getUserLink(
  2336. 'export',
  2337. $current_user,
  2338. $current_host,
  2339. $specific_db,
  2340. $specific_table,
  2341. $routine
  2342. );
  2343. $html_output .= '</td>';
  2344. $html_output .= '</tr>';
  2345. }
  2346. return $html_output;
  2347. }
  2348. /**
  2349. * Get the HTML for user form and check the privileges for a particular database.
  2350. *
  2351. * @param string $db database name
  2352. *
  2353. * @return string
  2354. */
  2355. public function getHtmlForSpecificDbPrivileges($db)
  2356. {
  2357. $html_output = '';
  2358. if ($this->dbi->isSuperuser()) {
  2359. // check the privileges for a particular database.
  2360. $html_output = '<form id="usersForm" action="server_privileges.php">';
  2361. $html_output .= Url::getHiddenInputs($db);
  2362. $html_output .= '<div class="width100">';
  2363. $html_output .= '<fieldset>';
  2364. $html_output .= '<legend>' . "\n"
  2365. . Util::getIcon('b_usrcheck')
  2366. . ' '
  2367. . sprintf(
  2368. __('Users having access to "%s"'),
  2369. '<a href="' . Util::getScriptNameForOption(
  2370. $GLOBALS['cfg']['DefaultTabDatabase'],
  2371. 'database'
  2372. )
  2373. . Url::getCommon(['db' => $db]) . '">'
  2374. . htmlspecialchars($db)
  2375. . '</a>'
  2376. )
  2377. . "\n"
  2378. . '</legend>' . "\n";
  2379. $html_output .= '<div class="responsivetable jsresponsive">';
  2380. $html_output .= '<table id="dbspecificuserrights" class="data">';
  2381. $html_output .= $this->getHtmlForPrivsTableHead();
  2382. $privMap = $this->getPrivMap($db);
  2383. $html_output .= $this->getHtmlTableBodyForSpecificDbOrTablePrivs($privMap, $db);
  2384. $html_output .= '</table>';
  2385. $html_output .= '</div>';
  2386. $html_output .= '<div class="floatleft">';
  2387. $html_output .= $this->template->render('select_all', [
  2388. 'pma_theme_image' => $GLOBALS['pmaThemeImage'],
  2389. 'text_dir' => $GLOBALS['text_dir'],
  2390. 'form_name' => "usersForm",
  2391. ]);
  2392. $html_output .= Util::getButtonOrImage(
  2393. 'submit_mult',
  2394. 'mult_submit',
  2395. __('Export'),
  2396. 'b_tblexport',
  2397. 'export'
  2398. );
  2399. $html_output .= '</fieldset>';
  2400. $html_output .= '</div>';
  2401. $html_output .= '</form>';
  2402. } else {
  2403. $html_output .= $this->getHtmlForViewUsersError();
  2404. }
  2405. $response = Response::getInstance();
  2406. if ($response->isAjax() === true
  2407. && empty($_REQUEST['ajax_page_request'])
  2408. ) {
  2409. $message = Message::success(__('User has been added.'));
  2410. $response->addJSON('message', $message);
  2411. $response->addJSON('user_form', $html_output);
  2412. exit;
  2413. } else {
  2414. // Offer to create a new user for the current database
  2415. $html_output .= $this->getAddUserHtmlFieldset($db);
  2416. }
  2417. return $html_output;
  2418. }
  2419. /**
  2420. * Get the HTML for user form and check the privileges for a particular table.
  2421. *
  2422. * @param string $db database name
  2423. * @param string $table table name
  2424. *
  2425. * @return string
  2426. */
  2427. public function getHtmlForSpecificTablePrivileges($db, $table)
  2428. {
  2429. $html_output = '';
  2430. if ($this->dbi->isSuperuser()) {
  2431. // check the privileges for a particular table.
  2432. $html_output = '<form id="usersForm" action="server_privileges.php">';
  2433. $html_output .= Url::getHiddenInputs($db, $table);
  2434. $html_output .= '<fieldset>';
  2435. $html_output .= '<legend>'
  2436. . Util::getIcon('b_usrcheck')
  2437. . sprintf(
  2438. __('Users having access to "%s"'),
  2439. '<a href="' . Util::getScriptNameForOption(
  2440. $GLOBALS['cfg']['DefaultTabTable'],
  2441. 'table'
  2442. )
  2443. . Url::getCommon(
  2444. [
  2445. 'db' => $db,
  2446. 'table' => $table,
  2447. ]
  2448. ) . '">'
  2449. . htmlspecialchars($db) . '.' . htmlspecialchars($table)
  2450. . '</a>'
  2451. )
  2452. . '</legend>';
  2453. $html_output .= '<div class="responsivetable jsresponsive">';
  2454. $html_output .= '<table id="tablespecificuserrights" class="data">';
  2455. $html_output .= $this->getHtmlForPrivsTableHead();
  2456. $privMap = $this->getPrivMap($db);
  2457. $sql_query = "SELECT `User`, `Host`, `Db`,"
  2458. . " 't' AS `Type`, `Table_name`, `Table_priv`"
  2459. . " FROM `mysql`.`tables_priv`"
  2460. . " WHERE '" . $this->dbi->escapeString($db) . "' LIKE `Db`"
  2461. . " AND '" . $this->dbi->escapeString($table) . "' LIKE `Table_name`"
  2462. . " AND NOT (`Table_priv` = '' AND Column_priv = '')"
  2463. . " ORDER BY `User` ASC, `Host` ASC, `Db` ASC, `Table_priv` ASC;";
  2464. $res = $this->dbi->query($sql_query);
  2465. $this->mergePrivMapFromResult($privMap, $res);
  2466. $html_output .= $this->getHtmlTableBodyForSpecificDbOrTablePrivs($privMap, $db);
  2467. $html_output .= '</table></div>';
  2468. $html_output .= '<div class="floatleft">';
  2469. $html_output .= $this->template->render('select_all', [
  2470. 'pma_theme_image' => $GLOBALS['pmaThemeImage'],
  2471. 'text_dir' => $GLOBALS['text_dir'],
  2472. 'form_name' => "usersForm",
  2473. ]);
  2474. $html_output .= Util::getButtonOrImage(
  2475. 'submit_mult',
  2476. 'mult_submit',
  2477. __('Export'),
  2478. 'b_tblexport',
  2479. 'export'
  2480. );
  2481. $html_output .= '</fieldset>';
  2482. $html_output .= '</form>';
  2483. } else {
  2484. $html_output .= $this->getHtmlForViewUsersError();
  2485. }
  2486. // Offer to create a new user for the current database
  2487. $html_output .= $this->getAddUserHtmlFieldset($db, $table);
  2488. return $html_output;
  2489. }
  2490. /**
  2491. * gets privilege map
  2492. *
  2493. * @param string $db the database
  2494. *
  2495. * @return array the privilege map
  2496. */
  2497. public function getPrivMap($db)
  2498. {
  2499. list($listOfPrivs, $listOfComparedPrivs)
  2500. = $this->getListOfPrivilegesAndComparedPrivileges();
  2501. $sql_query
  2502. = "("
  2503. . " SELECT " . $listOfPrivs . ", '*' AS `Db`, 'g' AS `Type`"
  2504. . " FROM `mysql`.`user`"
  2505. . " WHERE NOT (" . $listOfComparedPrivs . ")"
  2506. . ")"
  2507. . " UNION "
  2508. . "("
  2509. . " SELECT " . $listOfPrivs . ", `Db`, 'd' AS `Type`"
  2510. . " FROM `mysql`.`db`"
  2511. . " WHERE '" . $this->dbi->escapeString($db) . "' LIKE `Db`"
  2512. . " AND NOT (" . $listOfComparedPrivs . ")"
  2513. . ")"
  2514. . " ORDER BY `User` ASC, `Host` ASC, `Db` ASC;";
  2515. $res = $this->dbi->query($sql_query);
  2516. $privMap = [];
  2517. $this->mergePrivMapFromResult($privMap, $res);
  2518. return $privMap;
  2519. }
  2520. /**
  2521. * merge privilege map and rows from resultset
  2522. *
  2523. * @param array $privMap the privilege map reference
  2524. * @param object $result the resultset of query
  2525. *
  2526. * @return void
  2527. */
  2528. public function mergePrivMapFromResult(array &$privMap, $result)
  2529. {
  2530. while ($row = $this->dbi->fetchAssoc($result)) {
  2531. $user = (string) $row['User'];
  2532. $host = (string) $row['Host'];
  2533. if (! isset($privMap[$user])) {
  2534. $privMap[$user] = [];
  2535. }
  2536. if (! isset($privMap[$user][$host])) {
  2537. $privMap[$user][$host] = [];
  2538. }
  2539. $privMap[$user][$host][] = $row;
  2540. }
  2541. }
  2542. /**
  2543. * Get HTML snippet for privileges table head
  2544. *
  2545. * @return string
  2546. */
  2547. public function getHtmlForPrivsTableHead()
  2548. {
  2549. return '<thead>'
  2550. . '<tr>'
  2551. . '<th></th>'
  2552. . '<th>' . __('User name') . '</th>'
  2553. . '<th>' . __('Host name') . '</th>'
  2554. . '<th>' . __('Type') . '</th>'
  2555. . '<th>' . __('Privileges') . '</th>'
  2556. . '<th>' . __('Grant') . '</th>'
  2557. . '<th colspan="2">' . __('Action') . '</th>'
  2558. . '</tr>'
  2559. . '</thead>';
  2560. }
  2561. /**
  2562. * Get HTML error for View Users form
  2563. * For non superusers such as grant/create users
  2564. *
  2565. * @return string
  2566. */
  2567. public function getHtmlForViewUsersError()
  2568. {
  2569. return Message::error(
  2570. __('Not enough privilege to view users.')
  2571. )->getDisplay();
  2572. }
  2573. /**
  2574. * Get HTML snippet for table body of specific database or table privileges
  2575. *
  2576. * @param array $privMap privilege map
  2577. * @param string $db database
  2578. *
  2579. * @return string
  2580. */
  2581. public function getHtmlTableBodyForSpecificDbOrTablePrivs($privMap, $db)
  2582. {
  2583. $html_output = '<tbody>';
  2584. $index_checkbox = 0;
  2585. if (empty($privMap)) {
  2586. $html_output .= '<tr>'
  2587. . '<td colspan="6">'
  2588. . __('No user found.')
  2589. . '</td>'
  2590. . '</tr>'
  2591. . '</tbody>';
  2592. return $html_output;
  2593. }
  2594. foreach ($privMap as $current_user => $val) {
  2595. foreach ($val as $current_host => $current_privileges) {
  2596. $nbPrivileges = count($current_privileges);
  2597. $html_output .= '<tr>';
  2598. $value = htmlspecialchars($current_user . '&amp;#27;' . $current_host);
  2599. $html_output .= '<td';
  2600. if ($nbPrivileges > 1) {
  2601. $html_output .= ' rowspan="' . $nbPrivileges . '"';
  2602. }
  2603. $html_output .= '>';
  2604. $html_output .= '<input type="checkbox" class="checkall" '
  2605. . 'name="selected_usr[]" '
  2606. . 'id="checkbox_sel_users_' . ($index_checkbox++) . '" '
  2607. . 'value="' . $value . '"></td>' . "\n";
  2608. // user
  2609. $html_output .= '<td';
  2610. if ($nbPrivileges > 1) {
  2611. $html_output .= ' rowspan="' . $nbPrivileges . '"';
  2612. }
  2613. $html_output .= '>';
  2614. if (empty($current_user)) {
  2615. $html_output .= '<span style="color: #FF0000">'
  2616. . __('Any') . '</span>';
  2617. } else {
  2618. $html_output .= htmlspecialchars((string) $current_user);
  2619. }
  2620. $html_output .= '</td>';
  2621. // host
  2622. $html_output .= '<td';
  2623. if ($nbPrivileges > 1) {
  2624. $html_output .= ' rowspan="' . $nbPrivileges . '"';
  2625. }
  2626. $html_output .= '>';
  2627. $html_output .= htmlspecialchars($current_host);
  2628. $html_output .= '</td>';
  2629. $html_output .= $this->getHtmlListOfPrivs(
  2630. $db,
  2631. $current_privileges,
  2632. $current_user,
  2633. $current_host
  2634. );
  2635. }
  2636. }
  2637. //For fetching routine based privileges
  2638. $html_output .= $this->getHtmlTableBodyForSpecificDbRoutinePrivs($db, $index_checkbox);
  2639. $html_output .= '</tbody>';
  2640. return $html_output;
  2641. }
  2642. /**
  2643. * Get HTML to display privileges
  2644. *
  2645. * @param string $db Database name
  2646. * @param array $current_privileges List of privileges
  2647. * @param string $current_user Current user
  2648. * @param string $current_host Current host
  2649. *
  2650. * @return string HTML to display privileges
  2651. */
  2652. public function getHtmlListOfPrivs(
  2653. $db,
  2654. array $current_privileges,
  2655. $current_user,
  2656. $current_host
  2657. ) {
  2658. $nbPrivileges = count($current_privileges);
  2659. $html_output = null;
  2660. for ($i = 0; $i < $nbPrivileges; $i++) {
  2661. $current = $current_privileges[$i];
  2662. // type
  2663. $html_output .= '<td>';
  2664. if ($current['Type'] == 'g') {
  2665. $html_output .= __('global');
  2666. } elseif ($current['Type'] == 'd') {
  2667. if ($current['Db'] == Util::escapeMysqlWildcards($db)) {
  2668. $html_output .= __('database-specific');
  2669. } else {
  2670. $html_output .= __('wildcard') . ': '
  2671. . '<code>'
  2672. . htmlspecialchars($current['Db'])
  2673. . '</code>';
  2674. }
  2675. } elseif ($current['Type'] == 't') {
  2676. $html_output .= __('table-specific');
  2677. }
  2678. $html_output .= '</td>';
  2679. // privileges
  2680. $html_output .= '<td>';
  2681. if (isset($current['Table_name'])) {
  2682. $privList = explode(',', $current['Table_priv']);
  2683. $privs = [];
  2684. $grantsArr = $this->getTableGrantsArray();
  2685. foreach ($grantsArr as $grant) {
  2686. $privs[$grant[0]] = 'N';
  2687. foreach ($privList as $priv) {
  2688. if ($grant[0] == $priv) {
  2689. $privs[$grant[0]] = 'Y';
  2690. }
  2691. }
  2692. }
  2693. $html_output .= '<code>'
  2694. . implode(
  2695. ',',
  2696. $this->extractPrivInfo($privs, true, true)
  2697. )
  2698. . '</code>';
  2699. } else {
  2700. $html_output .= '<code>'
  2701. . implode(
  2702. ',',
  2703. $this->extractPrivInfo($current, true, false)
  2704. )
  2705. . '</code>';
  2706. }
  2707. $html_output .= '</td>';
  2708. // grant
  2709. $html_output .= '<td>';
  2710. $containsGrant = false;
  2711. if (isset($current['Table_name'])) {
  2712. $privList = explode(',', $current['Table_priv']);
  2713. foreach ($privList as $priv) {
  2714. if ($priv == 'Grant') {
  2715. $containsGrant = true;
  2716. }
  2717. }
  2718. } else {
  2719. $containsGrant = $current['Grant_priv'] == 'Y';
  2720. }
  2721. $html_output .= ($containsGrant ? __('Yes') : __('No'));
  2722. $html_output .= '</td>';
  2723. // action
  2724. $html_output .= '<td>';
  2725. $specific_db = isset($current['Db']) && $current['Db'] != '*'
  2726. ? $current['Db'] : '';
  2727. $specific_table = isset($current['Table_name'])
  2728. && $current['Table_name'] != '*'
  2729. ? $current['Table_name'] : '';
  2730. if ($GLOBALS['is_grantuser']) {
  2731. $html_output .= $this->getUserLink(
  2732. 'edit',
  2733. $current_user,
  2734. $current_host,
  2735. $specific_db,
  2736. $specific_table
  2737. );
  2738. }
  2739. $html_output .= '</td>';
  2740. $html_output .= '<td class="center">'
  2741. . $this->getUserLink(
  2742. 'export',
  2743. $current_user,
  2744. $current_host,
  2745. $specific_db,
  2746. $specific_table
  2747. )
  2748. . '</td>';
  2749. $html_output .= '</tr>';
  2750. if (($i + 1) < $nbPrivileges) {
  2751. $html_output .= '<tr class="noclick">';
  2752. }
  2753. }
  2754. return $html_output;
  2755. }
  2756. /**
  2757. * Returns edit, revoke or export link for a user.
  2758. *
  2759. * @param string $linktype The link type (edit | revoke | export)
  2760. * @param string $username User name
  2761. * @param string $hostname Host name
  2762. * @param string $dbname Database name
  2763. * @param string $tablename Table name
  2764. * @param string $routinename Routine name
  2765. * @param string $initial Initial value
  2766. *
  2767. * @return string HTML code with link
  2768. */
  2769. public function getUserLink(
  2770. $linktype,
  2771. $username,
  2772. $hostname,
  2773. $dbname = '',
  2774. $tablename = '',
  2775. $routinename = '',
  2776. $initial = ''
  2777. ) {
  2778. $html = '<a';
  2779. switch ($linktype) {
  2780. case 'edit':
  2781. $html .= ' class="edit_user_anchor"';
  2782. break;
  2783. case 'export':
  2784. $html .= ' class="export_user_anchor ajax"';
  2785. break;
  2786. }
  2787. $params = [
  2788. 'username' => $username,
  2789. 'hostname' => $hostname,
  2790. ];
  2791. switch ($linktype) {
  2792. case 'edit':
  2793. $params['dbname'] = $dbname;
  2794. $params['tablename'] = $tablename;
  2795. $params['routinename'] = $routinename;
  2796. break;
  2797. case 'revoke':
  2798. $params['dbname'] = $dbname;
  2799. $params['tablename'] = $tablename;
  2800. $params['routinename'] = $routinename;
  2801. $params['revokeall'] = 1;
  2802. break;
  2803. case 'export':
  2804. $params['initial'] = $initial;
  2805. $params['export'] = 1;
  2806. break;
  2807. }
  2808. $html .= ' href="server_privileges.php';
  2809. if ($linktype == 'revoke') {
  2810. $html .= '" data-post="' . Url::getCommon($params, '');
  2811. } else {
  2812. $html .= Url::getCommon($params);
  2813. }
  2814. $html .= '">';
  2815. switch ($linktype) {
  2816. case 'edit':
  2817. $html .= Util::getIcon('b_usredit', __('Edit privileges'));
  2818. break;
  2819. case 'revoke':
  2820. $html .= Util::getIcon('b_usrdrop', __('Revoke'));
  2821. break;
  2822. case 'export':
  2823. $html .= Util::getIcon('b_tblexport', __('Export'));
  2824. break;
  2825. }
  2826. $html .= '</a>';
  2827. return $html;
  2828. }
  2829. /**
  2830. * Returns user group edit link
  2831. *
  2832. * @param string $username User name
  2833. *
  2834. * @return string HTML code with link
  2835. */
  2836. public function getUserGroupEditLink($username)
  2837. {
  2838. return '<a class="edit_user_group_anchor ajax"'
  2839. . ' href="server_privileges.php'
  2840. . Url::getCommon(['username' => $username])
  2841. . '">'
  2842. . Util::getIcon('b_usrlist', __('Edit user group'))
  2843. . '</a>';
  2844. }
  2845. /**
  2846. * Returns number of defined user groups
  2847. *
  2848. * @return integer
  2849. */
  2850. public function getUserGroupCount()
  2851. {
  2852. $cfgRelation = $this->relation->getRelationsParam();
  2853. $user_group_table = Util::backquote($cfgRelation['db'])
  2854. . '.' . Util::backquote($cfgRelation['usergroups']);
  2855. $sql_query = 'SELECT COUNT(*) FROM ' . $user_group_table;
  2856. $user_group_count = $this->dbi->fetchValue(
  2857. $sql_query,
  2858. 0,
  2859. 0,
  2860. DatabaseInterface::CONNECT_CONTROL
  2861. );
  2862. return $user_group_count;
  2863. }
  2864. /**
  2865. * Returns name of user group that user is part of
  2866. *
  2867. * @param string $username User name
  2868. *
  2869. * @return mixed usergroup if found or null if not found
  2870. */
  2871. public function getUserGroupForUser($username)
  2872. {
  2873. $cfgRelation = $this->relation->getRelationsParam();
  2874. if (empty($cfgRelation['db'])
  2875. || empty($cfgRelation['users'])
  2876. ) {
  2877. return null;
  2878. }
  2879. $user_table = Util::backquote($cfgRelation['db'])
  2880. . '.' . Util::backquote($cfgRelation['users']);
  2881. $sql_query = 'SELECT `usergroup` FROM ' . $user_table
  2882. . ' WHERE `username` = \'' . $username . '\''
  2883. . ' LIMIT 1';
  2884. $usergroup = $this->dbi->fetchValue(
  2885. $sql_query,
  2886. 0,
  2887. 0,
  2888. DatabaseInterface::CONNECT_CONTROL
  2889. );
  2890. if ($usergroup === false) {
  2891. return null;
  2892. }
  2893. return $usergroup;
  2894. }
  2895. /**
  2896. * This function return the extra data array for the ajax behavior
  2897. *
  2898. * @param string $password password
  2899. * @param string $sql_query sql query
  2900. * @param string $hostname hostname
  2901. * @param string $username username
  2902. *
  2903. * @return array
  2904. */
  2905. public function getExtraDataForAjaxBehavior(
  2906. $password,
  2907. $sql_query,
  2908. $hostname,
  2909. $username
  2910. ) {
  2911. if (isset($GLOBALS['dbname'])) {
  2912. //if (preg_match('/\\\\(?:_|%)/i', $dbname)) {
  2913. if (preg_match('/(?<!\\\\)(?:_|%)/', $GLOBALS['dbname'])) {
  2914. $dbname_is_wildcard = true;
  2915. } else {
  2916. $dbname_is_wildcard = false;
  2917. }
  2918. }
  2919. $user_group_count = 0;
  2920. if ($GLOBALS['cfgRelation']['menuswork']) {
  2921. $user_group_count = $this->getUserGroupCount();
  2922. }
  2923. $extra_data = [];
  2924. if (strlen($sql_query) > 0) {
  2925. $extra_data['sql_query'] = Util::getMessage(null, $sql_query);
  2926. }
  2927. if (isset($_POST['change_copy'])) {
  2928. /**
  2929. * generate html on the fly for the new user that was just created.
  2930. */
  2931. $new_user_string = '<tr>' . "\n"
  2932. . '<td> <input type="checkbox" name="selected_usr[]" '
  2933. . 'id="checkbox_sel_users_"'
  2934. . 'value="'
  2935. . htmlspecialchars($username)
  2936. . '&amp;#27;' . htmlspecialchars($hostname) . '">'
  2937. . '</td>' . "\n"
  2938. . '<td><label for="checkbox_sel_users_">'
  2939. . (empty($_POST['username'])
  2940. ? '<span style="color: #FF0000">' . __('Any') . '</span>'
  2941. : htmlspecialchars($username) ) . '</label></td>' . "\n"
  2942. . '<td>' . htmlspecialchars($hostname) . '</td>' . "\n";
  2943. $new_user_string .= '<td>';
  2944. if (! empty($password) || isset($_POST['pma_pw'])) {
  2945. $new_user_string .= __('Yes');
  2946. } else {
  2947. $new_user_string .= '<span style="color: #FF0000">'
  2948. . __('No')
  2949. . '</span>';
  2950. }
  2951. $new_user_string .= '</td>' . "\n";
  2952. $new_user_string .= '<td>'
  2953. . '<code>' . implode(', ', $this->extractPrivInfo(null, true)) . '</code>'
  2954. . '</td>'; //Fill in privileges here
  2955. // if $cfg['Servers'][$i]['users'] and $cfg['Servers'][$i]['usergroups'] are
  2956. // enabled
  2957. $cfgRelation = $this->relation->getRelationsParam();
  2958. if (! empty($cfgRelation['users']) && ! empty($cfgRelation['usergroups'])) {
  2959. $new_user_string .= '<td class="usrGroup"></td>';
  2960. }
  2961. $new_user_string .= '<td>';
  2962. if (isset($_POST['Grant_priv']) && $_POST['Grant_priv'] == 'Y') {
  2963. $new_user_string .= __('Yes');
  2964. } else {
  2965. $new_user_string .= __('No');
  2966. }
  2967. $new_user_string .= '</td>';
  2968. if ($GLOBALS['is_grantuser']) {
  2969. $new_user_string .= '<td>'
  2970. . $this->getUserLink('edit', $username, $hostname)
  2971. . '</td>' . "\n";
  2972. }
  2973. if ($cfgRelation['menuswork'] && $user_group_count > 0) {
  2974. $new_user_string .= '<td>'
  2975. . $this->getUserGroupEditLink($username)
  2976. . '</td>' . "\n";
  2977. }
  2978. $new_user_string .= '<td>'
  2979. . $this->getUserLink(
  2980. 'export',
  2981. $username,
  2982. $hostname,
  2983. '',
  2984. '',
  2985. '',
  2986. isset($_GET['initial']) ? $_GET['initial'] : ''
  2987. )
  2988. . '</td>' . "\n";
  2989. $new_user_string .= '</tr>';
  2990. $extra_data['new_user_string'] = $new_user_string;
  2991. /**
  2992. * Generate the string for this alphabet's initial, to update the user
  2993. * pagination
  2994. */
  2995. $new_user_initial = mb_strtoupper(
  2996. mb_substr($username, 0, 1)
  2997. );
  2998. $newUserInitialString = '<a href="server_privileges.php'
  2999. . Url::getCommon(['initial' => $new_user_initial]) . '">'
  3000. . $new_user_initial . '</a>';
  3001. $extra_data['new_user_initial'] = $new_user_initial;
  3002. $extra_data['new_user_initial_string'] = $newUserInitialString;
  3003. }
  3004. if (isset($_POST['update_privs'])) {
  3005. $extra_data['db_specific_privs'] = false;
  3006. $extra_data['db_wildcard_privs'] = false;
  3007. if (isset($dbname_is_wildcard)) {
  3008. $extra_data['db_specific_privs'] = ! $dbname_is_wildcard;
  3009. $extra_data['db_wildcard_privs'] = $dbname_is_wildcard;
  3010. }
  3011. $new_privileges = implode(', ', $this->extractPrivInfo(null, true));
  3012. $extra_data['new_privileges'] = $new_privileges;
  3013. }
  3014. if (isset($_GET['validate_username'])) {
  3015. $sql_query = "SELECT * FROM `mysql`.`user` WHERE `User` = '"
  3016. . $this->dbi->escapeString($_GET['username']) . "';";
  3017. $res = $this->dbi->query($sql_query);
  3018. $row = $this->dbi->fetchRow($res);
  3019. if (empty($row)) {
  3020. $extra_data['user_exists'] = false;
  3021. } else {
  3022. $extra_data['user_exists'] = true;
  3023. }
  3024. }
  3025. return $extra_data;
  3026. }
  3027. /**
  3028. * Get the HTML snippet for change user login information
  3029. *
  3030. * @param string $username username
  3031. * @param string $hostname host name
  3032. *
  3033. * @return string HTML snippet
  3034. */
  3035. public function getChangeLoginInformationHtmlForm($username, $hostname)
  3036. {
  3037. $choices = [
  3038. '4' => __('… keep the old one.'),
  3039. '1' => __('… delete the old one from the user tables.'),
  3040. '2' => __(
  3041. '… revoke all active privileges from '
  3042. . 'the old one and delete it afterwards.'
  3043. ),
  3044. '3' => __(
  3045. '… delete the old one from the user tables '
  3046. . 'and reload the privileges afterwards.'
  3047. ),
  3048. ];
  3049. $html_output = '<form action="server_privileges.php" '
  3050. . 'onsubmit="return checkAddUser(this);" '
  3051. . 'method="post" class="copyUserForm submenu-item">' . "\n"
  3052. . Url::getHiddenInputs('', '')
  3053. . '<input type="hidden" name="old_username" '
  3054. . 'value="' . htmlspecialchars($username) . '">' . "\n"
  3055. . '<input type="hidden" name="old_hostname" '
  3056. . 'value="' . htmlspecialchars($hostname) . '">' . "\n";
  3057. $usergroup = $this->getUserGroupForUser($username);
  3058. if ($usergroup !== null) {
  3059. $html_output .= '<input type="hidden" name="old_usergroup" '
  3060. . 'value="' . htmlspecialchars($usergroup) . '">' . "\n";
  3061. }
  3062. $html_output .= '<fieldset id="fieldset_change_copy_user">' . "\n"
  3063. . '<legend data-submenu-label="' . __('Login Information') . '">' . "\n"
  3064. . __('Change login information / Copy user account')
  3065. . '</legend>' . "\n"
  3066. . $this->getHtmlForLoginInformationFields('change', $username, $hostname);
  3067. $html_output .= '<fieldset id="fieldset_mode">' . "\n"
  3068. . ' <legend>'
  3069. . __('Create a new user account with the same privileges and …')
  3070. . '</legend>' . "\n";
  3071. $html_output .= Util::getRadioFields(
  3072. 'mode',
  3073. $choices,
  3074. '4',
  3075. true
  3076. );
  3077. $html_output .= '</fieldset>' . "\n"
  3078. . '</fieldset>' . "\n";
  3079. $html_output .= '<fieldset id="fieldset_change_copy_user_footer" '
  3080. . 'class="tblFooters">' . "\n"
  3081. . '<input type="hidden" name="change_copy" value="1">' . "\n"
  3082. . '<input class="btn btn-primary" type="submit" value="' . __('Go') . '">' . "\n"
  3083. . '</fieldset>' . "\n"
  3084. . '</form>' . "\n";
  3085. return $html_output;
  3086. }
  3087. /**
  3088. * Provide a line with links to the relevant database and table
  3089. *
  3090. * @param string $url_dbname url database name that urlencode() string
  3091. * @param string $dbname database name
  3092. * @param string $tablename table name
  3093. *
  3094. * @return string HTML snippet
  3095. */
  3096. public function getLinkToDbAndTable($url_dbname, $dbname, $tablename)
  3097. {
  3098. $html_output = '[ ' . __('Database')
  3099. . ' <a href="' . Util::getScriptNameForOption(
  3100. $GLOBALS['cfg']['DefaultTabDatabase'],
  3101. 'database'
  3102. )
  3103. . Url::getCommon(
  3104. [
  3105. 'db' => $url_dbname,
  3106. 'reload' => 1,
  3107. ]
  3108. )
  3109. . '">'
  3110. . htmlspecialchars(Util::unescapeMysqlWildcards($dbname)) . ': '
  3111. . Util::getTitleForTarget(
  3112. $GLOBALS['cfg']['DefaultTabDatabase']
  3113. )
  3114. . "</a> ]\n";
  3115. if (strlen($tablename) > 0) {
  3116. $html_output .= ' [ ' . __('Table') . ' <a href="'
  3117. . Util::getScriptNameForOption(
  3118. $GLOBALS['cfg']['DefaultTabTable'],
  3119. 'table'
  3120. )
  3121. . Url::getCommon(
  3122. [
  3123. 'db' => $url_dbname,
  3124. 'table' => $tablename,
  3125. 'reload' => 1,
  3126. ]
  3127. )
  3128. . '">' . htmlspecialchars($tablename) . ': '
  3129. . Util::getTitleForTarget(
  3130. $GLOBALS['cfg']['DefaultTabTable']
  3131. )
  3132. . "</a> ]\n";
  3133. }
  3134. return $html_output;
  3135. }
  3136. /**
  3137. * no db name given, so we want all privs for the given user
  3138. * db name was given, so we want all user specific rights for this db
  3139. * So this function returns user rights as an array
  3140. *
  3141. * @param string $username username
  3142. * @param string $hostname host name
  3143. * @param string $type database or table
  3144. * @param string $dbname database name
  3145. *
  3146. * @return array database rights
  3147. */
  3148. public function getUserSpecificRights($username, $hostname, $type, $dbname = '')
  3149. {
  3150. $user_host_condition = " WHERE `User`"
  3151. . " = '" . $this->dbi->escapeString($username) . "'"
  3152. . " AND `Host`"
  3153. . " = '" . $this->dbi->escapeString($hostname) . "'";
  3154. if ($type == 'database') {
  3155. $tables_to_search_for_users = [
  3156. 'tables_priv',
  3157. 'columns_priv',
  3158. 'procs_priv',
  3159. ];
  3160. $dbOrTableName = 'Db';
  3161. } elseif ($type == 'table') {
  3162. $user_host_condition .= " AND `Db` LIKE '"
  3163. . $this->dbi->escapeString($dbname) . "'";
  3164. $tables_to_search_for_users = ['columns_priv'];
  3165. $dbOrTableName = 'Table_name';
  3166. } else { // routine
  3167. $user_host_condition .= " AND `Db` LIKE '"
  3168. . $this->dbi->escapeString($dbname) . "'";
  3169. $tables_to_search_for_users = ['procs_priv'];
  3170. $dbOrTableName = 'Routine_name';
  3171. }
  3172. // we also want privileges for this user not in table `db` but in other table
  3173. $tables = $this->dbi->fetchResult('SHOW TABLES FROM `mysql`;');
  3174. $db_rights_sqls = [];
  3175. foreach ($tables_to_search_for_users as $table_search_in) {
  3176. if (in_array($table_search_in, $tables)) {
  3177. $db_rights_sqls[] = '
  3178. SELECT DISTINCT `' . $dbOrTableName . '`
  3179. FROM `mysql`.' . Util::backquote($table_search_in)
  3180. . $user_host_condition;
  3181. }
  3182. }
  3183. $user_defaults = [
  3184. $dbOrTableName => '',
  3185. 'Grant_priv' => 'N',
  3186. 'privs' => ['USAGE'],
  3187. 'Column_priv' => true,
  3188. ];
  3189. // for the rights
  3190. $db_rights = [];
  3191. $db_rights_sql = '(' . implode(') UNION (', $db_rights_sqls) . ')'
  3192. . ' ORDER BY `' . $dbOrTableName . '` ASC';
  3193. $db_rights_result = $this->dbi->query($db_rights_sql);
  3194. while ($db_rights_row = $this->dbi->fetchAssoc($db_rights_result)) {
  3195. $db_rights_row = array_merge($user_defaults, $db_rights_row);
  3196. if ($type == 'database') {
  3197. // only Db names in the table `mysql`.`db` uses wildcards
  3198. // as we are in the db specific rights display we want
  3199. // all db names escaped, also from other sources
  3200. $db_rights_row['Db'] = Util::escapeMysqlWildcards(
  3201. $db_rights_row['Db']
  3202. );
  3203. }
  3204. $db_rights[$db_rights_row[$dbOrTableName]] = $db_rights_row;
  3205. }
  3206. $this->dbi->freeResult($db_rights_result);
  3207. if ($type == 'database') {
  3208. $sql_query = 'SELECT * FROM `mysql`.`db`'
  3209. . $user_host_condition . ' ORDER BY `Db` ASC';
  3210. } elseif ($type == 'table') {
  3211. $sql_query = 'SELECT `Table_name`,'
  3212. . ' `Table_priv`,'
  3213. . ' IF(`Column_priv` = _latin1 \'\', 0, 1)'
  3214. . ' AS \'Column_priv\''
  3215. . ' FROM `mysql`.`tables_priv`'
  3216. . $user_host_condition
  3217. . ' ORDER BY `Table_name` ASC;';
  3218. } else {
  3219. $sql_query = "SELECT `Routine_name`, `Proc_priv`"
  3220. . " FROM `mysql`.`procs_priv`"
  3221. . $user_host_condition
  3222. . " ORDER BY `Routine_name`";
  3223. }
  3224. $result = $this->dbi->query($sql_query);
  3225. while ($row = $this->dbi->fetchAssoc($result)) {
  3226. if (isset($db_rights[$row[$dbOrTableName]])) {
  3227. $db_rights[$row[$dbOrTableName]]
  3228. = array_merge($db_rights[$row[$dbOrTableName]], $row);
  3229. } else {
  3230. $db_rights[$row[$dbOrTableName]] = $row;
  3231. }
  3232. if ($type == 'database') {
  3233. // there are db specific rights for this user
  3234. // so we can drop this db rights
  3235. $db_rights[$row['Db']]['can_delete'] = true;
  3236. }
  3237. }
  3238. $this->dbi->freeResult($result);
  3239. return $db_rights;
  3240. }
  3241. /**
  3242. * Parses Proc_priv data
  3243. *
  3244. * @param string $privs Proc_priv
  3245. *
  3246. * @return array
  3247. */
  3248. public function parseProcPriv($privs)
  3249. {
  3250. $result = [
  3251. 'Alter_routine_priv' => 'N',
  3252. 'Execute_priv' => 'N',
  3253. 'Grant_priv' => 'N',
  3254. ];
  3255. foreach (explode(',', (string) $privs) as $priv) {
  3256. if ($priv == 'Alter Routine') {
  3257. $result['Alter_routine_priv'] = 'Y';
  3258. } else {
  3259. $result[$priv . '_priv'] = 'Y';
  3260. }
  3261. }
  3262. return $result;
  3263. }
  3264. /**
  3265. * Get a HTML table for display user's tabel specific or database specific rights
  3266. *
  3267. * @param string $username username
  3268. * @param string $hostname host name
  3269. * @param string $type database, table or routine
  3270. * @param string $dbname database name
  3271. *
  3272. * @return string
  3273. */
  3274. public function getHtmlForAllTableSpecificRights(
  3275. $username,
  3276. $hostname,
  3277. $type,
  3278. $dbname = ''
  3279. ) {
  3280. $uiData = [
  3281. 'database' => [
  3282. 'form_id' => 'database_specific_priv',
  3283. 'sub_menu_label' => __('Database'),
  3284. 'legend' => __('Database-specific privileges'),
  3285. 'type_label' => __('Database'),
  3286. ],
  3287. 'table' => [
  3288. 'form_id' => 'table_specific_priv',
  3289. 'sub_menu_label' => __('Table'),
  3290. 'legend' => __('Table-specific privileges'),
  3291. 'type_label' => __('Table'),
  3292. ],
  3293. 'routine' => [
  3294. 'form_id' => 'routine_specific_priv',
  3295. 'sub_menu_label' => __('Routine'),
  3296. 'legend' => __('Routine-specific privileges'),
  3297. 'type_label' => __('Routine'),
  3298. ],
  3299. ];
  3300. /**
  3301. * no db name given, so we want all privs for the given user
  3302. * db name was given, so we want all user specific rights for this db
  3303. */
  3304. $db_rights = $this->getUserSpecificRights($username, $hostname, $type, $dbname);
  3305. ksort($db_rights);
  3306. $foundRows = [];
  3307. $privileges = [];
  3308. foreach ($db_rights as $row) {
  3309. $onePrivilege = [];
  3310. $paramTableName = '';
  3311. $paramRoutineName = '';
  3312. if ($type == 'database') {
  3313. $name = $row['Db'];
  3314. $onePrivilege['grant'] = $row['Grant_priv'] == 'Y';
  3315. $onePrivilege['table_privs'] = ! empty($row['Table_priv'])
  3316. || ! empty($row['Column_priv']);
  3317. $onePrivilege['privileges'] = implode(',', $this->extractPrivInfo($row, true));
  3318. $paramDbName = $row['Db'];
  3319. } elseif ($type == 'table') {
  3320. $name = $row['Table_name'];
  3321. $onePrivilege['grant'] = in_array(
  3322. 'Grant',
  3323. explode(',', $row['Table_priv'])
  3324. );
  3325. $onePrivilege['column_privs'] = ! empty($row['Column_priv']);
  3326. $onePrivilege['privileges'] = implode(',', $this->extractPrivInfo($row, true));
  3327. $paramDbName = $dbname;
  3328. $paramTableName = $row['Table_name'];
  3329. } else { // routine
  3330. $name = $row['Routine_name'];
  3331. $onePrivilege['grant'] = in_array(
  3332. 'Grant',
  3333. explode(',', $row['Proc_priv'])
  3334. );
  3335. $privs = $this->parseProcPriv($row['Proc_priv']);
  3336. $onePrivilege['privileges'] = implode(
  3337. ',',
  3338. $this->extractPrivInfo($privs, true)
  3339. );
  3340. $paramDbName = $dbname;
  3341. $paramRoutineName = $row['Routine_name'];
  3342. }
  3343. $foundRows[] = $name;
  3344. $onePrivilege['name'] = $name;
  3345. $onePrivilege['edit_link'] = '';
  3346. if ($GLOBALS['is_grantuser']) {
  3347. $onePrivilege['edit_link'] = $this->getUserLink(
  3348. 'edit',
  3349. $username,
  3350. $hostname,
  3351. $paramDbName,
  3352. $paramTableName,
  3353. $paramRoutineName
  3354. );
  3355. }
  3356. $onePrivilege['revoke_link'] = '';
  3357. if ($type != 'database' || ! empty($row['can_delete'])) {
  3358. $onePrivilege['revoke_link'] = $this->getUserLink(
  3359. 'revoke',
  3360. $username,
  3361. $hostname,
  3362. $paramDbName,
  3363. $paramTableName,
  3364. $paramRoutineName
  3365. );
  3366. }
  3367. $privileges[] = $onePrivilege;
  3368. }
  3369. $data = $uiData[$type];
  3370. $data['privileges'] = $privileges;
  3371. $data['username'] = $username;
  3372. $data['hostname'] = $hostname;
  3373. $data['database'] = $dbname;
  3374. $data['type'] = $type;
  3375. if ($type == 'database') {
  3376. // we already have the list of databases from libraries/common.inc.php
  3377. // via $pma = new PMA;
  3378. $pred_db_array = $GLOBALS['dblist']->databases;
  3379. $databases_to_skip = [
  3380. 'information_schema',
  3381. 'performance_schema',
  3382. ];
  3383. $databases = [];
  3384. if (! empty($pred_db_array)) {
  3385. foreach ($pred_db_array as $current_db) {
  3386. if (in_array($current_db, $databases_to_skip)) {
  3387. continue;
  3388. }
  3389. $current_db_escaped = Util::escapeMysqlWildcards($current_db);
  3390. // cannot use array_diff() once, outside of the loop,
  3391. // because the list of databases has special characters
  3392. // already escaped in $foundRows,
  3393. // contrary to the output of SHOW DATABASES
  3394. if (! in_array($current_db_escaped, $foundRows)) {
  3395. $databases[] = $current_db;
  3396. }
  3397. }
  3398. }
  3399. $data['databases'] = $databases;
  3400. } elseif ($type == 'table') {
  3401. $result = @$this->dbi->tryQuery(
  3402. "SHOW TABLES FROM " . Util::backquote($dbname),
  3403. DatabaseInterface::CONNECT_USER,
  3404. DatabaseInterface::QUERY_STORE
  3405. );
  3406. $tables = [];
  3407. if ($result) {
  3408. while ($row = $this->dbi->fetchRow($result)) {
  3409. if (! in_array($row[0], $foundRows)) {
  3410. $tables[] = $row[0];
  3411. }
  3412. }
  3413. $this->dbi->freeResult($result);
  3414. }
  3415. $data['tables'] = $tables;
  3416. } else { // routine
  3417. $routineData = $this->dbi->getRoutines($dbname);
  3418. $routines = [];
  3419. foreach ($routineData as $routine) {
  3420. if (! in_array($routine['name'], $foundRows)) {
  3421. $routines[] = $routine['name'];
  3422. }
  3423. }
  3424. $data['routines'] = $routines;
  3425. }
  3426. return $this->template->render('server/privileges/privileges_summary', $data);
  3427. }
  3428. /**
  3429. * Get HTML for display the users overview
  3430. * (if less than 50 users, display them immediately)
  3431. *
  3432. * @param array $result ran sql query
  3433. * @param array $db_rights user's database rights array
  3434. * @param string $pmaThemeImage a image source link
  3435. * @param string $text_dir text directory
  3436. *
  3437. * @return string HTML snippet
  3438. */
  3439. public function getUsersOverview($result, array $db_rights, $pmaThemeImage, $text_dir)
  3440. {
  3441. while ($row = $this->dbi->fetchAssoc($result)) {
  3442. $row['privs'] = $this->extractPrivInfo($row, true);
  3443. $db_rights[$row['User']][$row['Host']] = $row;
  3444. }
  3445. $this->dbi->freeResult($result);
  3446. $user_group_count = 0;
  3447. if ($GLOBALS['cfgRelation']['menuswork']) {
  3448. $user_group_count = $this->getUserGroupCount();
  3449. }
  3450. $html_output
  3451. = '<form name="usersForm" id="usersForm" action="server_privileges.php" '
  3452. . 'method="post">' . "\n"
  3453. . Url::getHiddenInputs('', '')
  3454. . '<div class="responsivetable">'
  3455. . '<table id="tableuserrights" class="data">' . "\n"
  3456. . '<thead>' . "\n"
  3457. . '<tr><th></th>' . "\n"
  3458. . '<th>' . __('User name') . '</th>' . "\n"
  3459. . '<th>' . __('Host name') . '</th>' . "\n"
  3460. . '<th>' . __('Password') . '</th>' . "\n"
  3461. . '<th>' . __('Global privileges') . ' '
  3462. . Util::showHint(
  3463. __('Note: MySQL privilege names are expressed in English.')
  3464. )
  3465. . '</th>' . "\n";
  3466. if ($GLOBALS['cfgRelation']['menuswork']) {
  3467. $html_output .= '<th>' . __('User group') . '</th>' . "\n";
  3468. }
  3469. $html_output .= '<th>' . __('Grant') . '</th>' . "\n"
  3470. . '<th colspan="' . ($user_group_count > 0 ? '3' : '2') . '">'
  3471. . __('Action') . '</th>' . "\n"
  3472. . '</tr>' . "\n"
  3473. . '</thead>' . "\n";
  3474. $html_output .= '<tbody>' . "\n";
  3475. $html_output .= $this->getHtmlTableBodyForUserRights($db_rights);
  3476. $html_output .= '</tbody>'
  3477. . '</table></div>' . "\n";
  3478. $html_output .= '<div class="floatleft">'
  3479. . $this->template->render('select_all', [
  3480. 'pma_theme_image' => $pmaThemeImage,
  3481. 'text_dir' => $text_dir,
  3482. 'form_name' => 'usersForm',
  3483. ]) . "\n";
  3484. $html_output .= Util::getButtonOrImage(
  3485. 'submit_mult',
  3486. 'mult_submit',
  3487. __('Export'),
  3488. 'b_tblexport',
  3489. 'export'
  3490. );
  3491. $html_output .= '<input type="hidden" name="initial" '
  3492. . 'value="' . (isset($_GET['initial']) ? htmlspecialchars($_GET['initial']) : '') . '">';
  3493. $html_output .= '</div>'
  3494. . '<div class="clearfloat"></div>';
  3495. // add/delete user fieldset
  3496. $html_output .= $this->getFieldsetForAddDeleteUser();
  3497. $html_output .= '</form>' . "\n";
  3498. return $html_output;
  3499. }
  3500. /**
  3501. * Get table body for 'tableuserrights' table in userform
  3502. *
  3503. * @param array $db_rights user's database rights array
  3504. *
  3505. * @return string HTML snippet
  3506. */
  3507. public function getHtmlTableBodyForUserRights(array $db_rights)
  3508. {
  3509. $cfgRelation = $this->relation->getRelationsParam();
  3510. $user_group_count = 0;
  3511. if ($cfgRelation['menuswork']) {
  3512. $users_table = Util::backquote($cfgRelation['db'])
  3513. . "." . Util::backquote($cfgRelation['users']);
  3514. $sql_query = 'SELECT * FROM ' . $users_table;
  3515. $result = $this->relation->queryAsControlUser($sql_query, false);
  3516. $group_assignment = [];
  3517. if ($result) {
  3518. while ($row = $this->dbi->fetchAssoc($result)) {
  3519. $group_assignment[$row['username']] = $row['usergroup'];
  3520. }
  3521. }
  3522. $this->dbi->freeResult($result);
  3523. $user_group_count = $this->getUserGroupCount();
  3524. }
  3525. $index_checkbox = 0;
  3526. $html_output = '';
  3527. foreach ($db_rights as $user) {
  3528. ksort($user);
  3529. foreach ($user as $host) {
  3530. $index_checkbox++;
  3531. $html_output .= '<tr>'
  3532. . "\n";
  3533. $html_output .= '<td>'
  3534. . '<input type="checkbox" class="checkall" name="selected_usr[]" '
  3535. . 'id="checkbox_sel_users_'
  3536. . $index_checkbox . '" value="'
  3537. . htmlspecialchars($host['User'] . '&amp;#27;' . $host['Host'])
  3538. . '"'
  3539. . '></td>' . "\n";
  3540. $html_output .= '<td><label '
  3541. . 'for="checkbox_sel_users_' . $index_checkbox . '">'
  3542. . (empty($host['User'])
  3543. ? '<span style="color: #FF0000">' . __('Any') . '</span>'
  3544. : htmlspecialchars($host['User'])) . '</label></td>' . "\n"
  3545. . '<td>' . htmlspecialchars($host['Host']) . '</td>' . "\n";
  3546. $html_output .= '<td>';
  3547. $password_column = 'Password';
  3548. $check_plugin_query = "SELECT * FROM `mysql`.`user` WHERE "
  3549. . "`User` = '" . $host['User'] . "' AND `Host` = '"
  3550. . $host['Host'] . "'";
  3551. $res = $this->dbi->fetchSingleRow($check_plugin_query);
  3552. if ((isset($res['authentication_string'])
  3553. && ! empty($res['authentication_string']))
  3554. || (isset($res['Password'])
  3555. && ! empty($res['Password']))
  3556. ) {
  3557. $host[$password_column] = 'Y';
  3558. } else {
  3559. $host[$password_column] = 'N';
  3560. }
  3561. switch ($host[$password_column]) {
  3562. case 'Y':
  3563. $html_output .= __('Yes');
  3564. break;
  3565. case 'N':
  3566. $html_output .= '<span style="color: #FF0000">' . __('No')
  3567. . '</span>';
  3568. break;
  3569. // this happens if this is a definition not coming from mysql.user
  3570. default:
  3571. $html_output .= '--'; // in future version, replace by "not present"
  3572. break;
  3573. } // end switch
  3574. if (! isset($host['Select_priv'])) {
  3575. $html_output .= Util::showHint(
  3576. __('The selected user was not found in the privilege table.')
  3577. );
  3578. }
  3579. $html_output .= '</td>' . "\n";
  3580. $html_output .= '<td><code>' . "\n"
  3581. . '' . implode(',' . "\n" . ' ', $host['privs']) . "\n"
  3582. . '</code></td>' . "\n";
  3583. if ($cfgRelation['menuswork']) {
  3584. $html_output .= '<td class="usrGroup">' . "\n"
  3585. . (isset($group_assignment[$host['User']])
  3586. ? htmlspecialchars($group_assignment[$host['User']])
  3587. : ''
  3588. )
  3589. . '</td>' . "\n";
  3590. }
  3591. $html_output .= '<td>'
  3592. . ($host['Grant_priv'] == 'Y' ? __('Yes') : __('No'))
  3593. . '</td>' . "\n";
  3594. if ($GLOBALS['is_grantuser']) {
  3595. $html_output .= '<td class="center">'
  3596. . $this->getUserLink(
  3597. 'edit',
  3598. $host['User'],
  3599. $host['Host']
  3600. )
  3601. . '</td>';
  3602. }
  3603. if ($cfgRelation['menuswork'] && $user_group_count > 0) {
  3604. if (empty($host['User'])) {
  3605. $html_output .= '<td class="center"></td>';
  3606. } else {
  3607. $html_output .= '<td class="center">'
  3608. . $this->getUserGroupEditLink($host['User'])
  3609. . '</td>';
  3610. }
  3611. }
  3612. $html_output .= '<td class="center">'
  3613. . $this->getUserLink(
  3614. 'export',
  3615. $host['User'],
  3616. $host['Host'],
  3617. '',
  3618. '',
  3619. '',
  3620. isset($_GET['initial']) ? $_GET['initial'] : ''
  3621. )
  3622. . '</td>';
  3623. $html_output .= '</tr>';
  3624. }
  3625. }
  3626. return $html_output;
  3627. }
  3628. /**
  3629. * Get HTML fieldset for Add/Delete user
  3630. *
  3631. * @return string HTML snippet
  3632. */
  3633. public function getFieldsetForAddDeleteUser()
  3634. {
  3635. $html_output = $this->getAddUserHtmlFieldset();
  3636. $html_output .= $this->template->render('server/privileges/delete_user_fieldset');
  3637. return $html_output;
  3638. }
  3639. /**
  3640. * Get HTML for Displays the initials
  3641. *
  3642. * @param array $array_initials array for all initials, even non A-Z
  3643. *
  3644. * @return string HTML snippet
  3645. */
  3646. public function getHtmlForInitials(array $array_initials)
  3647. {
  3648. // initialize to false the letters A-Z
  3649. for ($letter_counter = 1; $letter_counter < 27; $letter_counter++) {
  3650. if (! isset($array_initials[mb_chr($letter_counter + 64)])) {
  3651. $array_initials[mb_chr($letter_counter + 64)] = false;
  3652. }
  3653. }
  3654. $initials = $this->dbi->tryQuery(
  3655. 'SELECT DISTINCT UPPER(LEFT(`User`,1)) FROM `user`'
  3656. . ' ORDER BY UPPER(LEFT(`User`,1)) ASC',
  3657. DatabaseInterface::CONNECT_USER,
  3658. DatabaseInterface::QUERY_STORE
  3659. );
  3660. if ($initials) {
  3661. while (list($tmp_initial) = $this->dbi->fetchRow($initials)) {
  3662. $array_initials[$tmp_initial] = true;
  3663. }
  3664. }
  3665. // Display the initials, which can be any characters, not
  3666. // just letters. For letters A-Z, we add the non-used letters
  3667. // as greyed out.
  3668. uksort($array_initials, "strnatcasecmp");
  3669. return $this->template->render('server/privileges/initials_row', [
  3670. 'array_initials' => $array_initials,
  3671. 'initial' => isset($_GET['initial']) ? $_GET['initial'] : null,
  3672. ]);
  3673. }
  3674. /**
  3675. * Get the database rights array for Display user overview
  3676. *
  3677. * @return array database rights array
  3678. */
  3679. public function getDbRightsForUserOverview()
  3680. {
  3681. // we also want users not in table `user` but in other table
  3682. $tables = $this->dbi->fetchResult('SHOW TABLES FROM `mysql`;');
  3683. $tablesSearchForUsers = [
  3684. 'user',
  3685. 'db',
  3686. 'tables_priv',
  3687. 'columns_priv',
  3688. 'procs_priv',
  3689. ];
  3690. $db_rights_sqls = [];
  3691. foreach ($tablesSearchForUsers as $table_search_in) {
  3692. if (in_array($table_search_in, $tables)) {
  3693. $db_rights_sqls[] = 'SELECT DISTINCT `User`, `Host` FROM `mysql`.`'
  3694. . $table_search_in . '` '
  3695. . (isset($_GET['initial'])
  3696. ? $this->rangeOfUsers($_GET['initial'])
  3697. : '');
  3698. }
  3699. }
  3700. $user_defaults = [
  3701. 'User' => '',
  3702. 'Host' => '%',
  3703. 'Password' => '?',
  3704. 'Grant_priv' => 'N',
  3705. 'privs' => ['USAGE'],
  3706. ];
  3707. // for the rights
  3708. $db_rights = [];
  3709. $db_rights_sql = '(' . implode(') UNION (', $db_rights_sqls) . ')'
  3710. . ' ORDER BY `User` ASC, `Host` ASC';
  3711. $db_rights_result = $this->dbi->query($db_rights_sql);
  3712. while ($db_rights_row = $this->dbi->fetchAssoc($db_rights_result)) {
  3713. $db_rights_row = array_merge($user_defaults, $db_rights_row);
  3714. $db_rights[$db_rights_row['User']][$db_rights_row['Host']]
  3715. = $db_rights_row;
  3716. }
  3717. $this->dbi->freeResult($db_rights_result);
  3718. ksort($db_rights);
  3719. return $db_rights;
  3720. }
  3721. /**
  3722. * Delete user and get message and sql query for delete user in privileges
  3723. *
  3724. * @param array $queries queries
  3725. *
  3726. * @return array Message
  3727. */
  3728. public function deleteUser(array $queries)
  3729. {
  3730. $sql_query = '';
  3731. if (empty($queries)) {
  3732. $message = Message::error(__('No users selected for deleting!'));
  3733. } else {
  3734. if ($_POST['mode'] == 3) {
  3735. $queries[] = '# ' . __('Reloading the privileges') . ' …';
  3736. $queries[] = 'FLUSH PRIVILEGES;';
  3737. }
  3738. $drop_user_error = '';
  3739. foreach ($queries as $sql_query) {
  3740. if ($sql_query[0] != '#') {
  3741. if (! $this->dbi->tryQuery($sql_query)) {
  3742. $drop_user_error .= $this->dbi->getError() . "\n";
  3743. }
  3744. }
  3745. }
  3746. // tracking sets this, causing the deleted db to be shown in navi
  3747. unset($GLOBALS['db']);
  3748. $sql_query = implode("\n", $queries);
  3749. if (! empty($drop_user_error)) {
  3750. $message = Message::rawError($drop_user_error);
  3751. } else {
  3752. $message = Message::success(
  3753. __('The selected users have been deleted successfully.')
  3754. );
  3755. }
  3756. }
  3757. return [
  3758. $sql_query,
  3759. $message,
  3760. ];
  3761. }
  3762. /**
  3763. * Update the privileges and return the success or error message
  3764. *
  3765. * @param string $username username
  3766. * @param string $hostname host name
  3767. * @param string $tablename table name
  3768. * @param string $dbname database name
  3769. * @param string $itemType item type
  3770. *
  3771. * @return array success message or error message for update
  3772. */
  3773. public function updatePrivileges($username, $hostname, $tablename, $dbname, $itemType)
  3774. {
  3775. $db_and_table = $this->wildcardEscapeForGrant($dbname, $tablename);
  3776. $sql_query0 = 'REVOKE ALL PRIVILEGES ON ' . $itemType . ' ' . $db_and_table
  3777. . ' FROM \'' . $this->dbi->escapeString($username)
  3778. . '\'@\'' . $this->dbi->escapeString($hostname) . '\';';
  3779. if (! isset($_POST['Grant_priv']) || $_POST['Grant_priv'] != 'Y') {
  3780. $sql_query1 = 'REVOKE GRANT OPTION ON ' . $itemType . ' ' . $db_and_table
  3781. . ' FROM \'' . $this->dbi->escapeString($username) . '\'@\''
  3782. . $this->dbi->escapeString($hostname) . '\';';
  3783. } else {
  3784. $sql_query1 = '';
  3785. }
  3786. // Should not do a GRANT USAGE for a table-specific privilege, it
  3787. // causes problems later (cannot revoke it)
  3788. if (! (strlen($tablename) > 0
  3789. && 'USAGE' == implode('', $this->extractPrivInfo()))
  3790. ) {
  3791. $sql_query2 = 'GRANT ' . implode(', ', $this->extractPrivInfo())
  3792. . ' ON ' . $itemType . ' ' . $db_and_table
  3793. . ' TO \'' . $this->dbi->escapeString($username) . '\'@\''
  3794. . $this->dbi->escapeString($hostname) . '\'';
  3795. if (strlen($dbname) === 0) {
  3796. // add REQUIRE clause
  3797. $sql_query2 .= $this->getRequireClause();
  3798. }
  3799. if ((isset($_POST['Grant_priv']) && $_POST['Grant_priv'] == 'Y')
  3800. || (strlen($dbname) === 0
  3801. && (isset($_POST['max_questions']) || isset($_POST['max_connections'])
  3802. || isset($_POST['max_updates'])
  3803. || isset($_POST['max_user_connections'])))
  3804. ) {
  3805. $sql_query2 .= $this->getWithClauseForAddUserAndUpdatePrivs();
  3806. }
  3807. $sql_query2 .= ';';
  3808. }
  3809. if (! $this->dbi->tryQuery($sql_query0)) {
  3810. // This might fail when the executing user does not have
  3811. // ALL PRIVILEGES himself.
  3812. // See https://github.com/phpmyadmin/phpmyadmin/issues/9673
  3813. $sql_query0 = '';
  3814. }
  3815. if (! empty($sql_query1) && ! $this->dbi->tryQuery($sql_query1)) {
  3816. // this one may fail, too...
  3817. $sql_query1 = '';
  3818. }
  3819. if (! empty($sql_query2)) {
  3820. $this->dbi->query($sql_query2);
  3821. } else {
  3822. $sql_query2 = '';
  3823. }
  3824. $sql_query = $sql_query0 . ' ' . $sql_query1 . ' ' . $sql_query2;
  3825. $message = Message::success(__('You have updated the privileges for %s.'));
  3826. $message->addParam('\'' . $username . '\'@\'' . $hostname . '\'');
  3827. return [
  3828. $sql_query,
  3829. $message,
  3830. ];
  3831. }
  3832. /**
  3833. * Get List of information: Changes / copies a user
  3834. *
  3835. * @return array
  3836. */
  3837. public function getDataForChangeOrCopyUser()
  3838. {
  3839. $queries = null;
  3840. $password = null;
  3841. if (isset($_POST['change_copy'])) {
  3842. $user_host_condition = ' WHERE `User` = '
  3843. . "'" . $this->dbi->escapeString($_POST['old_username']) . "'"
  3844. . ' AND `Host` = '
  3845. . "'" . $this->dbi->escapeString($_POST['old_hostname']) . "';";
  3846. $row = $this->dbi->fetchSingleRow(
  3847. 'SELECT * FROM `mysql`.`user` ' . $user_host_condition
  3848. );
  3849. if (! $row) {
  3850. $response = Response::getInstance();
  3851. $response->addHTML(
  3852. Message::notice(__('No user found.'))->getDisplay()
  3853. );
  3854. unset($_POST['change_copy']);
  3855. } else {
  3856. foreach ($row as $key => $value) {
  3857. $GLOBALS[$key] = $value;
  3858. }
  3859. $serverVersion = $this->dbi->getVersion();
  3860. // Recent MySQL versions have the field "Password" in mysql.user,
  3861. // so the previous extract creates $row['Password'] but this script
  3862. // uses $password
  3863. if (! isset($row['password']) && isset($row['Password'])) {
  3864. $row['password'] = $row['Password'];
  3865. }
  3866. if (Util::getServerType() == 'MySQL'
  3867. && $serverVersion >= 50606
  3868. && $serverVersion < 50706
  3869. && ((isset($row['authentication_string'])
  3870. && empty($row['password']))
  3871. || (isset($row['plugin'])
  3872. && $row['plugin'] == 'sha256_password'))
  3873. ) {
  3874. $row['password'] = $row['authentication_string'];
  3875. }
  3876. if (Util::getServerType() == 'MariaDB'
  3877. && $serverVersion >= 50500
  3878. && isset($row['authentication_string'])
  3879. && empty($row['password'])
  3880. ) {
  3881. $row['password'] = $row['authentication_string'];
  3882. }
  3883. // Always use 'authentication_string' column
  3884. // for MySQL 5.7.6+ since it does not have
  3885. // the 'password' column at all
  3886. if (in_array(Util::getServerType(), ['MySQL', 'Percona Server'])
  3887. && $serverVersion >= 50706
  3888. && isset($row['authentication_string'])
  3889. ) {
  3890. $row['password'] = $row['authentication_string'];
  3891. }
  3892. $password = $row['password'];
  3893. $queries = [];
  3894. }
  3895. }
  3896. return [
  3897. $queries,
  3898. $password,
  3899. ];
  3900. }
  3901. /**
  3902. * Update Data for information: Deletes users
  3903. *
  3904. * @param array $queries queries array
  3905. *
  3906. * @return array
  3907. */
  3908. public function getDataForDeleteUsers($queries)
  3909. {
  3910. if (isset($_POST['change_copy'])) {
  3911. $selected_usr = [
  3912. $_POST['old_username'] . '&amp;#27;' . $_POST['old_hostname'],
  3913. ];
  3914. } else {
  3915. $selected_usr = $_POST['selected_usr'];
  3916. $queries = [];
  3917. }
  3918. // this happens, was seen in https://reports.phpmyadmin.net/reports/view/17146
  3919. if (! is_array($selected_usr)) {
  3920. return [];
  3921. }
  3922. foreach ($selected_usr as $each_user) {
  3923. list($this_user, $this_host) = explode('&amp;#27;', $each_user);
  3924. $queries[] = '# '
  3925. . sprintf(
  3926. __('Deleting %s'),
  3927. '\'' . $this_user . '\'@\'' . $this_host . '\''
  3928. )
  3929. . ' ...';
  3930. $queries[] = 'DROP USER \''
  3931. . $this->dbi->escapeString($this_user)
  3932. . '\'@\'' . $this->dbi->escapeString($this_host) . '\';';
  3933. $this->relationCleanup->user($this_user);
  3934. if (isset($_POST['drop_users_db'])) {
  3935. $queries[] = 'DROP DATABASE IF EXISTS '
  3936. . Util::backquote($this_user) . ';';
  3937. $GLOBALS['reload'] = true;
  3938. }
  3939. }
  3940. return $queries;
  3941. }
  3942. /**
  3943. * update Message For Reload
  3944. *
  3945. * @return Message|null
  3946. */
  3947. public function updateMessageForReload(): ?Message
  3948. {
  3949. $message = null;
  3950. if (isset($_GET['flush_privileges'])) {
  3951. $sql_query = 'FLUSH PRIVILEGES;';
  3952. $this->dbi->query($sql_query);
  3953. $message = Message::success(
  3954. __('The privileges were reloaded successfully.')
  3955. );
  3956. }
  3957. if (isset($_GET['validate_username'])) {
  3958. $message = Message::success();
  3959. }
  3960. return $message;
  3961. }
  3962. /**
  3963. * update Data For Queries from queries_for_display
  3964. *
  3965. * @param array $queries queries array
  3966. * @param array|null $queries_for_display queries array for display
  3967. *
  3968. * @return array
  3969. */
  3970. public function getDataForQueries(array $queries, $queries_for_display)
  3971. {
  3972. $tmp_count = 0;
  3973. foreach ($queries as $sql_query) {
  3974. if ($sql_query[0] != '#') {
  3975. $this->dbi->query($sql_query);
  3976. }
  3977. // when there is a query containing a hidden password, take it
  3978. // instead of the real query sent
  3979. if (isset($queries_for_display[$tmp_count])) {
  3980. $queries[$tmp_count] = $queries_for_display[$tmp_count];
  3981. }
  3982. $tmp_count++;
  3983. }
  3984. return $queries;
  3985. }
  3986. /**
  3987. * update Data for information: Adds a user
  3988. *
  3989. * @param string|array|null $dbname db name
  3990. * @param string $username user name
  3991. * @param string $hostname host name
  3992. * @param string|null $password password
  3993. * @param bool $is_menuwork is_menuwork set?
  3994. *
  3995. * @return array
  3996. */
  3997. public function addUser(
  3998. $dbname,
  3999. $username,
  4000. $hostname,
  4001. ?string $password,
  4002. $is_menuwork
  4003. ) {
  4004. $_add_user_error = false;
  4005. $message = null;
  4006. $queries = null;
  4007. $queries_for_display = null;
  4008. $sql_query = null;
  4009. if (! isset($_POST['adduser_submit']) && ! isset($_POST['change_copy'])) {
  4010. return [
  4011. $message,
  4012. $queries,
  4013. $queries_for_display,
  4014. $sql_query,
  4015. $_add_user_error,
  4016. ];
  4017. }
  4018. $sql_query = '';
  4019. if ($_POST['pred_username'] == 'any') {
  4020. $username = '';
  4021. }
  4022. switch ($_POST['pred_hostname']) {
  4023. case 'any':
  4024. $hostname = '%';
  4025. break;
  4026. case 'localhost':
  4027. $hostname = 'localhost';
  4028. break;
  4029. case 'hosttable':
  4030. $hostname = '';
  4031. break;
  4032. case 'thishost':
  4033. $_user_name = $this->dbi->fetchValue('SELECT USER()');
  4034. $hostname = mb_substr(
  4035. $_user_name,
  4036. mb_strrpos($_user_name, '@') + 1
  4037. );
  4038. unset($_user_name);
  4039. break;
  4040. }
  4041. $sql = "SELECT '1' FROM `mysql`.`user`"
  4042. . " WHERE `User` = '" . $this->dbi->escapeString($username) . "'"
  4043. . " AND `Host` = '" . $this->dbi->escapeString($hostname) . "';";
  4044. if ($this->dbi->fetchValue($sql) == 1) {
  4045. $message = Message::error(__('The user %s already exists!'));
  4046. $message->addParam('[em]\'' . $username . '\'@\'' . $hostname . '\'[/em]');
  4047. $_GET['adduser'] = true;
  4048. $_add_user_error = true;
  4049. return [
  4050. $message,
  4051. $queries,
  4052. $queries_for_display,
  4053. $sql_query,
  4054. $_add_user_error,
  4055. ];
  4056. }
  4057. list(
  4058. $create_user_real,
  4059. $create_user_show,
  4060. $real_sql_query,
  4061. $sql_query,
  4062. $password_set_real,
  4063. $password_set_show,
  4064. $alter_real_sql_query,
  4065. $alter_sql_query
  4066. ) = $this->getSqlQueriesForDisplayAndAddUser(
  4067. $username,
  4068. $hostname,
  4069. (isset($password) ? $password : '')
  4070. );
  4071. if (empty($_POST['change_copy'])) {
  4072. $_error = false;
  4073. if ($create_user_real !== null) {
  4074. if (! $this->dbi->tryQuery($create_user_real)) {
  4075. $_error = true;
  4076. }
  4077. if (isset($password_set_real) && ! empty($password_set_real)
  4078. && isset($_POST['authentication_plugin'])
  4079. ) {
  4080. $this->setProperPasswordHashing(
  4081. $_POST['authentication_plugin']
  4082. );
  4083. if ($this->dbi->tryQuery($password_set_real)) {
  4084. $sql_query .= $password_set_show;
  4085. }
  4086. }
  4087. $sql_query = $create_user_show . $sql_query;
  4088. }
  4089. list($sql_query, $message) = $this->addUserAndCreateDatabase(
  4090. $_error,
  4091. $real_sql_query,
  4092. $sql_query,
  4093. $username,
  4094. $hostname,
  4095. $dbname,
  4096. $alter_real_sql_query,
  4097. $alter_sql_query
  4098. );
  4099. if (! empty($_POST['userGroup']) && $is_menuwork) {
  4100. $this->setUserGroup($GLOBALS['username'], $_POST['userGroup']);
  4101. }
  4102. return [
  4103. $message,
  4104. $queries,
  4105. $queries_for_display,
  4106. $sql_query,
  4107. $_add_user_error,
  4108. ];
  4109. }
  4110. // Copy the user group while copying a user
  4111. $old_usergroup =
  4112. isset($_POST['old_usergroup']) ? $_POST['old_usergroup'] : null;
  4113. $this->setUserGroup($_POST['username'], $old_usergroup);
  4114. if ($create_user_real !== null) {
  4115. $queries[] = $create_user_real;
  4116. }
  4117. $queries[] = $real_sql_query;
  4118. if (isset($password_set_real) && ! empty($password_set_real)
  4119. && isset($_POST['authentication_plugin'])
  4120. ) {
  4121. $this->setProperPasswordHashing(
  4122. $_POST['authentication_plugin']
  4123. );
  4124. $queries[] = $password_set_real;
  4125. }
  4126. // we put the query containing the hidden password in
  4127. // $queries_for_display, at the same position occupied
  4128. // by the real query in $queries
  4129. $tmp_count = count($queries);
  4130. if (isset($create_user_real)) {
  4131. $queries_for_display[$tmp_count - 2] = $create_user_show;
  4132. }
  4133. if (isset($password_set_real) && ! empty($password_set_real)) {
  4134. $queries_for_display[$tmp_count - 3] = $create_user_show;
  4135. $queries_for_display[$tmp_count - 2] = $sql_query;
  4136. $queries_for_display[$tmp_count - 1] = $password_set_show;
  4137. } else {
  4138. $queries_for_display[$tmp_count - 1] = $sql_query;
  4139. }
  4140. return [
  4141. $message,
  4142. $queries,
  4143. $queries_for_display,
  4144. $sql_query,
  4145. $_add_user_error,
  4146. ];
  4147. }
  4148. /**
  4149. * Sets proper value of `old_passwords` according to
  4150. * the authentication plugin selected
  4151. *
  4152. * @param string $auth_plugin authentication plugin selected
  4153. *
  4154. * @return void
  4155. */
  4156. public function setProperPasswordHashing($auth_plugin)
  4157. {
  4158. // Set the hashing method used by PASSWORD()
  4159. // to be of type depending upon $authentication_plugin
  4160. if ($auth_plugin == 'sha256_password') {
  4161. $this->dbi->tryQuery('SET `old_passwords` = 2;');
  4162. } elseif ($auth_plugin == 'mysql_old_password') {
  4163. $this->dbi->tryQuery('SET `old_passwords` = 1;');
  4164. } else {
  4165. $this->dbi->tryQuery('SET `old_passwords` = 0;');
  4166. }
  4167. }
  4168. /**
  4169. * Update DB information: DB, Table, isWildcard
  4170. *
  4171. * @return array
  4172. */
  4173. public function getDataForDBInfo()
  4174. {
  4175. $username = null;
  4176. $hostname = null;
  4177. $dbname = null;
  4178. $tablename = null;
  4179. $routinename = null;
  4180. $dbname_is_wildcard = null;
  4181. if (isset($_REQUEST['username'])) {
  4182. $username = (string) $_REQUEST['username'];
  4183. }
  4184. if (isset($_REQUEST['hostname'])) {
  4185. $hostname = (string) $_REQUEST['hostname'];
  4186. }
  4187. /**
  4188. * Checks if a dropdown box has been used for selecting a database / table
  4189. */
  4190. if (Core::isValid($_POST['pred_tablename'])) {
  4191. $tablename = $_POST['pred_tablename'];
  4192. } elseif (Core::isValid($_REQUEST['tablename'])) {
  4193. $tablename = $_REQUEST['tablename'];
  4194. } else {
  4195. unset($tablename);
  4196. }
  4197. if (Core::isValid($_POST['pred_routinename'])) {
  4198. $routinename = $_POST['pred_routinename'];
  4199. } elseif (Core::isValid($_REQUEST['routinename'])) {
  4200. $routinename = $_REQUEST['routinename'];
  4201. } else {
  4202. unset($routinename);
  4203. }
  4204. if (isset($_POST['pred_dbname'])) {
  4205. $is_valid_pred_dbname = true;
  4206. foreach ($_POST['pred_dbname'] as $key => $db_name) {
  4207. if (! Core::isValid($db_name)) {
  4208. $is_valid_pred_dbname = false;
  4209. break;
  4210. }
  4211. }
  4212. }
  4213. if (isset($_REQUEST['dbname'])) {
  4214. $is_valid_dbname = true;
  4215. if (is_array($_REQUEST['dbname'])) {
  4216. foreach ($_REQUEST['dbname'] as $key => $db_name) {
  4217. if (! Core::isValid($db_name)) {
  4218. $is_valid_dbname = false;
  4219. break;
  4220. }
  4221. }
  4222. } else {
  4223. if (! Core::isValid($_REQUEST['dbname'])) {
  4224. $is_valid_dbname = false;
  4225. }
  4226. }
  4227. }
  4228. if (isset($is_valid_pred_dbname) && $is_valid_pred_dbname) {
  4229. $dbname = $_POST['pred_dbname'];
  4230. // If dbname contains only one database.
  4231. if (count($dbname) === 1) {
  4232. $dbname = $dbname[0];
  4233. }
  4234. } elseif (isset($is_valid_dbname) && $is_valid_dbname) {
  4235. $dbname = $_REQUEST['dbname'];
  4236. } else {
  4237. unset($dbname);
  4238. unset($tablename);
  4239. }
  4240. if (isset($dbname)) {
  4241. if (is_array($dbname)) {
  4242. $db_and_table = $dbname;
  4243. foreach ($db_and_table as $key => $db_name) {
  4244. $db_and_table[$key] .= '.';
  4245. }
  4246. } else {
  4247. $unescaped_db = Util::unescapeMysqlWildcards($dbname);
  4248. $db_and_table = Util::backquote($unescaped_db) . '.';
  4249. }
  4250. if (isset($tablename)) {
  4251. $db_and_table .= Util::backquote($tablename);
  4252. } else {
  4253. if (is_array($db_and_table)) {
  4254. foreach ($db_and_table as $key => $db_name) {
  4255. $db_and_table[$key] .= '*';
  4256. }
  4257. } else {
  4258. $db_and_table .= '*';
  4259. }
  4260. }
  4261. } else {
  4262. $db_and_table = '*.*';
  4263. }
  4264. // check if given $dbname is a wildcard or not
  4265. if (isset($dbname)) {
  4266. //if (preg_match('/\\\\(?:_|%)/i', $dbname)) {
  4267. if (! is_array($dbname) && preg_match('/(?<!\\\\)(?:_|%)/', $dbname)) {
  4268. $dbname_is_wildcard = true;
  4269. } else {
  4270. $dbname_is_wildcard = false;
  4271. }
  4272. }
  4273. return [
  4274. $username,
  4275. $hostname,
  4276. isset($dbname) ? $dbname : null,
  4277. isset($tablename) ? $tablename : null,
  4278. isset($routinename) ? $routinename : null,
  4279. $db_and_table,
  4280. $dbname_is_wildcard,
  4281. ];
  4282. }
  4283. /**
  4284. * Get title and textarea for export user definition in Privileges
  4285. *
  4286. * @param string $username username
  4287. * @param string $hostname host name
  4288. *
  4289. * @return array ($title, $export)
  4290. */
  4291. public function getListForExportUserDefinition($username, $hostname)
  4292. {
  4293. $export = '<textarea class="export" cols="60" rows="15">';
  4294. if (isset($_POST['selected_usr'])) {
  4295. // export privileges for selected users
  4296. $title = __('Privileges');
  4297. //For removing duplicate entries of users
  4298. $_POST['selected_usr'] = array_unique($_POST['selected_usr']);
  4299. foreach ($_POST['selected_usr'] as $export_user) {
  4300. $export_username = mb_substr(
  4301. $export_user,
  4302. 0,
  4303. mb_strpos($export_user, '&')
  4304. );
  4305. $export_hostname = mb_substr(
  4306. $export_user,
  4307. mb_strrpos($export_user, ';') + 1
  4308. );
  4309. $export .= '# '
  4310. . sprintf(
  4311. __('Privileges for %s'),
  4312. '`' . htmlspecialchars($export_username)
  4313. . '`@`' . htmlspecialchars($export_hostname) . '`'
  4314. )
  4315. . "\n\n";
  4316. $export .= $this->getGrants($export_username, $export_hostname) . "\n";
  4317. }
  4318. } else {
  4319. // export privileges for a single user
  4320. $title = __('User') . ' `' . htmlspecialchars($username)
  4321. . '`@`' . htmlspecialchars($hostname) . '`';
  4322. $export .= $this->getGrants($username, $hostname);
  4323. }
  4324. // remove trailing whitespace
  4325. $export = trim($export);
  4326. $export .= '</textarea>';
  4327. return [
  4328. $title,
  4329. $export,
  4330. ];
  4331. }
  4332. /**
  4333. * Get HTML for display Add userfieldset
  4334. *
  4335. * @param string $db the database
  4336. * @param string $table the table name
  4337. *
  4338. * @return string html output
  4339. */
  4340. public function getAddUserHtmlFieldset($db = '', $table = '')
  4341. {
  4342. if (! $GLOBALS['is_createuser']) {
  4343. return '';
  4344. }
  4345. $rel_params = [];
  4346. $url_params = [
  4347. 'adduser' => 1,
  4348. ];
  4349. if (! empty($db)) {
  4350. $url_params['dbname']
  4351. = $rel_params['checkprivsdb']
  4352. = $db;
  4353. }
  4354. if (! empty($table)) {
  4355. $url_params['tablename']
  4356. = $rel_params['checkprivstable']
  4357. = $table;
  4358. }
  4359. return $this->template->render('server/privileges/add_user_fieldset', [
  4360. 'url_params' => $url_params,
  4361. 'rel_params' => $rel_params,
  4362. ]);
  4363. }
  4364. /**
  4365. * Get HTML header for display User's properties
  4366. *
  4367. * @param boolean $dbname_is_wildcard whether database name is wildcard or not
  4368. * @param string $url_dbname url database name that urlencode() string
  4369. * @param string $dbname database name
  4370. * @param string $username username
  4371. * @param string $hostname host name
  4372. * @param string $entity_name entity (table or routine) name
  4373. * @param string $entity_type optional, type of entity ('table' or 'routine')
  4374. *
  4375. * @return string
  4376. */
  4377. public function getHtmlHeaderForUserProperties(
  4378. $dbname_is_wildcard,
  4379. $url_dbname,
  4380. $dbname,
  4381. $username,
  4382. $hostname,
  4383. $entity_name,
  4384. $entity_type = 'table'
  4385. ) {
  4386. $html_output = '<h2>' . "\n"
  4387. . Util::getIcon('b_usredit')
  4388. . __('Edit privileges:') . ' '
  4389. . __('User account');
  4390. if (! empty($dbname)) {
  4391. $html_output .= ' <i><a class="edit_user_anchor"'
  4392. . ' href="server_privileges.php'
  4393. . Url::getCommon(
  4394. [
  4395. 'username' => $username,
  4396. 'hostname' => $hostname,
  4397. 'dbname' => '',
  4398. 'tablename' => '',
  4399. ]
  4400. )
  4401. . '">\'' . htmlspecialchars($username)
  4402. . '\'@\'' . htmlspecialchars($hostname)
  4403. . '\'</a></i>' . "\n";
  4404. $html_output .= ' - ';
  4405. $html_output .= $dbname_is_wildcard
  4406. || is_array($dbname) && count($dbname) > 1
  4407. ? __('Databases') : __('Database');
  4408. if (! empty($entity_name) && $entity_type === 'table') {
  4409. $html_output .= ' <i><a href="server_privileges.php'
  4410. . Url::getCommon(
  4411. [
  4412. 'username' => $username,
  4413. 'hostname' => $hostname,
  4414. 'dbname' => $url_dbname,
  4415. 'tablename' => '',
  4416. ]
  4417. )
  4418. . '">' . htmlspecialchars($dbname)
  4419. . '</a></i>';
  4420. $html_output .= ' - ' . __('Table')
  4421. . ' <i>' . htmlspecialchars($entity_name) . '</i>';
  4422. } elseif (! empty($entity_name)) {
  4423. $html_output .= ' <i><a href="server_privileges.php'
  4424. . Url::getCommon(
  4425. [
  4426. 'username' => $username,
  4427. 'hostname' => $hostname,
  4428. 'dbname' => $url_dbname,
  4429. 'routinename' => '',
  4430. ]
  4431. )
  4432. . '">' . htmlspecialchars($dbname)
  4433. . '</a></i>';
  4434. $html_output .= ' - ' . __('Routine')
  4435. . ' <i>' . htmlspecialchars($entity_name) . '</i>';
  4436. } else {
  4437. if (! is_array($dbname)) {
  4438. $dbname = [$dbname];
  4439. }
  4440. $html_output .= ' <i>'
  4441. . htmlspecialchars(implode(', ', $dbname))
  4442. . '</i>';
  4443. }
  4444. } else {
  4445. $html_output .= ' <i>\'' . htmlspecialchars($username)
  4446. . '\'@\'' . htmlspecialchars($hostname)
  4447. . '\'</i>' . "\n";
  4448. }
  4449. $html_output .= '</h2>' . "\n";
  4450. $cur_user = $this->dbi->getCurrentUser();
  4451. $user = $username . '@' . $hostname;
  4452. // Add a short notice for the user
  4453. // to remind him that he is editing his own privileges
  4454. if ($user === $cur_user) {
  4455. $html_output .= Message::notice(
  4456. __(
  4457. 'Note: You are attempting to edit privileges of the '
  4458. . 'user with which you are currently logged in.'
  4459. )
  4460. )->getDisplay();
  4461. }
  4462. return $html_output;
  4463. }
  4464. /**
  4465. * Get HTML snippet for display user overview page
  4466. *
  4467. * @param string $pmaThemeImage a image source link
  4468. * @param string $text_dir text directory
  4469. *
  4470. * @return string
  4471. */
  4472. public function getHtmlForUserOverview($pmaThemeImage, $text_dir)
  4473. {
  4474. $html_output = '<h2>' . "\n"
  4475. . Util::getIcon('b_usrlist')
  4476. . __('User accounts overview') . "\n"
  4477. . '</h2>' . "\n";
  4478. $password_column = 'Password';
  4479. $server_type = Util::getServerType();
  4480. $serverVersion = $this->dbi->getVersion();
  4481. if (($server_type == 'MySQL' || $server_type == 'Percona Server')
  4482. && $serverVersion >= 50706
  4483. ) {
  4484. $password_column = 'authentication_string';
  4485. }
  4486. // $sql_query is for the initial-filtered,
  4487. // $sql_query_all is for counting the total no. of users
  4488. $sql_query = $sql_query_all = 'SELECT *,' .
  4489. " IF(`" . $password_column . "` = _latin1 '', 'N', 'Y') AS 'Password'" .
  4490. ' FROM `mysql`.`user`';
  4491. $sql_query .= (isset($_GET['initial'])
  4492. ? $this->rangeOfUsers($_GET['initial'])
  4493. : '');
  4494. $sql_query .= ' ORDER BY `User` ASC, `Host` ASC;';
  4495. $sql_query_all .= ' ;';
  4496. $res = $this->dbi->tryQuery(
  4497. $sql_query,
  4498. DatabaseInterface::CONNECT_USER,
  4499. DatabaseInterface::QUERY_STORE
  4500. );
  4501. $res_all = $this->dbi->tryQuery(
  4502. $sql_query_all,
  4503. DatabaseInterface::CONNECT_USER,
  4504. DatabaseInterface::QUERY_STORE
  4505. );
  4506. if (! $res) {
  4507. // the query failed! This may have two reasons:
  4508. // - the user does not have enough privileges
  4509. // - the privilege tables use a structure of an earlier version.
  4510. // so let's try a more simple query
  4511. $this->dbi->freeResult($res);
  4512. $this->dbi->freeResult($res_all);
  4513. $sql_query = 'SELECT * FROM `mysql`.`user`';
  4514. $res = $this->dbi->tryQuery(
  4515. $sql_query,
  4516. DatabaseInterface::CONNECT_USER,
  4517. DatabaseInterface::QUERY_STORE
  4518. );
  4519. if (! $res) {
  4520. $html_output .= $this->getHtmlForViewUsersError();
  4521. $html_output .= $this->getAddUserHtmlFieldset();
  4522. } else {
  4523. // This message is hardcoded because I will replace it by
  4524. // a automatic repair feature soon.
  4525. $raw = 'Your privilege table structure seems to be older than'
  4526. . ' this MySQL version!<br>'
  4527. . 'Please run the <code>mysql_upgrade</code> command'
  4528. . ' that should be included in your MySQL server distribution'
  4529. . ' to solve this problem!';
  4530. $html_output .= Message::rawError($raw)->getDisplay();
  4531. }
  4532. $this->dbi->freeResult($res);
  4533. } else {
  4534. $db_rights = $this->getDbRightsForUserOverview();
  4535. // for all initials, even non A-Z
  4536. $array_initials = [];
  4537. foreach ($db_rights as $right) {
  4538. foreach ($right as $account) {
  4539. if (empty($account['User']) && $account['Host'] == 'localhost') {
  4540. $html_output .= Message::notice(
  4541. __(
  4542. 'A user account allowing any user from localhost to '
  4543. . 'connect is present. This will prevent other users '
  4544. . 'from connecting if the host part of their account '
  4545. . 'allows a connection from any (%) host.'
  4546. )
  4547. . Util::showMySQLDocu('problems-connecting')
  4548. )->getDisplay();
  4549. break 2;
  4550. }
  4551. }
  4552. }
  4553. /**
  4554. * Displays the initials
  4555. * Also not necessary if there is less than 20 privileges
  4556. */
  4557. if ($this->dbi->numRows($res_all) > 20) {
  4558. $html_output .= $this->getHtmlForInitials($array_initials);
  4559. }
  4560. /**
  4561. * Display the user overview
  4562. * (if less than 50 users, display them immediately)
  4563. */
  4564. if (isset($_GET['initial'])
  4565. || isset($_GET['showall'])
  4566. || $this->dbi->numRows($res) < 50
  4567. ) {
  4568. $html_output .= $this->getUsersOverview(
  4569. $res,
  4570. $db_rights,
  4571. $pmaThemeImage,
  4572. $text_dir
  4573. );
  4574. } else {
  4575. $html_output .= $this->getAddUserHtmlFieldset();
  4576. } // end if (display overview)
  4577. $response = Response::getInstance();
  4578. if (! $response->isAjax()
  4579. || ! empty($_REQUEST['ajax_page_request'])
  4580. ) {
  4581. if ($GLOBALS['is_reload_priv']) {
  4582. $flushnote = new Message(
  4583. __(
  4584. 'Note: phpMyAdmin gets the users’ privileges directly '
  4585. . 'from MySQL’s privilege tables. The content of these '
  4586. . 'tables may differ from the privileges the server uses, '
  4587. . 'if they have been changed manually. In this case, '
  4588. . 'you should %sreload the privileges%s before you continue.'
  4589. ),
  4590. Message::NOTICE
  4591. );
  4592. $flushnote->addParamHtml(
  4593. '<a href="server_privileges.php'
  4594. . Url::getCommon(['flush_privileges' => 1])
  4595. . '" id="reload_privileges_anchor">'
  4596. );
  4597. $flushnote->addParamHtml('</a>');
  4598. } else {
  4599. $flushnote = new Message(
  4600. __(
  4601. 'Note: phpMyAdmin gets the users’ privileges directly '
  4602. . 'from MySQL’s privilege tables. The content of these '
  4603. . 'tables may differ from the privileges the server uses, '
  4604. . 'if they have been changed manually. In this case, '
  4605. . 'the privileges have to be reloaded but currently, you '
  4606. . 'don\'t have the RELOAD privilege.'
  4607. )
  4608. . Util::showMySQLDocu(
  4609. 'privileges-provided',
  4610. false,
  4611. null,
  4612. null,
  4613. 'priv_reload'
  4614. ),
  4615. Message::NOTICE
  4616. );
  4617. }
  4618. $html_output .= $flushnote->getDisplay();
  4619. }
  4620. }
  4621. return $html_output;
  4622. }
  4623. /**
  4624. * Get HTML snippet for display user properties
  4625. *
  4626. * @param boolean $dbname_is_wildcard whether database name is wildcard or not
  4627. * @param string $url_dbname url database name that urlencode() string
  4628. * @param string $username username
  4629. * @param string $hostname host name
  4630. * @param string $dbname database name
  4631. * @param string $tablename table name
  4632. *
  4633. * @return string
  4634. */
  4635. public function getHtmlForUserProperties(
  4636. $dbname_is_wildcard,
  4637. $url_dbname,
  4638. $username,
  4639. $hostname,
  4640. $dbname,
  4641. $tablename
  4642. ) {
  4643. $html_output = '<div id="edit_user_dialog">';
  4644. $html_output .= $this->getHtmlHeaderForUserProperties(
  4645. $dbname_is_wildcard,
  4646. $url_dbname,
  4647. $dbname,
  4648. $username,
  4649. $hostname,
  4650. $tablename,
  4651. 'table'
  4652. );
  4653. $sql = "SELECT '1' FROM `mysql`.`user`"
  4654. . " WHERE `User` = '" . $this->dbi->escapeString($username) . "'"
  4655. . " AND `Host` = '" . $this->dbi->escapeString($hostname) . "';";
  4656. $user_does_not_exists = (bool) ! $this->dbi->fetchValue($sql);
  4657. if ($user_does_not_exists) {
  4658. $html_output .= Message::error(
  4659. __('The selected user was not found in the privilege table.')
  4660. )->getDisplay();
  4661. $html_output .= $this->getHtmlForLoginInformationFields();
  4662. }
  4663. $_params = [
  4664. 'username' => $username,
  4665. 'hostname' => $hostname,
  4666. ];
  4667. if (! is_array($dbname) && strlen($dbname) > 0) {
  4668. $_params['dbname'] = $dbname;
  4669. if (strlen($tablename) > 0) {
  4670. $_params['tablename'] = $tablename;
  4671. }
  4672. } else {
  4673. $_params['dbname'] = $dbname;
  4674. }
  4675. $html_output .= '<form class="submenu-item" name="usersForm" '
  4676. . 'id="addUsersForm" action="server_privileges.php" method="post">' . "\n";
  4677. $html_output .= Url::getHiddenInputs($_params);
  4678. $html_output .= $this->getHtmlToDisplayPrivilegesTable(
  4679. // If $dbname is an array, pass any one db as all have same privs.
  4680. Core::ifSetOr($dbname, is_array($dbname) ? $dbname[0] : '*', 'length'),
  4681. Core::ifSetOr($tablename, '*', 'length')
  4682. );
  4683. $html_output .= '</form>' . "\n";
  4684. if (! is_array($dbname) && strlen($tablename) === 0
  4685. && empty($dbname_is_wildcard)
  4686. ) {
  4687. // no table name was given, display all table specific rights
  4688. // but only if $dbname contains no wildcards
  4689. if (strlen($dbname) === 0) {
  4690. $html_output .= $this->getHtmlForAllTableSpecificRights(
  4691. $username,
  4692. $hostname,
  4693. 'database'
  4694. );
  4695. } else {
  4696. // unescape wildcards in dbname at table level
  4697. $unescaped_db = Util::unescapeMysqlWildcards($dbname);
  4698. $html_output .= $this->getHtmlForAllTableSpecificRights(
  4699. $username,
  4700. $hostname,
  4701. 'table',
  4702. $unescaped_db
  4703. );
  4704. $html_output .= $this->getHtmlForAllTableSpecificRights(
  4705. $username,
  4706. $hostname,
  4707. 'routine',
  4708. $unescaped_db
  4709. );
  4710. }
  4711. }
  4712. // Provide a line with links to the relevant database and table
  4713. if (! is_array($dbname) && strlen($dbname) > 0 && empty($dbname_is_wildcard)) {
  4714. $html_output .= $this->getLinkToDbAndTable($url_dbname, $dbname, $tablename);
  4715. }
  4716. if (! is_array($dbname) && strlen($dbname) === 0 && ! $user_does_not_exists) {
  4717. //change login information
  4718. $html_output .= ChangePassword::getHtml(
  4719. 'edit_other',
  4720. $username,
  4721. $hostname
  4722. );
  4723. $html_output .= $this->getChangeLoginInformationHtmlForm($username, $hostname);
  4724. }
  4725. $html_output .= '</div>';
  4726. return $html_output;
  4727. }
  4728. /**
  4729. * Get queries for Table privileges to change or copy user
  4730. *
  4731. * @param string $user_host_condition user host condition to
  4732. * select relevant table privileges
  4733. * @param array $queries queries array
  4734. * @param string $username username
  4735. * @param string $hostname host name
  4736. *
  4737. * @return array
  4738. */
  4739. public function getTablePrivsQueriesForChangeOrCopyUser(
  4740. $user_host_condition,
  4741. array $queries,
  4742. $username,
  4743. $hostname
  4744. ) {
  4745. $res = $this->dbi->query(
  4746. 'SELECT `Db`, `Table_name`, `Table_priv` FROM `mysql`.`tables_priv`'
  4747. . $user_host_condition,
  4748. DatabaseInterface::CONNECT_USER,
  4749. DatabaseInterface::QUERY_STORE
  4750. );
  4751. while ($row = $this->dbi->fetchAssoc($res)) {
  4752. $res2 = $this->dbi->query(
  4753. 'SELECT `Column_name`, `Column_priv`'
  4754. . ' FROM `mysql`.`columns_priv`'
  4755. . ' WHERE `User`'
  4756. . ' = \'' . $this->dbi->escapeString($_POST['old_username']) . "'"
  4757. . ' AND `Host`'
  4758. . ' = \'' . $this->dbi->escapeString($_POST['old_username']) . '\''
  4759. . ' AND `Db`'
  4760. . ' = \'' . $this->dbi->escapeString($row['Db']) . "'"
  4761. . ' AND `Table_name`'
  4762. . ' = \'' . $this->dbi->escapeString($row['Table_name']) . "'"
  4763. . ';',
  4764. DatabaseInterface::CONNECT_USER,
  4765. DatabaseInterface::QUERY_STORE
  4766. );
  4767. $tmp_privs1 = $this->extractPrivInfo($row);
  4768. $tmp_privs2 = [
  4769. 'Select' => [],
  4770. 'Insert' => [],
  4771. 'Update' => [],
  4772. 'References' => [],
  4773. ];
  4774. while ($row2 = $this->dbi->fetchAssoc($res2)) {
  4775. $tmp_array = explode(',', $row2['Column_priv']);
  4776. if (in_array('Select', $tmp_array)) {
  4777. $tmp_privs2['Select'][] = $row2['Column_name'];
  4778. }
  4779. if (in_array('Insert', $tmp_array)) {
  4780. $tmp_privs2['Insert'][] = $row2['Column_name'];
  4781. }
  4782. if (in_array('Update', $tmp_array)) {
  4783. $tmp_privs2['Update'][] = $row2['Column_name'];
  4784. }
  4785. if (in_array('References', $tmp_array)) {
  4786. $tmp_privs2['References'][] = $row2['Column_name'];
  4787. }
  4788. }
  4789. if (count($tmp_privs2['Select']) > 0 && ! in_array('SELECT', $tmp_privs1)) {
  4790. $tmp_privs1[] = 'SELECT (`' . implode('`, `', $tmp_privs2['Select']) . '`)';
  4791. }
  4792. if (count($tmp_privs2['Insert']) > 0 && ! in_array('INSERT', $tmp_privs1)) {
  4793. $tmp_privs1[] = 'INSERT (`' . implode('`, `', $tmp_privs2['Insert']) . '`)';
  4794. }
  4795. if (count($tmp_privs2['Update']) > 0 && ! in_array('UPDATE', $tmp_privs1)) {
  4796. $tmp_privs1[] = 'UPDATE (`' . implode('`, `', $tmp_privs2['Update']) . '`)';
  4797. }
  4798. if (count($tmp_privs2['References']) > 0
  4799. && ! in_array('REFERENCES', $tmp_privs1)
  4800. ) {
  4801. $tmp_privs1[]
  4802. = 'REFERENCES (`' . implode('`, `', $tmp_privs2['References']) . '`)';
  4803. }
  4804. $queries[] = 'GRANT ' . implode(', ', $tmp_privs1)
  4805. . ' ON ' . Util::backquote($row['Db']) . '.'
  4806. . Util::backquote($row['Table_name'])
  4807. . ' TO \'' . $this->dbi->escapeString($username)
  4808. . '\'@\'' . $this->dbi->escapeString($hostname) . '\''
  4809. . (in_array('Grant', explode(',', $row['Table_priv']))
  4810. ? ' WITH GRANT OPTION;'
  4811. : ';');
  4812. }
  4813. return $queries;
  4814. }
  4815. /**
  4816. * Get queries for database specific privileges for change or copy user
  4817. *
  4818. * @param array $queries queries array with string
  4819. * @param string $username username
  4820. * @param string $hostname host name
  4821. *
  4822. * @return array
  4823. */
  4824. public function getDbSpecificPrivsQueriesForChangeOrCopyUser(
  4825. array $queries,
  4826. $username,
  4827. $hostname
  4828. ) {
  4829. $user_host_condition = ' WHERE `User`'
  4830. . ' = \'' . $this->dbi->escapeString($_POST['old_username']) . "'"
  4831. . ' AND `Host`'
  4832. . ' = \'' . $this->dbi->escapeString($_POST['old_hostname']) . '\';';
  4833. $res = $this->dbi->query(
  4834. 'SELECT * FROM `mysql`.`db`' . $user_host_condition
  4835. );
  4836. while ($row = $this->dbi->fetchAssoc($res)) {
  4837. $queries[] = 'GRANT ' . implode(', ', $this->extractPrivInfo($row))
  4838. . ' ON ' . Util::backquote($row['Db']) . '.*'
  4839. . ' TO \'' . $this->dbi->escapeString($username)
  4840. . '\'@\'' . $this->dbi->escapeString($hostname) . '\''
  4841. . ($row['Grant_priv'] == 'Y' ? ' WITH GRANT OPTION;' : ';');
  4842. }
  4843. $this->dbi->freeResult($res);
  4844. $queries = $this->getTablePrivsQueriesForChangeOrCopyUser(
  4845. $user_host_condition,
  4846. $queries,
  4847. $username,
  4848. $hostname
  4849. );
  4850. return $queries;
  4851. }
  4852. /**
  4853. * Prepares queries for adding users and
  4854. * also create database and return query and message
  4855. *
  4856. * @param boolean $_error whether user create or not
  4857. * @param string $real_sql_query SQL query for add a user
  4858. * @param string $sql_query SQL query to be displayed
  4859. * @param string $username username
  4860. * @param string $hostname host name
  4861. * @param string $dbname database name
  4862. * @param string $alter_real_sql_query SQL query for ALTER USER
  4863. * @param string $alter_sql_query SQL query for ALTER USER to be displayed
  4864. *
  4865. * @return array, $message
  4866. */
  4867. public function addUserAndCreateDatabase(
  4868. $_error,
  4869. $real_sql_query,
  4870. $sql_query,
  4871. $username,
  4872. $hostname,
  4873. $dbname,
  4874. $alter_real_sql_query,
  4875. $alter_sql_query
  4876. ) {
  4877. if ($_error || (! empty($real_sql_query)
  4878. && ! $this->dbi->tryQuery($real_sql_query))
  4879. ) {
  4880. $_POST['createdb-1'] = $_POST['createdb-2']
  4881. = $_POST['createdb-3'] = null;
  4882. $message = Message::rawError($this->dbi->getError());
  4883. } elseif ($alter_real_sql_query !== '' && ! $this->dbi->tryQuery($alter_real_sql_query)) {
  4884. $_POST['createdb-1'] = $_POST['createdb-2']
  4885. = $_POST['createdb-3'] = null;
  4886. $message = Message::rawError($this->dbi->getError());
  4887. } else {
  4888. $sql_query .= $alter_sql_query;
  4889. $message = Message::success(__('You have added a new user.'));
  4890. }
  4891. if (isset($_POST['createdb-1'])) {
  4892. // Create database with same name and grant all privileges
  4893. $q = 'CREATE DATABASE IF NOT EXISTS '
  4894. . Util::backquote(
  4895. $this->dbi->escapeString($username)
  4896. ) . ';';
  4897. $sql_query .= $q;
  4898. if (! $this->dbi->tryQuery($q)) {
  4899. $message = Message::rawError($this->dbi->getError());
  4900. }
  4901. /**
  4902. * Reload the navigation
  4903. */
  4904. $GLOBALS['reload'] = true;
  4905. $GLOBALS['db'] = $username;
  4906. $q = 'GRANT ALL PRIVILEGES ON '
  4907. . Util::backquote(
  4908. Util::escapeMysqlWildcards(
  4909. $this->dbi->escapeString($username)
  4910. )
  4911. ) . '.* TO \''
  4912. . $this->dbi->escapeString($username)
  4913. . '\'@\'' . $this->dbi->escapeString($hostname) . '\';';
  4914. $sql_query .= $q;
  4915. if (! $this->dbi->tryQuery($q)) {
  4916. $message = Message::rawError($this->dbi->getError());
  4917. }
  4918. }
  4919. if (isset($_POST['createdb-2'])) {
  4920. // Grant all privileges on wildcard name (username\_%)
  4921. $q = 'GRANT ALL PRIVILEGES ON '
  4922. . Util::backquote(
  4923. Util::escapeMysqlWildcards(
  4924. $this->dbi->escapeString($username)
  4925. ) . '\_%'
  4926. ) . '.* TO \''
  4927. . $this->dbi->escapeString($username)
  4928. . '\'@\'' . $this->dbi->escapeString($hostname) . '\';';
  4929. $sql_query .= $q;
  4930. if (! $this->dbi->tryQuery($q)) {
  4931. $message = Message::rawError($this->dbi->getError());
  4932. }
  4933. }
  4934. if (isset($_POST['createdb-3'])) {
  4935. // Grant all privileges on the specified database to the new user
  4936. $q = 'GRANT ALL PRIVILEGES ON '
  4937. . Util::backquote(
  4938. $this->dbi->escapeString($dbname)
  4939. ) . '.* TO \''
  4940. . $this->dbi->escapeString($username)
  4941. . '\'@\'' . $this->dbi->escapeString($hostname) . '\';';
  4942. $sql_query .= $q;
  4943. if (! $this->dbi->tryQuery($q)) {
  4944. $message = Message::rawError($this->dbi->getError());
  4945. }
  4946. }
  4947. return [
  4948. $sql_query,
  4949. $message,
  4950. ];
  4951. }
  4952. /**
  4953. * Get the hashed string for password
  4954. *
  4955. * @param string $password password
  4956. *
  4957. * @return string
  4958. */
  4959. public function getHashedPassword($password)
  4960. {
  4961. $password = $this->dbi->escapeString($password);
  4962. $result = $this->dbi->fetchSingleRow(
  4963. "SELECT PASSWORD('" . $password . "') AS `password`;"
  4964. );
  4965. return $result['password'];
  4966. }
  4967. /**
  4968. * Check if MariaDB's 'simple_password_check'
  4969. * OR 'cracklib_password_check' is ACTIVE
  4970. *
  4971. * @return boolean if atleast one of the plugins is ACTIVE
  4972. */
  4973. public function checkIfMariaDBPwdCheckPluginActive()
  4974. {
  4975. $serverVersion = $this->dbi->getVersion();
  4976. if (! (Util::getServerType() == 'MariaDB' && $serverVersion >= 100002)) {
  4977. return false;
  4978. }
  4979. $result = $this->dbi->tryQuery(
  4980. 'SHOW PLUGINS SONAME LIKE \'%_password_check%\''
  4981. );
  4982. /* Plugins are not working, for example directory does not exists */
  4983. if ($result === false) {
  4984. return false;
  4985. }
  4986. while ($row = $this->dbi->fetchAssoc($result)) {
  4987. if ($row['Status'] === 'ACTIVE') {
  4988. return true;
  4989. }
  4990. }
  4991. return false;
  4992. }
  4993. /**
  4994. * Get SQL queries for Display and Add user
  4995. *
  4996. * @param string $username username
  4997. * @param string $hostname host name
  4998. * @param string $password password
  4999. *
  5000. * @return array ($create_user_real, $create_user_show, $real_sql_query, $sql_query
  5001. * $password_set_real, $password_set_show, $alter_real_sql_query, $alter_sql_query)
  5002. */
  5003. public function getSqlQueriesForDisplayAndAddUser($username, $hostname, $password)
  5004. {
  5005. $slashedUsername = $this->dbi->escapeString($username);
  5006. $slashedHostname = $this->dbi->escapeString($hostname);
  5007. $slashedPassword = $this->dbi->escapeString($password);
  5008. $serverType = Util::getServerType();
  5009. $serverVersion = $this->dbi->getVersion();
  5010. $create_user_stmt = sprintf(
  5011. 'CREATE USER \'%s\'@\'%s\'',
  5012. $slashedUsername,
  5013. $slashedHostname
  5014. );
  5015. $isMariaDBPwdPluginActive = $this->checkIfMariaDBPwdCheckPluginActive();
  5016. // See https://github.com/phpmyadmin/phpmyadmin/pull/11560#issuecomment-147158219
  5017. // for details regarding details of syntax usage for various versions
  5018. // 'IDENTIFIED WITH auth_plugin'
  5019. // is supported by MySQL 5.5.7+
  5020. if (($serverType == 'MySQL' || $serverType == 'Percona Server')
  5021. && $serverVersion >= 50507
  5022. && isset($_POST['authentication_plugin'])
  5023. ) {
  5024. $create_user_stmt .= ' IDENTIFIED WITH '
  5025. . $_POST['authentication_plugin'];
  5026. }
  5027. // 'IDENTIFIED VIA auth_plugin'
  5028. // is supported by MariaDB 5.2+
  5029. if ($serverType == 'MariaDB'
  5030. && $serverVersion >= 50200
  5031. && isset($_POST['authentication_plugin'])
  5032. && ! $isMariaDBPwdPluginActive
  5033. ) {
  5034. $create_user_stmt .= ' IDENTIFIED VIA '
  5035. . $_POST['authentication_plugin'];
  5036. }
  5037. $create_user_real = $create_user_stmt;
  5038. $create_user_show = $create_user_stmt;
  5039. $password_set_stmt = 'SET PASSWORD FOR \'%s\'@\'%s\' = \'%s\'';
  5040. $password_set_show = sprintf(
  5041. $password_set_stmt,
  5042. $slashedUsername,
  5043. $slashedHostname,
  5044. '***'
  5045. );
  5046. $sql_query_stmt = sprintf(
  5047. 'GRANT %s ON *.* TO \'%s\'@\'%s\'',
  5048. implode(', ', $this->extractPrivInfo()),
  5049. $slashedUsername,
  5050. $slashedHostname
  5051. );
  5052. $real_sql_query = $sql_query = $sql_query_stmt;
  5053. // Set the proper hashing method
  5054. if (isset($_POST['authentication_plugin'])) {
  5055. $this->setProperPasswordHashing(
  5056. $_POST['authentication_plugin']
  5057. );
  5058. }
  5059. // Use 'CREATE USER ... WITH ... AS ..' syntax for
  5060. // newer MySQL versions
  5061. // and 'CREATE USER ... VIA .. USING ..' syntax for
  5062. // newer MariaDB versions
  5063. if ((($serverType == 'MySQL' || $serverType == 'Percona Server')
  5064. && $serverVersion >= 50706)
  5065. || ($serverType == 'MariaDB'
  5066. && $serverVersion >= 50200)
  5067. ) {
  5068. $password_set_real = null;
  5069. // Required for binding '%' with '%s'
  5070. $create_user_stmt = str_replace(
  5071. '%',
  5072. '%%',
  5073. $create_user_stmt
  5074. );
  5075. // MariaDB uses 'USING' whereas MySQL uses 'AS'
  5076. // but MariaDB with validation plugin needs cleartext password
  5077. if ($serverType == 'MariaDB'
  5078. && ! $isMariaDBPwdPluginActive
  5079. ) {
  5080. $create_user_stmt .= ' USING \'%s\'';
  5081. } elseif ($serverType == 'MariaDB') {
  5082. $create_user_stmt .= ' IDENTIFIED BY \'%s\'';
  5083. } elseif (($serverType == 'MySQL' || $serverType == 'Percona Server') && $serverVersion >= 80011) {
  5084. if (mb_strpos($create_user_stmt, 'IDENTIFIED') === false) {
  5085. // Maybe the authentication_plugin was not posted and then a part is missing
  5086. $create_user_stmt .= ' IDENTIFIED BY \'%s\'';
  5087. } else {
  5088. $create_user_stmt .= ' BY \'%s\'';
  5089. }
  5090. } else {
  5091. $create_user_stmt .= ' AS \'%s\'';
  5092. }
  5093. if ($_POST['pred_password'] == 'keep') {
  5094. $create_user_real = sprintf(
  5095. $create_user_stmt,
  5096. $slashedPassword
  5097. );
  5098. $create_user_show = sprintf(
  5099. $create_user_stmt,
  5100. '***'
  5101. );
  5102. } elseif ($_POST['pred_password'] == 'none') {
  5103. $create_user_real = sprintf(
  5104. $create_user_stmt,
  5105. null
  5106. );
  5107. $create_user_show = sprintf(
  5108. $create_user_stmt,
  5109. '***'
  5110. );
  5111. } else {
  5112. if (! (($serverType == 'MariaDB' && $isMariaDBPwdPluginActive)
  5113. || ($serverType == 'MySQL' || $serverType == 'Percona Server') && $serverVersion >= 80011)) {
  5114. $hashedPassword = $this->getHashedPassword($_POST['pma_pw']);
  5115. } else {
  5116. // MariaDB with validation plugin needs cleartext password
  5117. $hashedPassword = $_POST['pma_pw'];
  5118. }
  5119. $create_user_real = sprintf(
  5120. $create_user_stmt,
  5121. $hashedPassword
  5122. );
  5123. $create_user_show = sprintf(
  5124. $create_user_stmt,
  5125. '***'
  5126. );
  5127. }
  5128. } else {
  5129. // Use 'SET PASSWORD' syntax for pre-5.7.6 MySQL versions
  5130. // and pre-5.2.0 MariaDB versions
  5131. if ($_POST['pred_password'] == 'keep') {
  5132. $password_set_real = sprintf(
  5133. $password_set_stmt,
  5134. $slashedUsername,
  5135. $slashedHostname,
  5136. $slashedPassword
  5137. );
  5138. } elseif ($_POST['pred_password'] == 'none') {
  5139. $password_set_real = sprintf(
  5140. $password_set_stmt,
  5141. $slashedUsername,
  5142. $slashedHostname,
  5143. null
  5144. );
  5145. } else {
  5146. $hashedPassword = $this->getHashedPassword($_POST['pma_pw']);
  5147. $password_set_real = sprintf(
  5148. $password_set_stmt,
  5149. $slashedUsername,
  5150. $slashedHostname,
  5151. $hashedPassword
  5152. );
  5153. }
  5154. }
  5155. $alter_real_sql_query = '';
  5156. $alter_sql_query = '';
  5157. if (($serverType == 'MySQL' || $serverType == 'Percona Server') && $serverVersion >= 80011) {
  5158. $sql_query_stmt = '';
  5159. if ((isset($_POST['Grant_priv']) && $_POST['Grant_priv'] == 'Y')
  5160. || (isset($GLOBALS['Grant_priv']) && $GLOBALS['Grant_priv'] == 'Y')
  5161. ) {
  5162. $sql_query_stmt = ' WITH GRANT OPTION';
  5163. }
  5164. $real_sql_query .= $sql_query_stmt;
  5165. $sql_query .= $sql_query_stmt;
  5166. $alter_sql_query_stmt = sprintf(
  5167. 'ALTER USER \'%s\'@\'%s\'',
  5168. $slashedUsername,
  5169. $slashedHostname
  5170. );
  5171. $alter_real_sql_query = $alter_sql_query_stmt;
  5172. $alter_sql_query = $alter_sql_query_stmt;
  5173. }
  5174. // add REQUIRE clause
  5175. $require_clause = $this->getRequireClause();
  5176. $with_clause = $this->getWithClauseForAddUserAndUpdatePrivs();
  5177. if (($serverType == 'MySQL' || $serverType == 'Percona Server') && $serverVersion >= 80011) {
  5178. $alter_real_sql_query .= $require_clause;
  5179. $alter_sql_query .= $require_clause;
  5180. $alter_real_sql_query .= $with_clause;
  5181. $alter_sql_query .= $with_clause;
  5182. } else {
  5183. $real_sql_query .= $require_clause;
  5184. $sql_query .= $require_clause;
  5185. $real_sql_query .= $with_clause;
  5186. $sql_query .= $with_clause;
  5187. }
  5188. if ($alter_real_sql_query !== '') {
  5189. $alter_real_sql_query .= ';';
  5190. $alter_sql_query .= ';';
  5191. }
  5192. $create_user_real .= ';';
  5193. $create_user_show .= ';';
  5194. $real_sql_query .= ';';
  5195. $sql_query .= ';';
  5196. // No Global GRANT_OPTION privilege
  5197. if (! $GLOBALS['is_grantuser']) {
  5198. $real_sql_query = '';
  5199. $sql_query = '';
  5200. }
  5201. // Use 'SET PASSWORD' for pre-5.7.6 MySQL versions
  5202. // and pre-5.2.0 MariaDB
  5203. if (($serverType == 'MySQL'
  5204. && $serverVersion >= 50706)
  5205. || ($serverType == 'MariaDB'
  5206. && $serverVersion >= 50200)
  5207. ) {
  5208. $password_set_real = null;
  5209. $password_set_show = null;
  5210. } else {
  5211. if ($password_set_real !== null) {
  5212. $password_set_real .= ";";
  5213. }
  5214. $password_set_show .= ";";
  5215. }
  5216. return [
  5217. $create_user_real,
  5218. $create_user_show,
  5219. $real_sql_query,
  5220. $sql_query,
  5221. $password_set_real,
  5222. $password_set_show,
  5223. $alter_real_sql_query,
  5224. $alter_sql_query,
  5225. ];
  5226. }
  5227. /**
  5228. * Returns the type ('PROCEDURE' or 'FUNCTION') of the routine
  5229. *
  5230. * @param string $dbname database
  5231. * @param string $routineName routine
  5232. *
  5233. * @return string type
  5234. */
  5235. public function getRoutineType($dbname, $routineName)
  5236. {
  5237. $routineData = $this->dbi->getRoutines($dbname);
  5238. foreach ($routineData as $routine) {
  5239. if ($routine['name'] === $routineName) {
  5240. return $routine['type'];
  5241. }
  5242. }
  5243. return '';
  5244. }
  5245. }