Privileges.php 194 KB

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