Privileges.php 198 KB

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