Privileges.php 197 KB

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