Privileges.php 131 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791
  1. <?php
  2. /**
  3. * set of functions with the Privileges section in pma
  4. */
  5. declare(strict_types=1);
  6. namespace PhpMyAdmin\Server;
  7. use mysqli_stmt;
  8. use PhpMyAdmin\ConfigStorage\Features\ConfigurableMenusFeature;
  9. use PhpMyAdmin\ConfigStorage\Relation;
  10. use PhpMyAdmin\ConfigStorage\RelationCleanup;
  11. use PhpMyAdmin\DatabaseInterface;
  12. use PhpMyAdmin\Dbal\MysqliResult;
  13. use PhpMyAdmin\Dbal\ResultInterface;
  14. use PhpMyAdmin\Html\Generator;
  15. use PhpMyAdmin\Html\MySQLDocumentation;
  16. use PhpMyAdmin\Message;
  17. use PhpMyAdmin\Query\Compatibility;
  18. use PhpMyAdmin\ResponseRenderer;
  19. use PhpMyAdmin\Template;
  20. use PhpMyAdmin\Url;
  21. use PhpMyAdmin\Util;
  22. use function __;
  23. use function array_filter;
  24. use function array_keys;
  25. use function array_map;
  26. use function array_merge;
  27. use function array_unique;
  28. use function count;
  29. use function explode;
  30. use function htmlspecialchars;
  31. use function implode;
  32. use function in_array;
  33. use function is_array;
  34. use function is_string;
  35. use function json_decode;
  36. use function ksort;
  37. use function max;
  38. use function mb_chr;
  39. use function mb_strpos;
  40. use function mb_strrpos;
  41. use function mb_strtolower;
  42. use function mb_strtoupper;
  43. use function mb_substr;
  44. use function preg_match;
  45. use function preg_replace;
  46. use function sprintf;
  47. use function str_contains;
  48. use function str_replace;
  49. use function strlen;
  50. use function strtr;
  51. use function trim;
  52. use function uksort;
  53. /**
  54. * Privileges class
  55. */
  56. class Privileges
  57. {
  58. /** @var Template */
  59. public $template;
  60. /** @var RelationCleanup */
  61. private $relationCleanup;
  62. /** @var DatabaseInterface */
  63. public $dbi;
  64. /** @var Relation */
  65. public $relation;
  66. /** @var Plugins */
  67. private $plugins;
  68. /**
  69. * @param Template $template Template object
  70. * @param DatabaseInterface $dbi DatabaseInterface object
  71. * @param Relation $relation Relation object
  72. * @param RelationCleanup $relationCleanup RelationCleanup object
  73. */
  74. public function __construct(
  75. Template $template,
  76. $dbi,
  77. Relation $relation,
  78. RelationCleanup $relationCleanup,
  79. Plugins $plugins
  80. ) {
  81. $this->template = $template;
  82. $this->dbi = $dbi;
  83. $this->relation = $relation;
  84. $this->relationCleanup = $relationCleanup;
  85. $this->plugins = $plugins;
  86. }
  87. /**
  88. * Escapes wildcard in a database+table specification
  89. * before using it in a GRANT statement.
  90. *
  91. * Escaping a wildcard character in a GRANT is only accepted at the global
  92. * or database level, not at table level; this is why I remove
  93. * the escaping character. Internally, in mysql.tables_priv.Db there are
  94. * no escaping (for example test_db) but in mysql.db you'll see test\_db
  95. * for a db-specific privilege.
  96. *
  97. * @param string $dbname Database name
  98. * @param string $tablename Table name
  99. *
  100. * @return string the escaped (if necessary) database.table
  101. */
  102. public function wildcardEscapeForGrant(string $dbname, string $tablename): string
  103. {
  104. if (strlen($dbname) === 0) {
  105. return '*.*';
  106. }
  107. if (strlen($tablename) > 0) {
  108. return Util::backquote(
  109. Util::unescapeMysqlWildcards($dbname)
  110. )
  111. . '.' . Util::backquote($tablename);
  112. }
  113. return Util::backquote($dbname) . '.*';
  114. }
  115. /**
  116. * Generates a condition on the user name
  117. *
  118. * @param string|null $initial the user's initial
  119. *
  120. * @return string the generated condition
  121. */
  122. public function rangeOfUsers(?string $initial = null)
  123. {
  124. if ($initial === null) {
  125. return '';
  126. }
  127. if ($initial === '') {
  128. return " WHERE `User` = ''";
  129. }
  130. $like = strtr($initial, ['_' => '\\_', '%' => '\\%', '\\' => '\\\\']) . '%';
  131. // strtolower() is used because the User field
  132. // might be BINARY, so LIKE would be case sensitive
  133. return " WHERE `User` LIKE '"
  134. . $this->dbi->escapeString($like) . "'"
  135. . " OR `User` LIKE '"
  136. . $this->dbi->escapeString(mb_strtolower($like))
  137. . "'";
  138. }
  139. /**
  140. * Parses privileges into an array, it modifies the array
  141. *
  142. * @param array $row Results row from
  143. */
  144. public function fillInTablePrivileges(array &$row): void
  145. {
  146. $row1 = $this->dbi->fetchSingleRow('SHOW COLUMNS FROM `mysql`.`tables_priv` LIKE \'Table_priv\';');
  147. // note: in MySQL 5.0.3 we get "Create View', 'Show view';
  148. // the View for Create is spelled with uppercase V
  149. // the view for Show is spelled with lowercase v
  150. // and there is a space between the words
  151. $avGrants = explode(
  152. '\',\'',
  153. mb_substr(
  154. $row1['Type'],
  155. mb_strpos($row1['Type'], '(') + 2,
  156. mb_strpos($row1['Type'], ')')
  157. - mb_strpos($row1['Type'], '(') - 3
  158. )
  159. );
  160. $usersGrants = explode(',', $row['Table_priv']);
  161. foreach ($avGrants as $currentGrant) {
  162. $row[$currentGrant . '_priv'] = in_array($currentGrant, $usersGrants) ? 'Y' : 'N';
  163. }
  164. unset($row['Table_priv']);
  165. }
  166. /**
  167. * Extracts the privilege information of a priv table row
  168. *
  169. * @param array|null $row the row
  170. * @param bool $enableHTML add <dfn> tag with tooltips
  171. * @param bool $tablePrivs whether row contains table privileges
  172. *
  173. * @return array
  174. *
  175. * @global resource $user_link the database connection
  176. */
  177. public function extractPrivInfo($row = null, $enableHTML = false, $tablePrivs = false)
  178. {
  179. if ($tablePrivs) {
  180. $grants = $this->getTableGrantsArray();
  181. } else {
  182. $grants = $this->getGrantsArray();
  183. }
  184. if ($row !== null && isset($row['Table_priv'])) {
  185. $this->fillInTablePrivileges($row);
  186. }
  187. $privs = [];
  188. $allPrivileges = true;
  189. foreach ($grants as $currentGrant) {
  190. if (
  191. ($row === null || ! isset($row[$currentGrant[0]]))
  192. && ($row !== null || ! isset($GLOBALS[$currentGrant[0]]))
  193. ) {
  194. continue;
  195. }
  196. if (
  197. ($row !== null && $row[$currentGrant[0]] === 'Y')
  198. || ($row === null
  199. && ($GLOBALS[$currentGrant[0]] === 'Y'
  200. || (is_array($GLOBALS[$currentGrant[0]])
  201. && count($GLOBALS[$currentGrant[0]]) == $_REQUEST['column_count']
  202. && empty($GLOBALS[$currentGrant[0] . '_none']))))
  203. ) {
  204. if ($enableHTML) {
  205. $privs[] = '<dfn title="' . $currentGrant[2] . '">'
  206. . $currentGrant[1] . '</dfn>';
  207. } else {
  208. $privs[] = $currentGrant[1];
  209. }
  210. } elseif (
  211. ! empty($GLOBALS[$currentGrant[0]])
  212. && is_array($GLOBALS[$currentGrant[0]])
  213. && empty($GLOBALS[$currentGrant[0] . '_none'])
  214. ) {
  215. // Required for proper escaping of ` (backtick) in a column name
  216. $grantCols = array_map(
  217. /**
  218. * @param string $val
  219. *
  220. * @return string
  221. */
  222. static function ($val) {
  223. return Util::backquote($val);
  224. },
  225. $GLOBALS[$currentGrant[0]]
  226. );
  227. if ($enableHTML) {
  228. $privs[] = '<dfn title="' . $currentGrant[2] . '">'
  229. . $currentGrant[1] . '</dfn>'
  230. . ' (' . implode(', ', $grantCols) . ')';
  231. } else {
  232. $privs[] = $currentGrant[1]
  233. . ' (' . implode(', ', $grantCols) . ')';
  234. }
  235. } else {
  236. $allPrivileges = false;
  237. }
  238. }
  239. if (empty($privs)) {
  240. if ($enableHTML) {
  241. $privs[] = '<dfn title="' . __('No privileges.') . '">USAGE</dfn>';
  242. } else {
  243. $privs[] = 'USAGE';
  244. }
  245. } elseif ($allPrivileges && (! isset($_POST['grant_count']) || count($privs) == $_POST['grant_count'])) {
  246. if ($enableHTML) {
  247. $privs = [
  248. '<dfn title="'
  249. . __('Includes all privileges except GRANT.')
  250. . '">ALL PRIVILEGES</dfn>',
  251. ];
  252. } else {
  253. $privs = ['ALL PRIVILEGES'];
  254. }
  255. }
  256. return $privs;
  257. }
  258. /**
  259. * Returns an array of table grants and their descriptions
  260. *
  261. * @return array array of table grants
  262. */
  263. public function getTableGrantsArray()
  264. {
  265. return [
  266. [
  267. 'Delete',
  268. 'DELETE',
  269. __('Allows deleting data.'),
  270. ],
  271. [
  272. 'Create',
  273. 'CREATE',
  274. __('Allows creating new tables.'),
  275. ],
  276. [
  277. 'Drop',
  278. 'DROP',
  279. __('Allows dropping tables.'),
  280. ],
  281. [
  282. 'Index',
  283. 'INDEX',
  284. __('Allows creating and dropping indexes.'),
  285. ],
  286. [
  287. 'Alter',
  288. 'ALTER',
  289. __('Allows altering the structure of existing tables.'),
  290. ],
  291. [
  292. 'Create View',
  293. 'CREATE_VIEW',
  294. __('Allows creating new views.'),
  295. ],
  296. [
  297. 'Show view',
  298. 'SHOW_VIEW',
  299. __('Allows performing SHOW CREATE VIEW queries.'),
  300. ],
  301. [
  302. 'Trigger',
  303. 'TRIGGER',
  304. __('Allows creating and dropping triggers.'),
  305. ],
  306. ];
  307. }
  308. /**
  309. * Get the grants array which contains all the privilege types
  310. * and relevant grant messages
  311. *
  312. * @return array
  313. */
  314. public function getGrantsArray()
  315. {
  316. return [
  317. [
  318. 'Select_priv',
  319. 'SELECT',
  320. __('Allows reading data.'),
  321. ],
  322. [
  323. 'Insert_priv',
  324. 'INSERT',
  325. __('Allows inserting and replacing data.'),
  326. ],
  327. [
  328. 'Update_priv',
  329. 'UPDATE',
  330. __('Allows changing data.'),
  331. ],
  332. [
  333. 'Delete_priv',
  334. 'DELETE',
  335. __('Allows deleting data.'),
  336. ],
  337. [
  338. 'Create_priv',
  339. 'CREATE',
  340. __('Allows creating new databases and tables.'),
  341. ],
  342. [
  343. 'Drop_priv',
  344. 'DROP',
  345. __('Allows dropping databases and tables.'),
  346. ],
  347. [
  348. 'Reload_priv',
  349. 'RELOAD',
  350. __('Allows reloading server settings and flushing the server\'s caches.'),
  351. ],
  352. [
  353. 'Shutdown_priv',
  354. 'SHUTDOWN',
  355. __('Allows shutting down the server.'),
  356. ],
  357. [
  358. 'Process_priv',
  359. 'PROCESS',
  360. __('Allows viewing processes of all users.'),
  361. ],
  362. [
  363. 'File_priv',
  364. 'FILE',
  365. __('Allows importing data from and exporting data into files.'),
  366. ],
  367. [
  368. 'References_priv',
  369. 'REFERENCES',
  370. __('Has no effect in this MySQL version.'),
  371. ],
  372. [
  373. 'Index_priv',
  374. 'INDEX',
  375. __('Allows creating and dropping indexes.'),
  376. ],
  377. [
  378. 'Alter_priv',
  379. 'ALTER',
  380. __('Allows altering the structure of existing tables.'),
  381. ],
  382. [
  383. 'Show_db_priv',
  384. 'SHOW DATABASES',
  385. __('Gives access to the complete list of databases.'),
  386. ],
  387. [
  388. 'Super_priv',
  389. 'SUPER',
  390. __(
  391. 'Allows connecting, even if maximum number of connections '
  392. . 'is reached; required for most administrative operations '
  393. . 'like setting global variables or killing threads of other users.'
  394. ),
  395. ],
  396. [
  397. 'Create_tmp_table_priv',
  398. 'CREATE TEMPORARY TABLES',
  399. __('Allows creating temporary tables.'),
  400. ],
  401. [
  402. 'Lock_tables_priv',
  403. 'LOCK TABLES',
  404. __('Allows locking tables for the current thread.'),
  405. ],
  406. [
  407. 'Repl_slave_priv',
  408. 'REPLICATION SLAVE',
  409. __('Needed for the replication replicas.'),
  410. ],
  411. [
  412. 'Repl_client_priv',
  413. 'REPLICATION CLIENT',
  414. __('Allows the user to ask where the replicas / primaries are.'),
  415. ],
  416. [
  417. 'Create_view_priv',
  418. 'CREATE VIEW',
  419. __('Allows creating new views.'),
  420. ],
  421. [
  422. 'Event_priv',
  423. 'EVENT',
  424. __('Allows to set up events for the event scheduler.'),
  425. ],
  426. [
  427. 'Trigger_priv',
  428. 'TRIGGER',
  429. __('Allows creating and dropping triggers.'),
  430. ],
  431. // for table privs:
  432. [
  433. 'Create View_priv',
  434. 'CREATE VIEW',
  435. __('Allows creating new views.'),
  436. ],
  437. [
  438. 'Show_view_priv',
  439. 'SHOW VIEW',
  440. __('Allows performing SHOW CREATE VIEW queries.'),
  441. ],
  442. // for table privs:
  443. [
  444. 'Show view_priv',
  445. 'SHOW VIEW',
  446. __('Allows performing SHOW CREATE VIEW queries.'),
  447. ],
  448. [
  449. 'Delete_history_priv',
  450. 'DELETE HISTORY',
  451. // phpcs:ignore Generic.Files.LineLength.TooLong
  452. /* l10n: https://mariadb.com/kb/en/library/grant/#table-privileges "Remove historical rows from a table using the DELETE HISTORY statement" */
  453. __('Allows deleting historical rows.'),
  454. ],
  455. [
  456. // This was finally removed in the following MariaDB versions
  457. // @see https://jira.mariadb.org/browse/MDEV-20382
  458. 'Delete versioning rows_priv',
  459. 'DELETE HISTORY',
  460. // phpcs:ignore Generic.Files.LineLength.TooLong
  461. /* l10n: https://mariadb.com/kb/en/library/grant/#table-privileges "Remove historical rows from a table using the DELETE HISTORY statement" */
  462. __('Allows deleting historical rows.'),
  463. ],
  464. [
  465. 'Create_routine_priv',
  466. 'CREATE ROUTINE',
  467. __('Allows creating stored routines.'),
  468. ],
  469. [
  470. 'Alter_routine_priv',
  471. 'ALTER ROUTINE',
  472. __('Allows altering and dropping stored routines.'),
  473. ],
  474. [
  475. 'Create_user_priv',
  476. 'CREATE USER',
  477. __('Allows creating, dropping and renaming user accounts.'),
  478. ],
  479. [
  480. 'Execute_priv',
  481. 'EXECUTE',
  482. __('Allows executing stored routines.'),
  483. ],
  484. ];
  485. }
  486. /**
  487. * Get sql query for display privileges table
  488. *
  489. * @param string $db the database
  490. * @param string $table the table
  491. * @param string $username username for database connection
  492. * @param string $hostname hostname for database connection
  493. *
  494. * @return string sql query
  495. */
  496. public function getSqlQueryForDisplayPrivTable(string $db, string $table, string $username, string $hostname)
  497. {
  498. if ($db === '*') {
  499. return 'SELECT * FROM `mysql`.`user`'
  500. . " WHERE `User` = '" . $this->dbi->escapeString($username) . "'"
  501. . " AND `Host` = '" . $this->dbi->escapeString($hostname) . "';";
  502. }
  503. if ($table === '*') {
  504. return 'SELECT * FROM `mysql`.`db`'
  505. . " WHERE `User` = '" . $this->dbi->escapeString($username) . "'"
  506. . " AND `Host` = '" . $this->dbi->escapeString($hostname) . "'"
  507. . " AND `Db` = '" . $this->dbi->escapeString($db) . "'";
  508. }
  509. return 'SELECT `Table_priv`'
  510. . ' FROM `mysql`.`tables_priv`'
  511. . " WHERE `User` = '" . $this->dbi->escapeString($username) . "'"
  512. . " AND `Host` = '" . $this->dbi->escapeString($hostname) . "'"
  513. . " AND `Db` = '" . $this->dbi->escapeString(Util::unescapeMysqlWildcards($db)) . "'"
  514. . " AND `Table_name` = '" . $this->dbi->escapeString($table) . "';";
  515. }
  516. /**
  517. * Sets the user group from request values
  518. *
  519. * @param string $username username
  520. * @param string $userGroup user group to set
  521. */
  522. public function setUserGroup($username, $userGroup): void
  523. {
  524. $userGroup = $userGroup ?? '';
  525. $configurableMenusFeature = $this->relation->getRelationParameters()->configurableMenusFeature;
  526. if ($configurableMenusFeature === null) {
  527. return;
  528. }
  529. $userTable = Util::backquote($configurableMenusFeature->database)
  530. . '.' . Util::backquote($configurableMenusFeature->users);
  531. $sqlQuery = 'SELECT `usergroup` FROM ' . $userTable
  532. . " WHERE `username` = '" . $this->dbi->escapeString($username) . "'";
  533. $oldUserGroup = $this->dbi->fetchValue($sqlQuery, 0, DatabaseInterface::CONNECT_CONTROL);
  534. if ($oldUserGroup === false) {
  535. $updQuery = 'INSERT INTO ' . $userTable . '(`username`, `usergroup`)'
  536. . " VALUES ('" . $this->dbi->escapeString($username) . "', "
  537. . "'" . $this->dbi->escapeString($userGroup) . "')";
  538. } else {
  539. if (empty($userGroup)) {
  540. $updQuery = 'DELETE FROM ' . $userTable
  541. . " WHERE `username`='" . $this->dbi->escapeString($username) . "'";
  542. } elseif ($oldUserGroup != $userGroup) {
  543. $updQuery = 'UPDATE ' . $userTable
  544. . " SET `usergroup`='" . $this->dbi->escapeString($userGroup) . "'"
  545. . " WHERE `username`='" . $this->dbi->escapeString($username) . "'";
  546. }
  547. }
  548. if (! isset($updQuery)) {
  549. return;
  550. }
  551. $this->dbi->queryAsControlUser($updQuery);
  552. }
  553. /**
  554. * Displays the privileges form table
  555. *
  556. * @param string $db the database
  557. * @param string $table the table
  558. * @param bool $submit whether to display the submit button or not
  559. *
  560. * @return string html snippet
  561. *
  562. * @global array $cfg the phpMyAdmin configuration
  563. * @global resource $user_link the database connection
  564. */
  565. public function getHtmlToDisplayPrivilegesTable(
  566. $db = '*',
  567. $table = '*',
  568. $submit = true
  569. ) {
  570. if ($db === '*') {
  571. $table = '*';
  572. }
  573. $username = '';
  574. $hostname = '';
  575. $row = [];
  576. if (isset($GLOBALS['username'])) {
  577. $username = $GLOBALS['username'];
  578. $hostname = $GLOBALS['hostname'];
  579. $sqlQuery = $this->getSqlQueryForDisplayPrivTable($db, $table, $username, $hostname);
  580. $row = $this->dbi->fetchSingleRow($sqlQuery);
  581. }
  582. if (empty($row)) {
  583. if ($table === '*' && $this->dbi->isSuperUser()) {
  584. $row = [];
  585. $sqlQuery = 'SHOW COLUMNS FROM `mysql`.' . ($db === '*' ? '`user`' : '`db`') . ';';
  586. $res = $this->dbi->query($sqlQuery);
  587. while ($row1 = $res->fetchRow()) {
  588. if (mb_substr($row1[0], 0, 4) === 'max_') {
  589. $row[$row1[0]] = 0;
  590. } elseif (mb_substr($row1[0], 0, 5) === 'x509_' || mb_substr($row1[0], 0, 4) === 'ssl_') {
  591. $row[$row1[0]] = '';
  592. } else {
  593. $row[$row1[0]] = 'N';
  594. }
  595. }
  596. } elseif ($table === '*') {
  597. $row = [];
  598. } else {
  599. $row = ['Table_priv' => ''];
  600. }
  601. }
  602. if (isset($row['Table_priv'])) {
  603. $this->fillInTablePrivileges($row);
  604. // get columns
  605. $res = $this->dbi->tryQuery(
  606. 'SHOW COLUMNS FROM '
  607. . Util::backquote(
  608. Util::unescapeMysqlWildcards($db)
  609. )
  610. . '.' . Util::backquote($table) . ';'
  611. );
  612. $columns = [];
  613. if ($res) {
  614. while ($row1 = $res->fetchRow()) {
  615. $columns[$row1[0]] = [
  616. 'Select' => false,
  617. 'Insert' => false,
  618. 'Update' => false,
  619. 'References' => false,
  620. ];
  621. }
  622. }
  623. }
  624. if (! empty($columns)) {
  625. $res = $this->dbi->query(
  626. 'SELECT `Column_name`, `Column_priv`'
  627. . ' FROM `mysql`.`columns_priv`'
  628. . ' WHERE `User`'
  629. . ' = \'' . $this->dbi->escapeString($username) . "'"
  630. . ' AND `Host`'
  631. . ' = \'' . $this->dbi->escapeString($hostname) . "'"
  632. . ' AND `Db`'
  633. . ' = \'' . $this->dbi->escapeString(
  634. Util::unescapeMysqlWildcards($db)
  635. ) . "'"
  636. . ' AND `Table_name`'
  637. . ' = \'' . $this->dbi->escapeString($table) . '\';'
  638. );
  639. while ($row1 = $res->fetchRow()) {
  640. $row1[1] = explode(',', $row1[1]);
  641. foreach ($row1[1] as $current) {
  642. $columns[$row1[0]][$current] = true;
  643. }
  644. }
  645. }
  646. return $this->template->render('server/privileges/privileges_table', [
  647. 'is_global' => $db === '*',
  648. 'is_database' => $table === '*',
  649. 'row' => $row,
  650. 'columns' => $columns ?? [],
  651. 'has_submit' => $submit,
  652. 'supports_references_privilege' => Compatibility::supportsReferencesPrivilege($this->dbi),
  653. 'is_mariadb' => $this->dbi->isMariaDB(),
  654. ]);
  655. }
  656. /**
  657. * Get the HTML snippet for routine specific privileges
  658. *
  659. * @param string $username username for database connection
  660. * @param string $hostname hostname for database connection
  661. * @param string $db the database
  662. * @param string $routine the routine
  663. * @param string $urlDbname url encoded db name
  664. *
  665. * @return string
  666. */
  667. public function getHtmlForRoutineSpecificPrivileges(
  668. string $username,
  669. string $hostname,
  670. string $db,
  671. string $routine,
  672. $urlDbname
  673. ) {
  674. $privileges = $this->getRoutinePrivileges($username, $hostname, $db, $routine);
  675. return $this->template->render('server/privileges/edit_routine_privileges', [
  676. 'username' => $username,
  677. 'hostname' => $hostname,
  678. 'database' => $db,
  679. 'routine' => $routine,
  680. 'privileges' => $privileges,
  681. 'dbname' => $urlDbname,
  682. 'current_user' => $this->dbi->getCurrentUser(),
  683. ]);
  684. }
  685. /**
  686. * Displays the fields used by the "new user" form as well as the
  687. * "change login information / copy user" form.
  688. *
  689. * @param string $mode are we creating a new user or are we just
  690. * changing one? (allowed values: 'new', 'change')
  691. * @param string $user User name
  692. * @param string $host Host name
  693. *
  694. * @return string a HTML snippet
  695. */
  696. public function getHtmlForLoginInformationFields(
  697. $mode = 'new',
  698. $user = null,
  699. $host = null
  700. ) {
  701. global $pred_username, $pred_hostname, $username, $hostname, $new_username;
  702. [$usernameLength, $hostnameLength] = $this->getUsernameAndHostnameLength();
  703. if (isset($username) && strlen($username) === 0) {
  704. $pred_username = 'any';
  705. }
  706. $currentUser = $this->dbi->fetchValue('SELECT USER();');
  707. $thisHost = null;
  708. if (! empty($currentUser)) {
  709. $thisHost = str_replace(
  710. '\'',
  711. '',
  712. mb_substr(
  713. $currentUser,
  714. mb_strrpos($currentUser, '@') + 1
  715. )
  716. );
  717. }
  718. if (! isset($pred_hostname) && isset($hostname)) {
  719. switch (mb_strtolower($hostname)) {
  720. case 'localhost':
  721. case '127.0.0.1':
  722. $pred_hostname = 'localhost';
  723. break;
  724. case '%':
  725. $pred_hostname = 'any';
  726. break;
  727. default:
  728. $pred_hostname = 'userdefined';
  729. break;
  730. }
  731. }
  732. $serverVersion = $this->dbi->getVersion();
  733. $authPlugin = $this->getCurrentAuthenticationPlugin($mode, $user, $host);
  734. $isNew = (Compatibility::isMySqlOrPerconaDb() && $serverVersion >= 50507)
  735. || (Compatibility::isMariaDb() && $serverVersion >= 50200);
  736. $activeAuthPlugins = ['mysql_native_password' => __('Native MySQL authentication')];
  737. if ($isNew) {
  738. $activeAuthPlugins = $this->plugins->getAuthentication();
  739. if (isset($activeAuthPlugins['mysql_old_password'])) {
  740. unset($activeAuthPlugins['mysql_old_password']);
  741. }
  742. }
  743. return $this->template->render('server/privileges/login_information_fields', [
  744. 'pred_username' => $pred_username ?? null,
  745. 'pred_hostname' => $pred_hostname ?? null,
  746. 'username_length' => $usernameLength,
  747. 'hostname_length' => $hostnameLength,
  748. 'username' => $username ?? null,
  749. 'new_username' => $new_username ?? null,
  750. 'hostname' => $hostname ?? null,
  751. 'this_host' => $thisHost,
  752. 'is_change' => $mode === 'change',
  753. 'auth_plugin' => $authPlugin,
  754. 'active_auth_plugins' => $activeAuthPlugins,
  755. 'is_new' => $isNew,
  756. ]);
  757. }
  758. /**
  759. * Get username and hostname length
  760. *
  761. * @return array username length and hostname length
  762. */
  763. public function getUsernameAndHostnameLength()
  764. {
  765. /* Fallback values */
  766. $usernameLength = 16;
  767. $hostnameLength = 41;
  768. /* Try to get real lengths from the database */
  769. $fieldsInfo = $this->dbi->fetchResult(
  770. 'SELECT COLUMN_NAME, CHARACTER_MAXIMUM_LENGTH '
  771. . 'FROM information_schema.columns '
  772. . "WHERE table_schema = 'mysql' AND table_name = 'user' "
  773. . "AND COLUMN_NAME IN ('User', 'Host')"
  774. );
  775. foreach ($fieldsInfo as $val) {
  776. if ($val['COLUMN_NAME'] === 'User') {
  777. $usernameLength = $val['CHARACTER_MAXIMUM_LENGTH'];
  778. } elseif ($val['COLUMN_NAME'] === 'Host') {
  779. $hostnameLength = $val['CHARACTER_MAXIMUM_LENGTH'];
  780. }
  781. }
  782. return [
  783. $usernameLength,
  784. $hostnameLength,
  785. ];
  786. }
  787. /**
  788. * Get current authentication plugin in use - for a user or globally
  789. *
  790. * @param string $mode are we creating a new user or are we just
  791. * changing one? (allowed values: 'new', 'change')
  792. * @param string $username User name
  793. * @param string $hostname Host name
  794. *
  795. * @return string authentication plugin in use
  796. */
  797. public function getCurrentAuthenticationPlugin(
  798. $mode = 'new',
  799. $username = null,
  800. $hostname = null
  801. ) {
  802. global $dbi;
  803. /* Fallback (standard) value */
  804. $authenticationPlugin = 'mysql_native_password';
  805. $serverVersion = $this->dbi->getVersion();
  806. if (isset($username, $hostname) && $mode === 'change') {
  807. $row = $this->dbi->fetchSingleRow(
  808. 'SELECT `plugin` FROM `mysql`.`user` WHERE `User` = "'
  809. . $dbi->escapeString($username)
  810. . '" AND `Host` = "'
  811. . $dbi->escapeString($hostname)
  812. . '" LIMIT 1'
  813. );
  814. // Table 'mysql'.'user' may not exist for some previous
  815. // versions of MySQL - in that case consider fallback value
  816. if (is_array($row) && isset($row['plugin'])) {
  817. $authenticationPlugin = $row['plugin'];
  818. }
  819. } elseif ($mode === 'change') {
  820. [$username, $hostname] = $this->dbi->getCurrentUserAndHost();
  821. $row = $this->dbi->fetchSingleRow(
  822. 'SELECT `plugin` FROM `mysql`.`user` WHERE `User` = "'
  823. . $dbi->escapeString($username)
  824. . '" AND `Host` = "'
  825. . $dbi->escapeString($hostname)
  826. . '"'
  827. );
  828. if (is_array($row) && isset($row['plugin'])) {
  829. $authenticationPlugin = $row['plugin'];
  830. }
  831. } elseif ($serverVersion >= 50702) {
  832. $row = $this->dbi->fetchSingleRow('SELECT @@default_authentication_plugin');
  833. $authenticationPlugin = is_array($row) ? $row['@@default_authentication_plugin'] : null;
  834. }
  835. return $authenticationPlugin;
  836. }
  837. /**
  838. * Returns all the grants for a certain user on a certain host
  839. * Used in the export privileges for all users section
  840. *
  841. * @param string $user User name
  842. * @param string $host Host name
  843. *
  844. * @return string containing all the grants text
  845. */
  846. public function getGrants($user, $host)
  847. {
  848. $grants = $this->dbi->fetchResult(
  849. "SHOW GRANTS FOR '"
  850. . $this->dbi->escapeString($user) . "'@'"
  851. . $this->dbi->escapeString($host) . "'"
  852. );
  853. $response = '';
  854. foreach ($grants as $oneGrant) {
  855. $response .= $oneGrant . ";\n\n";
  856. }
  857. return $response;
  858. }
  859. /**
  860. * Update password and get message for password updating
  861. *
  862. * @param string $errorUrl error url
  863. * @param string $username username
  864. * @param string $hostname hostname
  865. *
  866. * @return Message success or error message after updating password
  867. */
  868. public function updatePassword($errorUrl, $username, $hostname)
  869. {
  870. global $dbi;
  871. // similar logic in /user-password
  872. $message = null;
  873. if (isset($_POST['pma_pw'], $_POST['pma_pw2']) && empty($_POST['nopass'])) {
  874. if ($_POST['pma_pw'] != $_POST['pma_pw2']) {
  875. $message = Message::error(__('The passwords aren\'t the same!'));
  876. } elseif (empty($_POST['pma_pw']) || empty($_POST['pma_pw2'])) {
  877. $message = Message::error(__('The password is empty!'));
  878. }
  879. }
  880. // here $nopass could be == 1
  881. if ($message === null) {
  882. $hashingFunction = 'PASSWORD';
  883. $serverVersion = $this->dbi->getVersion();
  884. $authenticationPlugin = ($_POST['authentication_plugin'] ?? $this->getCurrentAuthenticationPlugin(
  885. 'change',
  886. $username,
  887. $hostname
  888. ));
  889. // Use 'ALTER USER ...' syntax for MySQL 5.7.6+
  890. if (Compatibility::isMySqlOrPerconaDb() && $serverVersion >= 50706) {
  891. if ($authenticationPlugin !== 'mysql_old_password') {
  892. $queryPrefix = "ALTER USER '"
  893. . $this->dbi->escapeString($username)
  894. . "'@'" . $this->dbi->escapeString($hostname) . "'"
  895. . ' IDENTIFIED WITH '
  896. . $authenticationPlugin
  897. . " BY '";
  898. } else {
  899. $queryPrefix = "ALTER USER '"
  900. . $this->dbi->escapeString($username)
  901. . "'@'" . $this->dbi->escapeString($hostname) . "'"
  902. . " IDENTIFIED BY '";
  903. }
  904. // in $sql_query which will be displayed, hide the password
  905. $sqlQuery = $queryPrefix . "*'";
  906. $localQuery = $queryPrefix
  907. . $this->dbi->escapeString($_POST['pma_pw']) . "'";
  908. } elseif (Compatibility::isMariaDb() && $serverVersion >= 10000) {
  909. // MariaDB uses "SET PASSWORD" syntax to change user password.
  910. // On Galera cluster only DDL queries are replicated, since
  911. // users are stored in MyISAM storage engine.
  912. $queryPrefix = "SET PASSWORD FOR '"
  913. . $this->dbi->escapeString($username)
  914. . "'@'" . $this->dbi->escapeString($hostname) . "'"
  915. . " = PASSWORD ('";
  916. $sqlQuery = $localQuery = $queryPrefix
  917. . $this->dbi->escapeString($_POST['pma_pw']) . "')";
  918. } elseif (Compatibility::isMariaDb() && $serverVersion >= 50200 && $this->dbi->isSuperUser()) {
  919. // Use 'UPDATE `mysql`.`user` ...' Syntax for MariaDB 5.2+
  920. if ($authenticationPlugin === 'mysql_native_password') {
  921. // Set the hashing method used by PASSWORD()
  922. // to be 'mysql_native_password' type
  923. $this->dbi->tryQuery('SET old_passwords = 0;');
  924. } elseif ($authenticationPlugin === 'sha256_password') {
  925. // Set the hashing method used by PASSWORD()
  926. // to be 'sha256_password' type
  927. $this->dbi->tryQuery('SET `old_passwords` = 2;');
  928. }
  929. $hashedPassword = $this->getHashedPassword($_POST['pma_pw']);
  930. $sqlQuery = 'SET PASSWORD FOR \''
  931. . $this->dbi->escapeString($username)
  932. . '\'@\'' . $this->dbi->escapeString($hostname) . '\' = '
  933. . ($_POST['pma_pw'] == ''
  934. ? '\'\''
  935. : $hashingFunction . '(\''
  936. . preg_replace('@.@s', '*', $_POST['pma_pw']) . '\')');
  937. $localQuery = 'UPDATE `mysql`.`user` SET '
  938. . " `authentication_string` = '" . $hashedPassword
  939. . "', `Password` = '', "
  940. . " `plugin` = '" . $authenticationPlugin . "'"
  941. . " WHERE `User` = '" . $dbi->escapeString($username)
  942. . "' AND Host = '" . $dbi->escapeString($hostname) . "';";
  943. } else {
  944. // USE 'SET PASSWORD ...' syntax for rest of the versions
  945. // Backup the old value, to be reset later
  946. $row = $this->dbi->fetchSingleRow('SELECT @@old_passwords;');
  947. $origValue = $row['@@old_passwords'];
  948. $updatePluginQuery = 'UPDATE `mysql`.`user` SET'
  949. . " `plugin` = '" . $authenticationPlugin . "'"
  950. . " WHERE `User` = '" . $dbi->escapeString($username)
  951. . "' AND Host = '" . $dbi->escapeString($hostname) . "';";
  952. // Update the plugin for the user
  953. if (! $this->dbi->tryQuery($updatePluginQuery)) {
  954. Generator::mysqlDie(
  955. $this->dbi->getError(),
  956. $updatePluginQuery,
  957. false,
  958. $errorUrl
  959. );
  960. }
  961. $this->dbi->tryQuery('FLUSH PRIVILEGES;');
  962. if ($authenticationPlugin === 'mysql_native_password') {
  963. // Set the hashing method used by PASSWORD()
  964. // to be 'mysql_native_password' type
  965. $this->dbi->tryQuery('SET old_passwords = 0;');
  966. } elseif ($authenticationPlugin === 'sha256_password') {
  967. // Set the hashing method used by PASSWORD()
  968. // to be 'sha256_password' type
  969. $this->dbi->tryQuery('SET `old_passwords` = 2;');
  970. }
  971. $sqlQuery = 'SET PASSWORD FOR \''
  972. . $this->dbi->escapeString($username)
  973. . '\'@\'' . $this->dbi->escapeString($hostname) . '\' = '
  974. . ($_POST['pma_pw'] == ''
  975. ? '\'\''
  976. : $hashingFunction . '(\''
  977. . preg_replace('@.@s', '*', $_POST['pma_pw']) . '\')');
  978. $localQuery = 'SET PASSWORD FOR \''
  979. . $this->dbi->escapeString($username)
  980. . '\'@\'' . $this->dbi->escapeString($hostname) . '\' = '
  981. . ($_POST['pma_pw'] == '' ? '\'\'' : $hashingFunction
  982. . '(\'' . $this->dbi->escapeString($_POST['pma_pw']) . '\')');
  983. }
  984. if (! $this->dbi->tryQuery($localQuery)) {
  985. Generator::mysqlDie(
  986. $this->dbi->getError(),
  987. $sqlQuery,
  988. false,
  989. $errorUrl
  990. );
  991. }
  992. // Flush privileges after successful password change
  993. $this->dbi->tryQuery('FLUSH PRIVILEGES;');
  994. $message = Message::success(
  995. __('The password for %s was changed successfully.')
  996. );
  997. $message->addParam('\'' . $username . '\'@\'' . $hostname . '\'');
  998. if (isset($origValue)) {
  999. $this->dbi->tryQuery('SET `old_passwords` = ' . $origValue . ';');
  1000. }
  1001. }
  1002. return $message;
  1003. }
  1004. /**
  1005. * Revokes privileges and get message and SQL query for privileges revokes
  1006. *
  1007. * @param string $dbname database name
  1008. * @param string $tablename table name
  1009. * @param string $username username
  1010. * @param string $hostname host name
  1011. * @param string $itemType item type
  1012. *
  1013. * @return array ($message, $sql_query)
  1014. */
  1015. public function getMessageAndSqlQueryForPrivilegesRevoke(
  1016. string $dbname,
  1017. string $tablename,
  1018. string $username,
  1019. string $hostname,
  1020. $itemType
  1021. ) {
  1022. $dbAndTable = $this->wildcardEscapeForGrant($dbname, $tablename);
  1023. $sqlQuery0 = 'REVOKE ALL PRIVILEGES ON ' . $itemType . ' ' . $dbAndTable
  1024. . ' FROM \''
  1025. . $this->dbi->escapeString($username) . '\'@\''
  1026. . $this->dbi->escapeString($hostname) . '\';';
  1027. $sqlQuery1 = 'REVOKE GRANT OPTION ON ' . $itemType . ' ' . $dbAndTable
  1028. . ' FROM \'' . $this->dbi->escapeString($username) . '\'@\''
  1029. . $this->dbi->escapeString($hostname) . '\';';
  1030. $this->dbi->query($sqlQuery0);
  1031. if (! $this->dbi->tryQuery($sqlQuery1)) {
  1032. // this one may fail, too...
  1033. $sqlQuery1 = '';
  1034. }
  1035. $sqlQuery = $sqlQuery0 . ' ' . $sqlQuery1;
  1036. $message = Message::success(
  1037. __('You have revoked the privileges for %s.')
  1038. );
  1039. $message->addParam('\'' . $username . '\'@\'' . $hostname . '\'');
  1040. return [
  1041. $message,
  1042. $sqlQuery,
  1043. ];
  1044. }
  1045. /**
  1046. * Get REQUIRE clause
  1047. *
  1048. * @return string REQUIRE clause
  1049. */
  1050. public function getRequireClause()
  1051. {
  1052. $arr = isset($_POST['ssl_type']) ? $_POST : $GLOBALS;
  1053. if (isset($arr['ssl_type']) && $arr['ssl_type'] === 'SPECIFIED') {
  1054. $require = [];
  1055. if (! empty($arr['ssl_cipher'])) {
  1056. $require[] = "CIPHER '"
  1057. . $this->dbi->escapeString($arr['ssl_cipher']) . "'";
  1058. }
  1059. if (! empty($arr['x509_issuer'])) {
  1060. $require[] = "ISSUER '"
  1061. . $this->dbi->escapeString($arr['x509_issuer']) . "'";
  1062. }
  1063. if (! empty($arr['x509_subject'])) {
  1064. $require[] = "SUBJECT '"
  1065. . $this->dbi->escapeString($arr['x509_subject']) . "'";
  1066. }
  1067. if (count($require)) {
  1068. $requireClause = ' REQUIRE ' . implode(' AND ', $require);
  1069. } else {
  1070. $requireClause = ' REQUIRE NONE';
  1071. }
  1072. } elseif (isset($arr['ssl_type']) && $arr['ssl_type'] === 'X509') {
  1073. $requireClause = ' REQUIRE X509';
  1074. } elseif (isset($arr['ssl_type']) && $arr['ssl_type'] === 'ANY') {
  1075. $requireClause = ' REQUIRE SSL';
  1076. } else {
  1077. $requireClause = ' REQUIRE NONE';
  1078. }
  1079. return $requireClause;
  1080. }
  1081. /**
  1082. * Get a WITH clause for 'update privileges' and 'add user'
  1083. *
  1084. * @return string
  1085. */
  1086. public function getWithClauseForAddUserAndUpdatePrivs()
  1087. {
  1088. $sqlQuery = '';
  1089. if (
  1090. ((isset($_POST['Grant_priv']) && $_POST['Grant_priv'] === 'Y')
  1091. || (isset($GLOBALS['Grant_priv']) && $GLOBALS['Grant_priv'] === 'Y'))
  1092. && ! (Compatibility::isMySqlOrPerconaDb() && $this->dbi->getVersion() >= 80011)
  1093. ) {
  1094. $sqlQuery .= ' GRANT OPTION';
  1095. }
  1096. if (isset($_POST['max_questions']) || isset($GLOBALS['max_questions'])) {
  1097. $maxQuestions = isset($_POST['max_questions'])
  1098. ? (int) $_POST['max_questions'] : (int) $GLOBALS['max_questions'];
  1099. $maxQuestions = max(0, $maxQuestions);
  1100. $sqlQuery .= ' MAX_QUERIES_PER_HOUR ' . $maxQuestions;
  1101. }
  1102. if (isset($_POST['max_connections']) || isset($GLOBALS['max_connections'])) {
  1103. $maxConnections = isset($_POST['max_connections'])
  1104. ? (int) $_POST['max_connections'] : (int) $GLOBALS['max_connections'];
  1105. $maxConnections = max(0, $maxConnections);
  1106. $sqlQuery .= ' MAX_CONNECTIONS_PER_HOUR ' . $maxConnections;
  1107. }
  1108. if (isset($_POST['max_updates']) || isset($GLOBALS['max_updates'])) {
  1109. $maxUpdates = isset($_POST['max_updates'])
  1110. ? (int) $_POST['max_updates'] : (int) $GLOBALS['max_updates'];
  1111. $maxUpdates = max(0, $maxUpdates);
  1112. $sqlQuery .= ' MAX_UPDATES_PER_HOUR ' . $maxUpdates;
  1113. }
  1114. if (isset($_POST['max_user_connections']) || isset($GLOBALS['max_user_connections'])) {
  1115. $maxUserConnections = isset($_POST['max_user_connections'])
  1116. ? (int) $_POST['max_user_connections']
  1117. : (int) $GLOBALS['max_user_connections'];
  1118. $maxUserConnections = max(0, $maxUserConnections);
  1119. $sqlQuery .= ' MAX_USER_CONNECTIONS ' . $maxUserConnections;
  1120. }
  1121. return ! empty($sqlQuery) ? ' WITH' . $sqlQuery : '';
  1122. }
  1123. /**
  1124. * Get HTML for addUsersForm, This function call if isset($_GET['adduser'])
  1125. *
  1126. * @param string $dbname database name
  1127. *
  1128. * @return string HTML for addUserForm
  1129. */
  1130. public function getHtmlForAddUser($dbname)
  1131. {
  1132. $isGrantUser = $this->dbi->isGrantUser();
  1133. $loginInformationFieldsNew = $this->getHtmlForLoginInformationFields('new');
  1134. $privilegesTable = '';
  1135. if ($isGrantUser) {
  1136. $privilegesTable = $this->getHtmlToDisplayPrivilegesTable('*', '*', false);
  1137. }
  1138. return $this->template->render('server/privileges/add_user', [
  1139. 'database' => $dbname,
  1140. 'login_information_fields_new' => $loginInformationFieldsNew,
  1141. 'is_grant_user' => $isGrantUser,
  1142. 'privileges_table' => $privilegesTable,
  1143. ]);
  1144. }
  1145. /**
  1146. * @param string $db database name
  1147. * @param string $table table name
  1148. *
  1149. * @return array
  1150. */
  1151. public function getAllPrivileges(string $db, string $table = ''): array
  1152. {
  1153. $databasePrivileges = $this->getGlobalAndDatabasePrivileges($db);
  1154. $tablePrivileges = [];
  1155. if ($table !== '') {
  1156. $tablePrivileges = $this->getTablePrivileges($db, $table);
  1157. }
  1158. $routinePrivileges = $this->getRoutinesPrivileges($db);
  1159. $allPrivileges = array_merge($databasePrivileges, $tablePrivileges, $routinePrivileges);
  1160. $privileges = [];
  1161. foreach ($allPrivileges as $privilege) {
  1162. $userHost = $privilege['User'] . '@' . $privilege['Host'];
  1163. $privileges[$userHost] = $privileges[$userHost] ?? [];
  1164. $privileges[$userHost]['user'] = (string) $privilege['User'];
  1165. $privileges[$userHost]['host'] = (string) $privilege['Host'];
  1166. $privileges[$userHost]['privileges'] = $privileges[$userHost]['privileges'] ?? [];
  1167. $privileges[$userHost]['privileges'][] = $this->getSpecificPrivilege($privilege);
  1168. }
  1169. return $privileges;
  1170. }
  1171. /**
  1172. * @param array $row Array with user privileges
  1173. *
  1174. * @return array
  1175. */
  1176. private function getSpecificPrivilege(array $row): array
  1177. {
  1178. $privilege = [
  1179. 'type' => $row['Type'],
  1180. 'database' => $row['Db'],
  1181. ];
  1182. if ($row['Type'] === 'r') {
  1183. $privilege['routine'] = $row['Routine_name'];
  1184. $privilege['has_grant'] = str_contains($row['Proc_priv'], 'Grant');
  1185. $privilege['privileges'] = explode(',', $row['Proc_priv']);
  1186. } elseif ($row['Type'] === 't') {
  1187. $privilege['table'] = $row['Table_name'];
  1188. $privilege['has_grant'] = str_contains($row['Table_priv'], 'Grant');
  1189. $tablePrivs = explode(',', $row['Table_priv']);
  1190. $specificPrivileges = [];
  1191. $grantsArr = $this->getTableGrantsArray();
  1192. foreach ($grantsArr as $grant) {
  1193. $specificPrivileges[$grant[0]] = 'N';
  1194. foreach ($tablePrivs as $tablePriv) {
  1195. if ($grant[0] != $tablePriv) {
  1196. continue;
  1197. }
  1198. $specificPrivileges[$grant[0]] = 'Y';
  1199. }
  1200. }
  1201. $privilege['privileges'] = $this->extractPrivInfo($specificPrivileges, true, true);
  1202. } else {
  1203. $privilege['has_grant'] = $row['Grant_priv'] === 'Y';
  1204. $privilege['privileges'] = $this->extractPrivInfo($row, true);
  1205. }
  1206. return $privilege;
  1207. }
  1208. /**
  1209. * @param string $db database name
  1210. *
  1211. * @return array
  1212. */
  1213. private function getGlobalAndDatabasePrivileges(string $db): array
  1214. {
  1215. $listOfPrivileges = '`Select_priv`,
  1216. `Insert_priv`,
  1217. `Update_priv`,
  1218. `Delete_priv`,
  1219. `Create_priv`,
  1220. `Drop_priv`,
  1221. `Grant_priv`,
  1222. `Index_priv`,
  1223. `Alter_priv`,
  1224. `References_priv`,
  1225. `Create_tmp_table_priv`,
  1226. `Lock_tables_priv`,
  1227. `Create_view_priv`,
  1228. `Show_view_priv`,
  1229. `Create_routine_priv`,
  1230. `Alter_routine_priv`,
  1231. `Execute_priv`,
  1232. `Event_priv`,
  1233. `Trigger_priv`,';
  1234. $listOfComparedPrivileges = 'BINARY `Select_priv` = \'N\' AND
  1235. BINARY `Insert_priv` = \'N\' AND
  1236. BINARY `Update_priv` = \'N\' AND
  1237. BINARY `Delete_priv` = \'N\' AND
  1238. BINARY `Create_priv` = \'N\' AND
  1239. BINARY `Drop_priv` = \'N\' AND
  1240. BINARY `Grant_priv` = \'N\' AND
  1241. BINARY `References_priv` = \'N\' AND
  1242. BINARY `Create_tmp_table_priv` = \'N\' AND
  1243. BINARY `Lock_tables_priv` = \'N\' AND
  1244. BINARY `Create_view_priv` = \'N\' AND
  1245. BINARY `Show_view_priv` = \'N\' AND
  1246. BINARY `Create_routine_priv` = \'N\' AND
  1247. BINARY `Alter_routine_priv` = \'N\' AND
  1248. BINARY `Execute_priv` = \'N\' AND
  1249. BINARY `Event_priv` = \'N\' AND
  1250. BINARY `Trigger_priv` = \'N\'';
  1251. $query = '
  1252. (
  1253. SELECT `User`, `Host`, ' . $listOfPrivileges . ' \'*\' AS `Db`, \'g\' AS `Type`
  1254. FROM `mysql`.`user`
  1255. WHERE NOT (' . $listOfComparedPrivileges . ')
  1256. )
  1257. UNION
  1258. (
  1259. SELECT `User`, `Host`, ' . $listOfPrivileges . ' `Db`, \'d\' AS `Type`
  1260. FROM `mysql`.`db`
  1261. WHERE \'' . $this->dbi->escapeString($db) . '\' LIKE `Db` AND NOT (' . $listOfComparedPrivileges . ')
  1262. )
  1263. ORDER BY `User` ASC, `Host` ASC, `Db` ASC;
  1264. ';
  1265. $result = $this->dbi->query($query);
  1266. return $result->fetchAllAssoc();
  1267. }
  1268. /**
  1269. * @param string $db database name
  1270. * @param string $table table name
  1271. *
  1272. * @return array
  1273. */
  1274. private function getTablePrivileges(string $db, string $table): array
  1275. {
  1276. $query = '
  1277. SELECT `User`, `Host`, `Db`, \'t\' AS `Type`, `Table_name`, `Table_priv`
  1278. FROM `mysql`.`tables_priv`
  1279. WHERE
  1280. ? LIKE `Db` AND
  1281. ? LIKE `Table_name` AND
  1282. NOT (`Table_priv` = \'\' AND Column_priv = \'\')
  1283. ORDER BY `User` ASC, `Host` ASC, `Db` ASC, `Table_priv` ASC;
  1284. ';
  1285. /** @var mysqli_stmt|false $statement */
  1286. $statement = $this->dbi->prepare($query);
  1287. if ($statement === false || ! $statement->bind_param('ss', $db, $table) || ! $statement->execute()) {
  1288. return [];
  1289. }
  1290. $result = new MysqliResult($statement->get_result());
  1291. return $result->fetchAllAssoc();
  1292. }
  1293. /**
  1294. * @param string $db database name
  1295. *
  1296. * @return array
  1297. */
  1298. private function getRoutinesPrivileges(string $db): array
  1299. {
  1300. $query = '
  1301. SELECT *, \'r\' AS `Type`
  1302. FROM `mysql`.`procs_priv`
  1303. WHERE Db = \'' . $this->dbi->escapeString($db) . '\';
  1304. ';
  1305. $result = $this->dbi->query($query);
  1306. return $result->fetchAllAssoc();
  1307. }
  1308. /**
  1309. * Get HTML error for View Users form
  1310. * For non superusers such as grant/create users
  1311. *
  1312. * @return string
  1313. */
  1314. public function getHtmlForViewUsersError()
  1315. {
  1316. return Message::error(
  1317. __('Not enough privilege to view users.')
  1318. )->getDisplay();
  1319. }
  1320. /**
  1321. * Returns edit, revoke or export link for a user.
  1322. *
  1323. * @param string $linktype The link type (edit | revoke | export)
  1324. * @param string $username User name
  1325. * @param string $hostname Host name
  1326. * @param string $dbname Database name
  1327. * @param string $tablename Table name
  1328. * @param string $routinename Routine name
  1329. * @param string $initial Initial value
  1330. *
  1331. * @return string HTML code with link
  1332. */
  1333. public function getUserLink(
  1334. $linktype,
  1335. $username,
  1336. $hostname,
  1337. $dbname = '',
  1338. $tablename = '',
  1339. $routinename = '',
  1340. $initial = ''
  1341. ) {
  1342. $linkClass = '';
  1343. switch ($linktype) {
  1344. case 'edit':
  1345. $linkClass = 'edit_user_anchor';
  1346. break;
  1347. case 'export':
  1348. $linkClass = 'export_user_anchor ajax';
  1349. break;
  1350. }
  1351. $params = [
  1352. 'username' => $username,
  1353. 'hostname' => $hostname,
  1354. ];
  1355. switch ($linktype) {
  1356. case 'edit':
  1357. $params['dbname'] = $dbname;
  1358. $params['tablename'] = $tablename;
  1359. $params['routinename'] = $routinename;
  1360. break;
  1361. case 'revoke':
  1362. $params['dbname'] = $dbname;
  1363. $params['tablename'] = $tablename;
  1364. $params['routinename'] = $routinename;
  1365. $params['revokeall'] = 1;
  1366. break;
  1367. case 'export':
  1368. $params['initial'] = $initial;
  1369. $params['export'] = 1;
  1370. break;
  1371. }
  1372. $action = [];
  1373. switch ($linktype) {
  1374. case 'edit':
  1375. $action['icon'] = 'b_usredit';
  1376. $action['text'] = __('Edit privileges');
  1377. break;
  1378. case 'revoke':
  1379. $action['icon'] = 'b_usrdrop';
  1380. $action['text'] = __('Revoke');
  1381. break;
  1382. case 'export':
  1383. $action['icon'] = 'b_tblexport';
  1384. $action['text'] = __('Export');
  1385. break;
  1386. }
  1387. return $this->template->render('server/privileges/get_user_link', [
  1388. 'link_class' => $linkClass,
  1389. 'is_revoke' => $linktype === 'revoke',
  1390. 'url_params' => $params,
  1391. 'action' => $action,
  1392. ]);
  1393. }
  1394. /**
  1395. * Returns number of defined user groups
  1396. */
  1397. public function getUserGroupCount(ConfigurableMenusFeature $configurableMenusFeature): int
  1398. {
  1399. $userGroupTable = Util::backquote($configurableMenusFeature->database)
  1400. . '.' . Util::backquote($configurableMenusFeature->userGroups);
  1401. $sqlQuery = 'SELECT COUNT(*) FROM ' . $userGroupTable;
  1402. return (int) $this->dbi->fetchValue($sqlQuery, 0, DatabaseInterface::CONNECT_CONTROL);
  1403. }
  1404. /**
  1405. * Returns name of user group that user is part of
  1406. *
  1407. * @param string $username User name
  1408. *
  1409. * @return mixed|null usergroup if found or null if not found
  1410. */
  1411. public function getUserGroupForUser($username)
  1412. {
  1413. $configurableMenusFeature = $this->relation->getRelationParameters()->configurableMenusFeature;
  1414. if ($configurableMenusFeature === null) {
  1415. return null;
  1416. }
  1417. $userTable = Util::backquote($configurableMenusFeature->database)
  1418. . '.' . Util::backquote($configurableMenusFeature->users);
  1419. $sqlQuery = 'SELECT `usergroup` FROM ' . $userTable
  1420. . ' WHERE `username` = \'' . $username . '\''
  1421. . ' LIMIT 1';
  1422. $usergroup = $this->dbi->fetchValue($sqlQuery, 0, DatabaseInterface::CONNECT_CONTROL);
  1423. if ($usergroup === false) {
  1424. return null;
  1425. }
  1426. return $usergroup;
  1427. }
  1428. /**
  1429. * This function return the extra data array for the ajax behavior
  1430. *
  1431. * @param string $password password
  1432. * @param string $sqlQuery sql query
  1433. * @param string $hostname hostname
  1434. * @param string $username username
  1435. *
  1436. * @return array
  1437. */
  1438. public function getExtraDataForAjaxBehavior(
  1439. $password,
  1440. $sqlQuery,
  1441. $hostname,
  1442. $username
  1443. ) {
  1444. if (isset($GLOBALS['dbname'])) {
  1445. //if (preg_match('/\\\\(?:_|%)/i', $dbname)) {
  1446. if (preg_match('/(?<!\\\\)(?:_|%)/', $GLOBALS['dbname'])) {
  1447. $dbnameIsWildcard = true;
  1448. } else {
  1449. $dbnameIsWildcard = false;
  1450. }
  1451. }
  1452. $configurableMenusFeature = $this->relation->getRelationParameters()->configurableMenusFeature;
  1453. $userGroupCount = 0;
  1454. if ($configurableMenusFeature !== null) {
  1455. $userGroupCount = $this->getUserGroupCount($configurableMenusFeature);
  1456. }
  1457. $extraData = [];
  1458. if (strlen($sqlQuery) > 0) {
  1459. $extraData['sql_query'] = Generator::getMessage('', $sqlQuery);
  1460. }
  1461. if (isset($_POST['change_copy'])) {
  1462. $user = [
  1463. 'name' => $username,
  1464. 'host' => $hostname,
  1465. 'has_password' => ! empty($password) || isset($_POST['pma_pw']),
  1466. 'privileges' => implode(', ', $this->extractPrivInfo(null, true)),
  1467. 'has_group' => $configurableMenusFeature !== null,
  1468. 'has_group_edit' => $configurableMenusFeature !== null && $userGroupCount > 0,
  1469. 'has_grant' => isset($_POST['Grant_priv']) && $_POST['Grant_priv'] === 'Y',
  1470. ];
  1471. $extraData['new_user_string'] = $this->template->render('server/privileges/new_user_ajax', [
  1472. 'user' => $user,
  1473. 'is_grantuser' => $this->dbi->isGrantUser(),
  1474. 'initial' => $_GET['initial'] ?? '',
  1475. ]);
  1476. /**
  1477. * Generate the string for this alphabet's initial, to update the user
  1478. * pagination
  1479. */
  1480. $newUserInitial = mb_strtoupper(
  1481. mb_substr($username, 0, 1)
  1482. );
  1483. $newUserInitialString = '<a href="';
  1484. $newUserInitialString .= Url::getFromRoute('/server/privileges', ['initial' => $newUserInitial]);
  1485. $newUserInitialString .= '">' . $newUserInitial . '</a>';
  1486. $extraData['new_user_initial'] = $newUserInitial;
  1487. $extraData['new_user_initial_string'] = $newUserInitialString;
  1488. }
  1489. if (isset($_POST['update_privs'])) {
  1490. $extraData['db_specific_privs'] = false;
  1491. $extraData['db_wildcard_privs'] = false;
  1492. if (isset($dbnameIsWildcard)) {
  1493. $extraData['db_specific_privs'] = ! $dbnameIsWildcard;
  1494. $extraData['db_wildcard_privs'] = $dbnameIsWildcard;
  1495. }
  1496. $newPrivileges = implode(', ', $this->extractPrivInfo(null, true));
  1497. $extraData['new_privileges'] = $newPrivileges;
  1498. }
  1499. if (isset($_GET['validate_username'])) {
  1500. $sqlQuery = "SELECT * FROM `mysql`.`user` WHERE `User` = '"
  1501. . $this->dbi->escapeString($_GET['username']) . "';";
  1502. $res = $this->dbi->query($sqlQuery);
  1503. $extraData['user_exists'] = $res->fetchRow() !== [];
  1504. }
  1505. return $extraData;
  1506. }
  1507. /**
  1508. * no db name given, so we want all privs for the given user
  1509. * db name was given, so we want all user specific rights for this db
  1510. * So this function returns user rights as an array
  1511. *
  1512. * @param string $username username
  1513. * @param string $hostname host name
  1514. * @param string $type database or table
  1515. * @param string $dbname database name
  1516. *
  1517. * @return array database rights
  1518. */
  1519. public function getUserSpecificRights($username, $hostname, $type, $dbname = '')
  1520. {
  1521. $userHostCondition = ' WHERE `User`'
  1522. . " = '" . $this->dbi->escapeString($username) . "'"
  1523. . ' AND `Host`'
  1524. . " = '" . $this->dbi->escapeString($hostname) . "'";
  1525. if ($type === 'database') {
  1526. $tablesToSearchForUsers = [
  1527. 'tables_priv',
  1528. 'columns_priv',
  1529. 'procs_priv',
  1530. ];
  1531. $dbOrTableName = 'Db';
  1532. } elseif ($type === 'table') {
  1533. $userHostCondition .= " AND `Db` LIKE '"
  1534. . $this->dbi->escapeString($dbname) . "'";
  1535. $tablesToSearchForUsers = ['columns_priv'];
  1536. $dbOrTableName = 'Table_name';
  1537. } else { // routine
  1538. $userHostCondition .= " AND `Db` LIKE '"
  1539. . $this->dbi->escapeString($dbname) . "'";
  1540. $tablesToSearchForUsers = ['procs_priv'];
  1541. $dbOrTableName = 'Routine_name';
  1542. }
  1543. // we also want privileges for this user not in table `db` but in other table
  1544. $tables = $this->dbi->fetchResult('SHOW TABLES FROM `mysql`;');
  1545. $dbRightsSqls = [];
  1546. foreach ($tablesToSearchForUsers as $tableSearchIn) {
  1547. if (! in_array($tableSearchIn, $tables)) {
  1548. continue;
  1549. }
  1550. $dbRightsSqls[] = '
  1551. SELECT DISTINCT `' . $dbOrTableName . '`
  1552. FROM `mysql`.' . Util::backquote($tableSearchIn)
  1553. . $userHostCondition;
  1554. }
  1555. $userDefaults = [
  1556. $dbOrTableName => '',
  1557. 'Grant_priv' => 'N',
  1558. 'privs' => ['USAGE'],
  1559. 'Column_priv' => true,
  1560. ];
  1561. // for the rights
  1562. $dbRights = [];
  1563. $dbRightsSql = '(' . implode(') UNION (', $dbRightsSqls) . ')'
  1564. . ' ORDER BY `' . $dbOrTableName . '` ASC';
  1565. $dbRightsResult = $this->dbi->query($dbRightsSql);
  1566. while ($dbRightsRow = $dbRightsResult->fetchAssoc()) {
  1567. $dbRightsRow = array_merge($userDefaults, $dbRightsRow);
  1568. if ($type === 'database') {
  1569. // only Db names in the table `mysql`.`db` uses wildcards
  1570. // as we are in the db specific rights display we want
  1571. // all db names escaped, also from other sources
  1572. $dbRightsRow['Db'] = Util::escapeMysqlWildcards($dbRightsRow['Db']);
  1573. }
  1574. $dbRights[$dbRightsRow[$dbOrTableName]] = $dbRightsRow;
  1575. }
  1576. if ($type === 'database') {
  1577. $sqlQuery = 'SELECT * FROM `mysql`.`db`'
  1578. . $userHostCondition . ' ORDER BY `Db` ASC';
  1579. } elseif ($type === 'table') {
  1580. $sqlQuery = 'SELECT `Table_name`,'
  1581. . ' `Table_priv`,'
  1582. . ' IF(`Column_priv` = _latin1 \'\', 0, 1)'
  1583. . ' AS \'Column_priv\''
  1584. . ' FROM `mysql`.`tables_priv`'
  1585. . $userHostCondition
  1586. . ' ORDER BY `Table_name` ASC;';
  1587. } else {
  1588. $sqlQuery = 'SELECT `Routine_name`, `Proc_priv`'
  1589. . ' FROM `mysql`.`procs_priv`'
  1590. . $userHostCondition
  1591. . ' ORDER BY `Routine_name`';
  1592. }
  1593. $result = $this->dbi->query($sqlQuery);
  1594. while ($row = $result->fetchAssoc()) {
  1595. if (isset($dbRights[$row[$dbOrTableName]])) {
  1596. $dbRights[$row[$dbOrTableName]] = array_merge($dbRights[$row[$dbOrTableName]], $row);
  1597. } else {
  1598. $dbRights[$row[$dbOrTableName]] = $row;
  1599. }
  1600. if ($type !== 'database') {
  1601. continue;
  1602. }
  1603. // there are db specific rights for this user
  1604. // so we can drop this db rights
  1605. $dbRights[$row['Db']]['can_delete'] = true;
  1606. }
  1607. return $dbRights;
  1608. }
  1609. /**
  1610. * Parses Proc_priv data
  1611. *
  1612. * @param string $privs Proc_priv
  1613. *
  1614. * @return array
  1615. */
  1616. public function parseProcPriv($privs)
  1617. {
  1618. $result = [
  1619. 'Alter_routine_priv' => 'N',
  1620. 'Execute_priv' => 'N',
  1621. 'Grant_priv' => 'N',
  1622. ];
  1623. foreach (explode(',', (string) $privs) as $priv) {
  1624. if ($priv === 'Alter Routine') {
  1625. $result['Alter_routine_priv'] = 'Y';
  1626. } else {
  1627. $result[$priv . '_priv'] = 'Y';
  1628. }
  1629. }
  1630. return $result;
  1631. }
  1632. /**
  1633. * Get a HTML table for display user's table specific or database specific rights
  1634. *
  1635. * @param string $username username
  1636. * @param string $hostname host name
  1637. * @param string $type database, table or routine
  1638. * @param string $dbname database name
  1639. *
  1640. * @return string
  1641. */
  1642. public function getHtmlForAllTableSpecificRights(
  1643. $username,
  1644. $hostname,
  1645. $type,
  1646. $dbname = ''
  1647. ) {
  1648. $uiData = [
  1649. 'database' => [
  1650. 'form_id' => 'database_specific_priv',
  1651. 'sub_menu_label' => __('Database'),
  1652. 'legend' => __('Database-specific privileges'),
  1653. 'type_label' => __('Database'),
  1654. ],
  1655. 'table' => [
  1656. 'form_id' => 'table_specific_priv',
  1657. 'sub_menu_label' => __('Table'),
  1658. 'legend' => __('Table-specific privileges'),
  1659. 'type_label' => __('Table'),
  1660. ],
  1661. 'routine' => [
  1662. 'form_id' => 'routine_specific_priv',
  1663. 'sub_menu_label' => __('Routine'),
  1664. 'legend' => __('Routine-specific privileges'),
  1665. 'type_label' => __('Routine'),
  1666. ],
  1667. ];
  1668. /**
  1669. * no db name given, so we want all privs for the given user
  1670. * db name was given, so we want all user specific rights for this db
  1671. */
  1672. $dbRights = $this->getUserSpecificRights($username, $hostname, $type, $dbname);
  1673. ksort($dbRights);
  1674. $foundRows = [];
  1675. $privileges = [];
  1676. foreach ($dbRights as $row) {
  1677. $onePrivilege = [];
  1678. $paramTableName = '';
  1679. $paramRoutineName = '';
  1680. if ($type === 'database') {
  1681. $name = $row['Db'];
  1682. $onePrivilege['grant'] = $row['Grant_priv'] === 'Y';
  1683. $onePrivilege['table_privs'] = ! empty($row['Table_priv'])
  1684. || ! empty($row['Column_priv']);
  1685. $onePrivilege['privileges'] = implode(',', $this->extractPrivInfo($row, true));
  1686. $paramDbName = $row['Db'];
  1687. } elseif ($type === 'table') {
  1688. $name = $row['Table_name'];
  1689. $onePrivilege['grant'] = in_array(
  1690. 'Grant',
  1691. explode(',', $row['Table_priv'])
  1692. );
  1693. $onePrivilege['column_privs'] = ! empty($row['Column_priv']);
  1694. $onePrivilege['privileges'] = implode(',', $this->extractPrivInfo($row, true));
  1695. $paramDbName = Util::escapeMysqlWildcards($dbname);
  1696. $paramTableName = $row['Table_name'];
  1697. } else { // routine
  1698. $name = $row['Routine_name'];
  1699. $onePrivilege['grant'] = in_array(
  1700. 'Grant',
  1701. explode(',', $row['Proc_priv'])
  1702. );
  1703. $privs = $this->parseProcPriv($row['Proc_priv']);
  1704. $onePrivilege['privileges'] = implode(
  1705. ',',
  1706. $this->extractPrivInfo($privs, true)
  1707. );
  1708. $paramDbName = Util::escapeMysqlWildcards($dbname);
  1709. $paramRoutineName = $row['Routine_name'];
  1710. }
  1711. $foundRows[] = $name;
  1712. $onePrivilege['name'] = $name;
  1713. $onePrivilege['edit_link'] = '';
  1714. if ($this->dbi->isGrantUser()) {
  1715. $onePrivilege['edit_link'] = $this->getUserLink(
  1716. 'edit',
  1717. $username,
  1718. $hostname,
  1719. $paramDbName,
  1720. $paramTableName,
  1721. $paramRoutineName
  1722. );
  1723. }
  1724. $onePrivilege['revoke_link'] = '';
  1725. if ($type !== 'database' || ! empty($row['can_delete'])) {
  1726. $onePrivilege['revoke_link'] = $this->getUserLink(
  1727. 'revoke',
  1728. $username,
  1729. $hostname,
  1730. $paramDbName,
  1731. $paramTableName,
  1732. $paramRoutineName
  1733. );
  1734. }
  1735. $privileges[] = $onePrivilege;
  1736. }
  1737. $data = $uiData[$type];
  1738. $data['privileges'] = $privileges;
  1739. $data['username'] = $username;
  1740. $data['hostname'] = $hostname;
  1741. $data['database'] = $dbname;
  1742. $data['type'] = $type;
  1743. if ($type === 'database') {
  1744. $predDbArray = $GLOBALS['dblist']->databases;
  1745. $databasesToSkip = [
  1746. 'information_schema',
  1747. 'performance_schema',
  1748. ];
  1749. $databases = [];
  1750. $escapedDatabases = [];
  1751. if (! empty($predDbArray)) {
  1752. foreach ($predDbArray as $currentDb) {
  1753. if (in_array($currentDb, $databasesToSkip)) {
  1754. continue;
  1755. }
  1756. $currentDbEscaped = Util::escapeMysqlWildcards($currentDb);
  1757. // cannot use array_diff() once, outside of the loop,
  1758. // because the list of databases has special characters
  1759. // already escaped in $foundRows,
  1760. // contrary to the output of SHOW DATABASES
  1761. if (in_array($currentDbEscaped, $foundRows)) {
  1762. continue;
  1763. }
  1764. $databases[] = $currentDb;
  1765. $escapedDatabases[] = $currentDbEscaped;
  1766. }
  1767. }
  1768. $data['databases'] = $databases;
  1769. $data['escaped_databases'] = $escapedDatabases;
  1770. } elseif ($type === 'table') {
  1771. $result = $this->dbi->tryQuery('SHOW TABLES FROM ' . Util::backquote($dbname));
  1772. $tables = [];
  1773. if ($result) {
  1774. while ($row = $result->fetchRow()) {
  1775. if (in_array($row[0], $foundRows)) {
  1776. continue;
  1777. }
  1778. $tables[] = $row[0];
  1779. }
  1780. }
  1781. $data['tables'] = $tables;
  1782. } else { // routine
  1783. $routineData = $this->dbi->getRoutines($dbname);
  1784. $routines = [];
  1785. foreach ($routineData as $routine) {
  1786. if (in_array($routine['name'], $foundRows)) {
  1787. continue;
  1788. }
  1789. $routines[] = $routine['name'];
  1790. }
  1791. $data['routines'] = $routines;
  1792. }
  1793. return $this->template->render('server/privileges/privileges_summary', $data);
  1794. }
  1795. /**
  1796. * Get HTML for display the users overview
  1797. * (if less than 50 users, display them immediately)
  1798. *
  1799. * @param ResultInterface $result ran sql query
  1800. * @param array $dbRights user's database rights array
  1801. * @param string $textDir text directory
  1802. *
  1803. * @return string HTML snippet
  1804. */
  1805. public function getUsersOverview(ResultInterface $result, array $dbRights, $textDir)
  1806. {
  1807. $configurableMenusFeature = $this->relation->getRelationParameters()->configurableMenusFeature;
  1808. while ($row = $result->fetchAssoc()) {
  1809. $row['privs'] = $this->extractPrivInfo($row, true);
  1810. $dbRights[$row['User']][$row['Host']] = $row;
  1811. }
  1812. unset($result);
  1813. $userGroupCount = 0;
  1814. if ($configurableMenusFeature !== null) {
  1815. $sqlQuery = 'SELECT * FROM ' . Util::backquote($configurableMenusFeature->database)
  1816. . '.' . Util::backquote($configurableMenusFeature->users);
  1817. $result = $this->dbi->tryQueryAsControlUser($sqlQuery);
  1818. $groupAssignment = [];
  1819. if ($result) {
  1820. while ($row = $result->fetchAssoc()) {
  1821. $groupAssignment[$row['username']] = $row['usergroup'];
  1822. }
  1823. }
  1824. unset($result);
  1825. $userGroupCount = $this->getUserGroupCount($configurableMenusFeature);
  1826. }
  1827. $hosts = [];
  1828. $hasAccountLocking = Compatibility::hasAccountLocking($this->dbi->isMariaDB(), $this->dbi->getVersion());
  1829. foreach ($dbRights as $user) {
  1830. ksort($user);
  1831. foreach ($user as $host) {
  1832. $res = $this->getUserPrivileges((string) $host['User'], (string) $host['Host'], $hasAccountLocking);
  1833. $hasPassword = false;
  1834. if (
  1835. (isset($res['authentication_string'])
  1836. && ! empty($res['authentication_string']))
  1837. || (isset($res['Password'])
  1838. && ! empty($res['Password']))
  1839. ) {
  1840. $hasPassword = true;
  1841. }
  1842. $hosts[] = [
  1843. 'user' => $host['User'],
  1844. 'host' => $host['Host'],
  1845. 'has_password' => $hasPassword,
  1846. 'has_select_priv' => isset($host['Select_priv']),
  1847. 'privileges' => $host['privs'],
  1848. 'group' => $groupAssignment[$host['User']] ?? '',
  1849. 'has_grant' => $host['Grant_priv'] === 'Y',
  1850. 'is_account_locked' => isset($res['account_locked']) && $res['account_locked'] === 'Y',
  1851. ];
  1852. }
  1853. }
  1854. return $this->template->render('server/privileges/users_overview', [
  1855. 'menus_work' => $configurableMenusFeature !== null,
  1856. 'user_group_count' => $userGroupCount,
  1857. 'text_dir' => $textDir,
  1858. 'initial' => $_GET['initial'] ?? '',
  1859. 'hosts' => $hosts,
  1860. 'is_grantuser' => $this->dbi->isGrantUser(),
  1861. 'is_createuser' => $this->dbi->isCreateUser(),
  1862. 'has_account_locking' => $hasAccountLocking,
  1863. ]);
  1864. }
  1865. /**
  1866. * Get HTML for Displays the initials
  1867. *
  1868. * @return string HTML snippet
  1869. */
  1870. public function getHtmlForInitials()
  1871. {
  1872. $arrayInitials = [];
  1873. // initialize to false the letters A-Z
  1874. for ($letterCounter = 1; $letterCounter < 27; $letterCounter++) {
  1875. $arrayInitials[mb_chr($letterCounter + 64)] = false;
  1876. }
  1877. $initials = $this->dbi->tryQuery(
  1878. 'SELECT DISTINCT UPPER(LEFT(`User`,1)) FROM `user` ORDER BY UPPER(LEFT(`User`,1)) ASC'
  1879. );
  1880. if ($initials) {
  1881. while ($tmpInitial = $initials->fetchRow()) {
  1882. $arrayInitials[$tmpInitial[0]] = true;
  1883. }
  1884. }
  1885. // Display the initials, which can be any characters, not
  1886. // just letters. For letters A-Z, we add the non-used letters
  1887. // as greyed out.
  1888. uksort($arrayInitials, 'strnatcasecmp');
  1889. return $this->template->render('server/privileges/initials_row', [
  1890. 'array_initials' => $arrayInitials,
  1891. 'initial' => $_GET['initial'] ?? null,
  1892. 'viewing_mode' => $_GET['viewing_mode'] ?? null,
  1893. ]);
  1894. }
  1895. /**
  1896. * Get the database rights array for Display user overview
  1897. *
  1898. * @return array database rights array
  1899. */
  1900. public function getDbRightsForUserOverview()
  1901. {
  1902. // we also want users not in table `user` but in other table
  1903. $tables = $this->dbi->fetchResult('SHOW TABLES FROM `mysql`;');
  1904. $tablesSearchForUsers = [
  1905. 'user',
  1906. 'db',
  1907. 'tables_priv',
  1908. 'columns_priv',
  1909. 'procs_priv',
  1910. ];
  1911. $dbRightsSqls = [];
  1912. foreach ($tablesSearchForUsers as $tableSearchIn) {
  1913. if (! in_array($tableSearchIn, $tables)) {
  1914. continue;
  1915. }
  1916. $dbRightsSqls[] = 'SELECT DISTINCT `User`, `Host` FROM `mysql`.`'
  1917. . $tableSearchIn . '` '
  1918. . (isset($_GET['initial'])
  1919. ? $this->rangeOfUsers($_GET['initial'])
  1920. : '');
  1921. }
  1922. $userDefaults = [
  1923. 'User' => '',
  1924. 'Host' => '%',
  1925. 'Password' => '?',
  1926. 'Grant_priv' => 'N',
  1927. 'privs' => ['USAGE'],
  1928. ];
  1929. // for the rights
  1930. $dbRights = [];
  1931. $dbRightsSql = '(' . implode(') UNION (', $dbRightsSqls) . ')'
  1932. . ' ORDER BY `User` ASC, `Host` ASC';
  1933. $dbRightsResult = $this->dbi->query($dbRightsSql);
  1934. while ($dbRightsRow = $dbRightsResult->fetchAssoc()) {
  1935. $dbRightsRow = array_merge($userDefaults, $dbRightsRow);
  1936. $dbRights[$dbRightsRow['User']][$dbRightsRow['Host']] = $dbRightsRow;
  1937. }
  1938. ksort($dbRights);
  1939. return $dbRights;
  1940. }
  1941. /**
  1942. * Delete user and get message and sql query for delete user in privileges
  1943. *
  1944. * @param array $queries queries
  1945. *
  1946. * @return array Message
  1947. */
  1948. public function deleteUser(array $queries)
  1949. {
  1950. $sqlQuery = '';
  1951. if (empty($queries)) {
  1952. $message = Message::error(__('No users selected for deleting!'));
  1953. } else {
  1954. if ($_POST['mode'] == 3) {
  1955. $queries[] = '# ' . __('Reloading the privileges') . ' …';
  1956. $queries[] = 'FLUSH PRIVILEGES;';
  1957. }
  1958. $dropUserError = '';
  1959. foreach ($queries as $sqlQuery) {
  1960. if ($sqlQuery[0] === '#') {
  1961. continue;
  1962. }
  1963. if ($this->dbi->tryQuery($sqlQuery)) {
  1964. continue;
  1965. }
  1966. $dropUserError .= $this->dbi->getError() . "\n";
  1967. }
  1968. // tracking sets this, causing the deleted db to be shown in navi
  1969. unset($GLOBALS['db']);
  1970. $sqlQuery = implode("\n", $queries);
  1971. if (! empty($dropUserError)) {
  1972. $message = Message::rawError($dropUserError);
  1973. } else {
  1974. $message = Message::success(
  1975. __('The selected users have been deleted successfully.')
  1976. );
  1977. }
  1978. }
  1979. return [
  1980. $sqlQuery,
  1981. $message,
  1982. ];
  1983. }
  1984. /**
  1985. * Update the privileges and return the success or error message
  1986. *
  1987. * @return array success message or error message for update
  1988. */
  1989. public function updatePrivileges(
  1990. string $username,
  1991. string $hostname,
  1992. string $tablename,
  1993. string $dbname,
  1994. string $itemType
  1995. ): array {
  1996. $dbAndTable = $this->wildcardEscapeForGrant($dbname, $tablename);
  1997. $sqlQuery0 = 'REVOKE ALL PRIVILEGES ON ' . $itemType . ' ' . $dbAndTable
  1998. . ' FROM \'' . $this->dbi->escapeString($username)
  1999. . '\'@\'' . $this->dbi->escapeString($hostname) . '\';';
  2000. if (! isset($_POST['Grant_priv']) || $_POST['Grant_priv'] !== 'Y') {
  2001. $sqlQuery1 = 'REVOKE GRANT OPTION ON ' . $itemType . ' ' . $dbAndTable
  2002. . ' FROM \'' . $this->dbi->escapeString($username) . '\'@\''
  2003. . $this->dbi->escapeString($hostname) . '\';';
  2004. } else {
  2005. $sqlQuery1 = '';
  2006. }
  2007. $grantBackQuery = null;
  2008. $alterUserQuery = null;
  2009. // Should not do a GRANT USAGE for a table-specific privilege, it
  2010. // causes problems later (cannot revoke it)
  2011. if (! (strlen($tablename) > 0 && implode('', $this->extractPrivInfo()) === 'USAGE')) {
  2012. [$grantBackQuery, $alterUserQuery] = $this->generateQueriesForUpdatePrivileges(
  2013. $itemType,
  2014. $dbAndTable,
  2015. $username,
  2016. $hostname,
  2017. $dbname
  2018. );
  2019. }
  2020. if (! $this->dbi->tryQuery($sqlQuery0)) {
  2021. // This might fail when the executing user does not have
  2022. // ALL PRIVILEGES themselves.
  2023. // See https://github.com/phpmyadmin/phpmyadmin/issues/9673
  2024. $sqlQuery0 = '';
  2025. }
  2026. if (! empty($sqlQuery1) && ! $this->dbi->tryQuery($sqlQuery1)) {
  2027. // this one may fail, too...
  2028. $sqlQuery1 = '';
  2029. }
  2030. if ($grantBackQuery !== null) {
  2031. $this->dbi->query($grantBackQuery);
  2032. } else {
  2033. $grantBackQuery = '';
  2034. }
  2035. if ($alterUserQuery !== null) {
  2036. $this->dbi->query($alterUserQuery);
  2037. } else {
  2038. $alterUserQuery = '';
  2039. }
  2040. $sqlQuery = $sqlQuery0 . ' ' . $sqlQuery1 . ' ' . $grantBackQuery . ' ' . $alterUserQuery;
  2041. $message = Message::success(__('You have updated the privileges for %s.'));
  2042. $message->addParam('\'' . $username . '\'@\'' . $hostname . '\'');
  2043. return [
  2044. $sqlQuery,
  2045. $message,
  2046. ];
  2047. }
  2048. /**
  2049. * Generate the query for the GRANTS and requirements + limits
  2050. *
  2051. * @return array<int,string|null>
  2052. */
  2053. private function generateQueriesForUpdatePrivileges(
  2054. string $itemType,
  2055. string $dbAndTable,
  2056. string $username,
  2057. string $hostname,
  2058. string $dbname
  2059. ): array {
  2060. $alterUserQuery = null;
  2061. $grantBackQuery = 'GRANT ' . implode(', ', $this->extractPrivInfo())
  2062. . ' ON ' . $itemType . ' ' . $dbAndTable
  2063. . ' TO \'' . $this->dbi->escapeString($username) . '\'@\''
  2064. . $this->dbi->escapeString($hostname) . '\'';
  2065. $isMySqlOrPercona = Compatibility::isMySqlOrPerconaDb();
  2066. $needsToUseAlter = $isMySqlOrPercona && $this->dbi->getVersion() >= 80011;
  2067. if ($needsToUseAlter) {
  2068. $alterUserQuery = 'ALTER USER \'' . $this->dbi->escapeString($username) . '\'@\''
  2069. . $this->dbi->escapeString($hostname) . '\' ';
  2070. }
  2071. if (strlen($dbname) === 0) {
  2072. // add REQUIRE clause
  2073. if ($needsToUseAlter) {
  2074. $alterUserQuery .= $this->getRequireClause();
  2075. } else {
  2076. $grantBackQuery .= $this->getRequireClause();
  2077. }
  2078. }
  2079. if (
  2080. (isset($_POST['Grant_priv']) && $_POST['Grant_priv'] === 'Y')
  2081. || (strlen($dbname) === 0
  2082. && (isset($_POST['max_questions']) || isset($_POST['max_connections'])
  2083. || isset($_POST['max_updates'])
  2084. || isset($_POST['max_user_connections'])))
  2085. ) {
  2086. if ($needsToUseAlter) {
  2087. $alterUserQuery .= $this->getWithClauseForAddUserAndUpdatePrivs();
  2088. } else {
  2089. $grantBackQuery .= $this->getWithClauseForAddUserAndUpdatePrivs();
  2090. }
  2091. }
  2092. $grantBackQuery .= ';';
  2093. if ($needsToUseAlter) {
  2094. $alterUserQuery .= ';';
  2095. }
  2096. return [$grantBackQuery, $alterUserQuery];
  2097. }
  2098. /**
  2099. * Get List of information: Changes / copies a user
  2100. *
  2101. * @return array
  2102. */
  2103. public function getDataForChangeOrCopyUser()
  2104. {
  2105. $queries = null;
  2106. $password = null;
  2107. if (isset($_POST['change_copy'])) {
  2108. $userHostCondition = ' WHERE `User` = '
  2109. . "'" . $this->dbi->escapeString($_POST['old_username']) . "'"
  2110. . ' AND `Host` = '
  2111. . "'" . $this->dbi->escapeString($_POST['old_hostname']) . "';";
  2112. $row = $this->dbi->fetchSingleRow('SELECT * FROM `mysql`.`user` ' . $userHostCondition);
  2113. if (! $row) {
  2114. $response = ResponseRenderer::getInstance();
  2115. $response->addHTML(
  2116. Message::notice(__('No user found.'))->getDisplay()
  2117. );
  2118. unset($_POST['change_copy']);
  2119. } else {
  2120. foreach ($row as $key => $value) {
  2121. $GLOBALS[$key] = $value;
  2122. }
  2123. $serverVersion = $this->dbi->getVersion();
  2124. // Recent MySQL versions have the field "Password" in mysql.user,
  2125. // so the previous extract creates $row['Password'] but this script
  2126. // uses $password
  2127. if (! isset($row['password']) && isset($row['Password'])) {
  2128. $row['password'] = $row['Password'];
  2129. }
  2130. if (
  2131. Compatibility::isMySqlOrPerconaDb()
  2132. && $serverVersion >= 50606
  2133. && $serverVersion < 50706
  2134. && ((isset($row['authentication_string'])
  2135. && empty($row['password']))
  2136. || (isset($row['plugin'])
  2137. && $row['plugin'] === 'sha256_password'))
  2138. ) {
  2139. $row['password'] = $row['authentication_string'];
  2140. }
  2141. if (
  2142. Compatibility::isMariaDb()
  2143. && $serverVersion >= 50500
  2144. && isset($row['authentication_string'])
  2145. && empty($row['password'])
  2146. ) {
  2147. $row['password'] = $row['authentication_string'];
  2148. }
  2149. // Always use 'authentication_string' column
  2150. // for MySQL 5.7.6+ since it does not have
  2151. // the 'password' column at all
  2152. if (
  2153. Compatibility::isMySqlOrPerconaDb()
  2154. && $serverVersion >= 50706
  2155. && isset($row['authentication_string'])
  2156. ) {
  2157. $row['password'] = $row['authentication_string'];
  2158. }
  2159. $password = $row['password'];
  2160. $queries = [];
  2161. }
  2162. }
  2163. return [
  2164. $queries,
  2165. $password,
  2166. ];
  2167. }
  2168. /**
  2169. * Update Data for information: Deletes users
  2170. *
  2171. * @param array $queries queries array
  2172. *
  2173. * @return array
  2174. */
  2175. public function getDataForDeleteUsers($queries)
  2176. {
  2177. if (isset($_POST['change_copy'])) {
  2178. $selectedUsr = [
  2179. $_POST['old_username'] . '&amp;#27;' . $_POST['old_hostname'],
  2180. ];
  2181. } else {
  2182. // null happens when no user was selected
  2183. $selectedUsr = $_POST['selected_usr'] ?? null;
  2184. $queries = [];
  2185. }
  2186. // this happens, was seen in https://reports.phpmyadmin.net/reports/view/17146
  2187. if (! is_array($selectedUsr)) {
  2188. return [];
  2189. }
  2190. foreach ($selectedUsr as $eachUser) {
  2191. [$thisUser, $thisHost] = explode('&amp;#27;', $eachUser);
  2192. $queries[] = '# '
  2193. . sprintf(
  2194. __('Deleting %s'),
  2195. '\'' . $thisUser . '\'@\'' . $thisHost . '\''
  2196. )
  2197. . ' ...';
  2198. $queries[] = 'DROP USER \''
  2199. . $this->dbi->escapeString($thisUser)
  2200. . '\'@\'' . $this->dbi->escapeString($thisHost) . '\';';
  2201. $this->relationCleanup->user($thisUser);
  2202. if (! isset($_POST['drop_users_db'])) {
  2203. continue;
  2204. }
  2205. $queries[] = 'DROP DATABASE IF EXISTS '
  2206. . Util::backquote($thisUser) . ';';
  2207. $GLOBALS['reload'] = true;
  2208. }
  2209. return $queries;
  2210. }
  2211. /**
  2212. * update Message For Reload
  2213. */
  2214. public function updateMessageForReload(): ?Message
  2215. {
  2216. $message = null;
  2217. if (isset($_GET['flush_privileges'])) {
  2218. $this->dbi->tryQuery('FLUSH PRIVILEGES;');
  2219. $message = Message::success(
  2220. __('The privileges were reloaded successfully.')
  2221. );
  2222. }
  2223. if (isset($_GET['validate_username'])) {
  2224. $message = Message::success();
  2225. }
  2226. return $message;
  2227. }
  2228. /**
  2229. * update Data For Queries from queries_for_display
  2230. *
  2231. * @param array $queries queries array
  2232. * @param array|null $queriesForDisplay queries array for display
  2233. *
  2234. * @return array
  2235. */
  2236. public function getDataForQueries(array $queries, $queriesForDisplay)
  2237. {
  2238. $tmpCount = 0;
  2239. foreach ($queries as $sqlQuery) {
  2240. if ($sqlQuery[0] !== '#') {
  2241. $this->dbi->query($sqlQuery);
  2242. }
  2243. // when there is a query containing a hidden password, take it
  2244. // instead of the real query sent
  2245. if (isset($queriesForDisplay[$tmpCount])) {
  2246. $queries[$tmpCount] = $queriesForDisplay[$tmpCount];
  2247. }
  2248. $tmpCount++;
  2249. }
  2250. return $queries;
  2251. }
  2252. /**
  2253. * update Data for information: Adds a user
  2254. *
  2255. * @param string|array|null $dbname db name
  2256. * @param string $username user name
  2257. * @param string $hostname host name
  2258. * @param string|null $password password
  2259. * @param bool $isMenuwork is_menuwork set?
  2260. *
  2261. * @return array
  2262. */
  2263. public function addUser(
  2264. $dbname,
  2265. string $username,
  2266. string $hostname,
  2267. ?string $password,
  2268. $isMenuwork
  2269. ) {
  2270. $message = null;
  2271. $queries = null;
  2272. $queriesForDisplay = null;
  2273. $sqlQuery = '';
  2274. if (! isset($_POST['adduser_submit']) && ! isset($_POST['change_copy'])) {
  2275. return [
  2276. $message,
  2277. $queries,
  2278. $queriesForDisplay,
  2279. $sqlQuery,
  2280. false, // Add user error
  2281. ];
  2282. }
  2283. // Some reports where sent to the error reporting server with phpMyAdmin 5.1.0
  2284. // pred_username was reported to be not defined
  2285. $predUsername = $_POST['pred_username'] ?? '';
  2286. if ($predUsername === 'any') {
  2287. $username = '';
  2288. }
  2289. switch ($_POST['pred_hostname']) {
  2290. case 'any':
  2291. $hostname = '%';
  2292. break;
  2293. case 'localhost':
  2294. $hostname = 'localhost';
  2295. break;
  2296. case 'hosttable':
  2297. $hostname = '';
  2298. break;
  2299. case 'thishost':
  2300. $currentUserName = $this->dbi->fetchValue('SELECT USER()');
  2301. if (is_string($currentUserName)) {
  2302. $hostname = mb_substr($currentUserName, mb_strrpos($currentUserName, '@') + 1);
  2303. unset($currentUserName);
  2304. }
  2305. break;
  2306. }
  2307. $sql = "SELECT '1' FROM `mysql`.`user`"
  2308. . " WHERE `User` = '" . $this->dbi->escapeString($username) . "'"
  2309. . " AND `Host` = '" . $this->dbi->escapeString($hostname) . "';";
  2310. if ($this->dbi->fetchValue($sql) == 1) {
  2311. $message = Message::error(__('The user %s already exists!'));
  2312. $message->addParam('[em]\'' . $username . '\'@\'' . $hostname . '\'[/em]');
  2313. $_GET['adduser'] = true;
  2314. return [
  2315. $message,
  2316. $queries,
  2317. $queriesForDisplay,
  2318. $sqlQuery,
  2319. true, // Add user error
  2320. ];
  2321. }
  2322. [
  2323. $createUserReal,
  2324. $createUserShow,
  2325. $realSqlQuery,
  2326. $sqlQuery,
  2327. $passwordSetReal,
  2328. $passwordSetShow,
  2329. $alterRealSqlQuery,
  2330. $alterSqlQuery,
  2331. ] = $this->getSqlQueriesForDisplayAndAddUser($username, $hostname, ($password ?? ''));
  2332. if (empty($_POST['change_copy'])) {
  2333. $error = false;
  2334. if ($createUserReal !== null) {
  2335. if (! $this->dbi->tryQuery($createUserReal)) {
  2336. $error = true;
  2337. }
  2338. if (isset($passwordSetReal, $_POST['authentication_plugin']) && ! empty($passwordSetReal)) {
  2339. $this->setProperPasswordHashing($_POST['authentication_plugin']);
  2340. if ($this->dbi->tryQuery($passwordSetReal)) {
  2341. $sqlQuery .= $passwordSetShow;
  2342. }
  2343. }
  2344. $sqlQuery = $createUserShow . $sqlQuery;
  2345. }
  2346. [$sqlQuery, $message] = $this->addUserAndCreateDatabase(
  2347. $error,
  2348. $realSqlQuery,
  2349. $sqlQuery,
  2350. $username,
  2351. $hostname,
  2352. $dbname,
  2353. $alterRealSqlQuery,
  2354. $alterSqlQuery,
  2355. isset($_POST['createdb-1']),
  2356. isset($_POST['createdb-2']),
  2357. isset($_POST['createdb-3'])
  2358. );
  2359. if (! empty($_POST['userGroup']) && $isMenuwork) {
  2360. $this->setUserGroup($GLOBALS['username'], $_POST['userGroup']);
  2361. }
  2362. return [
  2363. $message,
  2364. $queries,
  2365. $queriesForDisplay,
  2366. $sqlQuery,
  2367. $error, // Add user error if the query fails
  2368. ];
  2369. }
  2370. // Copy the user group while copying a user
  2371. $oldUserGroup = $_POST['old_usergroup'] ?? null;
  2372. $this->setUserGroup($_POST['username'], $oldUserGroup);
  2373. if ($createUserReal !== null) {
  2374. $queries[] = $createUserReal;
  2375. }
  2376. $queries[] = $realSqlQuery;
  2377. if (isset($passwordSetReal, $_POST['authentication_plugin']) && ! empty($passwordSetReal)) {
  2378. $this->setProperPasswordHashing($_POST['authentication_plugin']);
  2379. $queries[] = $passwordSetReal;
  2380. }
  2381. // we put the query containing the hidden password in
  2382. // $queries_for_display, at the same position occupied
  2383. // by the real query in $queries
  2384. $tmpCount = count($queries);
  2385. if (isset($createUserReal)) {
  2386. $queriesForDisplay[$tmpCount - 2] = $createUserShow;
  2387. }
  2388. if (isset($passwordSetReal) && ! empty($passwordSetReal)) {
  2389. $queriesForDisplay[$tmpCount - 3] = $createUserShow;
  2390. $queriesForDisplay[$tmpCount - 2] = $sqlQuery;
  2391. $queriesForDisplay[$tmpCount - 1] = $passwordSetShow;
  2392. } else {
  2393. $queriesForDisplay[$tmpCount - 1] = $sqlQuery;
  2394. }
  2395. return [
  2396. $message,
  2397. $queries,
  2398. $queriesForDisplay,
  2399. $sqlQuery,
  2400. false, // Add user error
  2401. ];
  2402. }
  2403. /**
  2404. * Sets proper value of `old_passwords` according to
  2405. * the authentication plugin selected
  2406. *
  2407. * @param string $authPlugin authentication plugin selected
  2408. */
  2409. public function setProperPasswordHashing($authPlugin): void
  2410. {
  2411. // Set the hashing method used by PASSWORD()
  2412. // to be of type depending upon $authentication_plugin
  2413. if ($authPlugin === 'sha256_password') {
  2414. $this->dbi->tryQuery('SET `old_passwords` = 2;');
  2415. } elseif ($authPlugin === 'mysql_old_password') {
  2416. $this->dbi->tryQuery('SET `old_passwords` = 1;');
  2417. } else {
  2418. $this->dbi->tryQuery('SET `old_passwords` = 0;');
  2419. }
  2420. }
  2421. /**
  2422. * Update DB information: DB, Table, isWildcard
  2423. *
  2424. * @return array
  2425. * @psalm-return array{?string, ?string, array|string|null, ?string, ?string, array|string, bool}
  2426. */
  2427. public function getDataForDBInfo()
  2428. {
  2429. $username = null;
  2430. $hostname = null;
  2431. $dbname = null;
  2432. $tablename = null;
  2433. $routinename = null;
  2434. if (isset($_REQUEST['username'])) {
  2435. $username = (string) $_REQUEST['username'];
  2436. }
  2437. if (isset($_REQUEST['hostname'])) {
  2438. $hostname = (string) $_REQUEST['hostname'];
  2439. }
  2440. /**
  2441. * Checks if a dropdown box has been used for selecting a database / table
  2442. */
  2443. if (
  2444. isset($_POST['pred_tablename'])
  2445. && is_string($_POST['pred_tablename'])
  2446. && $_POST['pred_tablename'] !== ''
  2447. ) {
  2448. $tablename = $_POST['pred_tablename'];
  2449. } elseif (
  2450. isset($_REQUEST['tablename'])
  2451. && is_string($_REQUEST['tablename'])
  2452. && $_REQUEST['tablename'] !== ''
  2453. ) {
  2454. $tablename = $_REQUEST['tablename'];
  2455. }
  2456. if (
  2457. isset($_POST['pred_routinename'])
  2458. && is_string($_POST['pred_routinename'])
  2459. && $_POST['pred_routinename'] !== ''
  2460. ) {
  2461. $routinename = $_POST['pred_routinename'];
  2462. } elseif (
  2463. isset($_REQUEST['routinename'])
  2464. && is_string($_REQUEST['routinename'])
  2465. && $_REQUEST['routinename'] !== ''
  2466. ) {
  2467. $routinename = $_REQUEST['routinename'];
  2468. }
  2469. if (isset($_POST['pred_dbname']) && is_array($_POST['pred_dbname'])) {
  2470. // Accept only array of non-empty strings
  2471. if ($_POST['pred_dbname'] === array_filter($_POST['pred_dbname'])) {
  2472. $dbname = $_POST['pred_dbname'];
  2473. // If dbname contains only one database.
  2474. if (count($dbname) === 1) {
  2475. $dbname = (string) $dbname[0];
  2476. }
  2477. }
  2478. }
  2479. if ($dbname === null && isset($_REQUEST['dbname'])) {
  2480. if (is_array($_REQUEST['dbname'])) {
  2481. // Accept only array of non-empty strings
  2482. if ($_REQUEST['dbname'] === array_filter($_REQUEST['dbname'])) {
  2483. $dbname = $_REQUEST['dbname'];
  2484. }
  2485. } elseif (
  2486. is_string($_REQUEST['dbname'])
  2487. && $_REQUEST['dbname'] !== ''
  2488. ) {
  2489. $dbname = $_REQUEST['dbname'];
  2490. }
  2491. }
  2492. $dbAndTable = '*.*';
  2493. if ($dbname === null) {
  2494. $tablename = null;
  2495. } else {
  2496. if (is_array($dbname)) {
  2497. $dbAndTable = $dbname;
  2498. foreach (array_keys($dbAndTable) as $key) {
  2499. $dbAndTable[$key] .= '.*';
  2500. }
  2501. } else {
  2502. $unescapedDb = Util::unescapeMysqlWildcards($dbname);
  2503. $dbAndTable = Util::backquote($unescapedDb) . '.';
  2504. if ($tablename !== null) {
  2505. $dbAndTable .= Util::backquote($tablename);
  2506. } else {
  2507. $dbAndTable .= '*';
  2508. }
  2509. }
  2510. }
  2511. // check if given $dbname is a wildcard or not
  2512. $databaseNameIsWildcard = is_string($dbname) && preg_match('/(?<!\\\\)(?:_|%)/', $dbname);
  2513. return [
  2514. $username,
  2515. $hostname,
  2516. $dbname,
  2517. $tablename,
  2518. $routinename,
  2519. $dbAndTable,
  2520. $databaseNameIsWildcard,
  2521. ];
  2522. }
  2523. /**
  2524. * Get title and textarea for export user definition in Privileges
  2525. *
  2526. * @param string $username username
  2527. * @param string $hostname host name
  2528. *
  2529. * @return array ($title, $export)
  2530. */
  2531. public function getListForExportUserDefinition(string $username, string $hostname)
  2532. {
  2533. $export = '<textarea class="export" cols="60" rows="15">';
  2534. /** @var array|null $selectedUsers */
  2535. $selectedUsers = $_POST['selected_usr'] ?? null;
  2536. if (isset($selectedUsers)) {
  2537. // export privileges for selected users
  2538. $title = __('Privileges');
  2539. //For removing duplicate entries of users
  2540. $selectedUsers = array_unique($selectedUsers);
  2541. foreach ($selectedUsers as $exportUser) {
  2542. $exportUsername = mb_substr(
  2543. $exportUser,
  2544. 0,
  2545. (int) mb_strpos($exportUser, '&')
  2546. );
  2547. $exportHostname = mb_substr(
  2548. $exportUser,
  2549. mb_strrpos($exportUser, ';') + 1
  2550. );
  2551. $export .= '# '
  2552. . sprintf(
  2553. __('Privileges for %s'),
  2554. '`' . htmlspecialchars($exportUsername)
  2555. . '`@`' . htmlspecialchars($exportHostname) . '`'
  2556. )
  2557. . "\n\n";
  2558. $export .= $this->getGrants($exportUsername, $exportHostname) . "\n";
  2559. }
  2560. } else {
  2561. // export privileges for a single user
  2562. $title = __('User') . ' `' . htmlspecialchars($username)
  2563. . '`@`' . htmlspecialchars($hostname) . '`';
  2564. $export .= $this->getGrants($username, $hostname);
  2565. }
  2566. // remove trailing whitespace
  2567. $export = trim($export);
  2568. $export .= '</textarea>';
  2569. return [
  2570. $title,
  2571. $export,
  2572. ];
  2573. }
  2574. /**
  2575. * Get HTML for display Add userfieldset
  2576. *
  2577. * @param string $db the database
  2578. * @param string $table the table name
  2579. *
  2580. * @return string html output
  2581. */
  2582. public function getAddUserHtmlFieldset($db = '', $table = '')
  2583. {
  2584. if (! $this->dbi->isCreateUser()) {
  2585. return '';
  2586. }
  2587. $relParams = [];
  2588. $urlParams = ['adduser' => 1];
  2589. if (! empty($db)) {
  2590. $urlParams['dbname'] = $relParams['checkprivsdb'] = $db;
  2591. }
  2592. if (! empty($table)) {
  2593. $urlParams['tablename'] = $relParams['checkprivstable'] = $table;
  2594. }
  2595. return $this->template->render('server/privileges/add_user_fieldset', [
  2596. 'url_params' => $urlParams,
  2597. 'rel_params' => $relParams,
  2598. ]);
  2599. }
  2600. /**
  2601. * Get HTML snippet for display user overview page
  2602. *
  2603. * @param string $textDir text directory
  2604. *
  2605. * @return string
  2606. */
  2607. public function getHtmlForUserOverview($textDir)
  2608. {
  2609. $passwordColumn = 'Password';
  2610. $serverVersion = $this->dbi->getVersion();
  2611. if (Compatibility::isMySqlOrPerconaDb() && $serverVersion >= 50706) {
  2612. $passwordColumn = 'authentication_string';
  2613. }
  2614. // $sql_query is for the initial-filtered,
  2615. // $sql_query_all is for counting the total no. of users
  2616. $sqlQuery = $sqlQueryAll = 'SELECT *,' .
  2617. ' IF(`' . $passwordColumn . "` = _latin1 '', 'N', 'Y') AS 'Password'" .
  2618. ' FROM `mysql`.`user`';
  2619. $sqlQuery .= (isset($_GET['initial'])
  2620. ? $this->rangeOfUsers($_GET['initial'])
  2621. : '');
  2622. $sqlQuery .= ' ORDER BY `User` ASC, `Host` ASC;';
  2623. $sqlQueryAll .= ' ;';
  2624. $res = $this->dbi->tryQuery($sqlQuery);
  2625. $resAll = $this->dbi->tryQuery($sqlQueryAll);
  2626. $errorMessages = '';
  2627. if (! $res) {
  2628. // the query failed! This may have two reasons:
  2629. // - the user does not have enough privileges
  2630. // - the privilege tables use a structure of an earlier version.
  2631. // so let's try a more simple query
  2632. unset($resAll);
  2633. $sqlQuery = 'SELECT * FROM `mysql`.`user`';
  2634. $res = $this->dbi->tryQuery($sqlQuery);
  2635. if (! $res) {
  2636. $errorMessages .= $this->getHtmlForViewUsersError();
  2637. $errorMessages .= $this->getAddUserHtmlFieldset();
  2638. } else {
  2639. // This message is hardcoded because I will replace it by
  2640. // a automatic repair feature soon.
  2641. $raw = 'Your privilege table structure seems to be older than'
  2642. . ' this MySQL version!<br>'
  2643. . 'Please run the <code>mysql_upgrade</code> command'
  2644. . ' that should be included in your MySQL server distribution'
  2645. . ' to solve this problem!';
  2646. $errorMessages .= Message::rawError($raw)->getDisplay();
  2647. }
  2648. unset($res);
  2649. } else {
  2650. $dbRights = $this->getDbRightsForUserOverview();
  2651. foreach ($dbRights as $right) {
  2652. foreach ($right as $account) {
  2653. if (empty($account['User']) && $account['Host'] === 'localhost') {
  2654. $emptyUserNotice = Message::notice(
  2655. __(
  2656. 'A user account allowing any user from localhost to '
  2657. . 'connect is present. This will prevent other users '
  2658. . 'from connecting if the host part of their account '
  2659. . 'allows a connection from any (%) host.'
  2660. )
  2661. . MySQLDocumentation::show('problems-connecting')
  2662. )->getDisplay();
  2663. break 2;
  2664. }
  2665. }
  2666. }
  2667. /**
  2668. * Displays the initials
  2669. * Also not necessary if there is less than 20 privileges
  2670. */
  2671. if ($resAll && $resAll->numRows() > 20) {
  2672. // for all initials, even non A-Z
  2673. $initials = $this->getHtmlForInitials();
  2674. }
  2675. /**
  2676. * Display the user overview
  2677. * (if less than 50 users, display them immediately)
  2678. */
  2679. if (isset($_GET['initial']) || isset($_GET['showall']) || $res->numRows() < 50) {
  2680. $usersOverview = $this->getUsersOverview($res, $dbRights, $textDir);
  2681. $usersOverview .= $this->template->render('export_modal');
  2682. }
  2683. $response = ResponseRenderer::getInstance();
  2684. if (! $response->isAjax() || ! empty($_REQUEST['ajax_page_request'])) {
  2685. if ($GLOBALS['is_reload_priv']) {
  2686. $flushnote = new Message(
  2687. __(
  2688. 'Note: phpMyAdmin gets the users’ privileges directly '
  2689. . 'from MySQL’s privilege tables. The content of these '
  2690. . 'tables may differ from the privileges the server uses, '
  2691. . 'if they have been changed manually. In this case, '
  2692. . 'you should %sreload the privileges%s before you continue.'
  2693. ),
  2694. Message::NOTICE
  2695. );
  2696. $flushnote->addParamHtml(
  2697. '<a href="' . Url::getFromRoute('/server/privileges', ['flush_privileges' => 1])
  2698. . '" id="reload_privileges_anchor">'
  2699. );
  2700. $flushnote->addParamHtml('</a>');
  2701. } else {
  2702. $flushnote = new Message(
  2703. __(
  2704. 'Note: phpMyAdmin gets the users’ privileges directly '
  2705. . 'from MySQL’s privilege tables. The content of these '
  2706. . 'tables may differ from the privileges the server uses, '
  2707. . 'if they have been changed manually. In this case, '
  2708. . 'the privileges have to be reloaded but currently, you '
  2709. . 'don\'t have the RELOAD privilege.'
  2710. )
  2711. . MySQLDocumentation::show(
  2712. 'privileges-provided',
  2713. false,
  2714. null,
  2715. null,
  2716. 'priv_reload'
  2717. ),
  2718. Message::NOTICE
  2719. );
  2720. }
  2721. $flushNotice = $flushnote->getDisplay();
  2722. }
  2723. }
  2724. return $this->template->render('server/privileges/user_overview', [
  2725. 'error_messages' => $errorMessages,
  2726. 'empty_user_notice' => $emptyUserNotice ?? '',
  2727. 'initials' => $initials ?? '',
  2728. 'users_overview' => $usersOverview ?? '',
  2729. 'is_createuser' => $this->dbi->isCreateUser(),
  2730. 'flush_notice' => $flushNotice ?? '',
  2731. ]);
  2732. }
  2733. /**
  2734. * Get HTML snippet for display user properties
  2735. *
  2736. * @param bool $dbnameIsWildcard whether database name is wildcard or not
  2737. * @param string $urlDbname url database name that urlencode() string
  2738. * @param string $username username
  2739. * @param string $hostname host name
  2740. * @param string|array $dbname database name
  2741. * @param string $tablename table name
  2742. *
  2743. * @return string
  2744. */
  2745. public function getHtmlForUserProperties(
  2746. $dbnameIsWildcard,
  2747. $urlDbname,
  2748. $username,
  2749. $hostname,
  2750. $dbname,
  2751. $tablename
  2752. ) {
  2753. global $cfg;
  2754. $sql = "SELECT '1' FROM `mysql`.`user`"
  2755. . " WHERE `User` = '" . $this->dbi->escapeString($username) . "'"
  2756. . " AND `Host` = '" . $this->dbi->escapeString($hostname) . "';";
  2757. $userDoesNotExists = ! $this->dbi->fetchValue($sql);
  2758. $loginInformationFields = '';
  2759. if ($userDoesNotExists) {
  2760. $loginInformationFields = $this->getHtmlForLoginInformationFields();
  2761. }
  2762. $params = [
  2763. 'username' => $username,
  2764. 'hostname' => $hostname,
  2765. ];
  2766. if (! is_array($dbname) && strlen($dbname) > 0) {
  2767. $params['dbname'] = $dbname;
  2768. if (strlen($tablename) > 0) {
  2769. $params['tablename'] = $tablename;
  2770. }
  2771. } else {
  2772. $params['dbname'] = $dbname;
  2773. }
  2774. $privilegesTable = $this->getHtmlToDisplayPrivilegesTable(
  2775. // If $dbname is an array, pass any one db as all have same privs.
  2776. is_string($dbname) && strlen($dbname) > 0
  2777. ? $dbname
  2778. : (is_array($dbname) ? (string) $dbname[0] : '*'),
  2779. strlen($tablename) > 0
  2780. ? $tablename
  2781. : '*'
  2782. );
  2783. $tableSpecificRights = '';
  2784. if (! is_array($dbname) && strlen($tablename) === 0 && empty($dbnameIsWildcard)) {
  2785. // no table name was given, display all table specific rights
  2786. // but only if $dbname contains no wildcards
  2787. if (strlen($dbname) === 0) {
  2788. $tableSpecificRights .= $this->getHtmlForAllTableSpecificRights($username, $hostname, 'database');
  2789. } else {
  2790. // unescape wildcards in dbname at table level
  2791. $unescapedDb = Util::unescapeMysqlWildcards($dbname);
  2792. $tableSpecificRights .= $this->getHtmlForAllTableSpecificRights(
  2793. $username,
  2794. $hostname,
  2795. 'table',
  2796. $unescapedDb
  2797. );
  2798. $tableSpecificRights .= $this->getHtmlForAllTableSpecificRights(
  2799. $username,
  2800. $hostname,
  2801. 'routine',
  2802. $unescapedDb
  2803. );
  2804. }
  2805. }
  2806. $databaseUrl = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database');
  2807. $databaseUrlTitle = Util::getTitleForTarget($cfg['DefaultTabDatabase']);
  2808. $tableUrl = Util::getScriptNameForOption($cfg['DefaultTabTable'], 'table');
  2809. $tableUrlTitle = Util::getTitleForTarget($cfg['DefaultTabTable']);
  2810. $changePassword = '';
  2811. $userGroup = '';
  2812. $changeLoginInfoFields = '';
  2813. if (! is_array($dbname) && strlen($dbname) === 0 && ! $userDoesNotExists) {
  2814. //change login information
  2815. $changePassword = $this->getFormForChangePassword($username, $hostname, true);
  2816. $userGroup = $this->getUserGroupForUser($username);
  2817. $changeLoginInfoFields = $this->getHtmlForLoginInformationFields('change', $username, $hostname);
  2818. }
  2819. return $this->template->render('server/privileges/user_properties', [
  2820. 'user_does_not_exists' => $userDoesNotExists,
  2821. 'login_information_fields' => $loginInformationFields,
  2822. 'params' => $params,
  2823. 'privileges_table' => $privilegesTable,
  2824. 'table_specific_rights' => $tableSpecificRights,
  2825. 'change_password' => $changePassword,
  2826. 'database' => $dbname,
  2827. 'dbname' => $urlDbname,
  2828. 'username' => $username,
  2829. 'hostname' => $hostname,
  2830. 'is_databases' => $dbnameIsWildcard || is_array($dbname) && count($dbname) > 1,
  2831. 'is_wildcard' => $dbnameIsWildcard,
  2832. 'table' => $tablename,
  2833. 'current_user' => $this->dbi->getCurrentUser(),
  2834. 'user_group' => $userGroup,
  2835. 'change_login_info_fields' => $changeLoginInfoFields,
  2836. 'database_url' => $databaseUrl,
  2837. 'database_url_title' => $databaseUrlTitle,
  2838. 'table_url' => $tableUrl,
  2839. 'table_url_title' => $tableUrlTitle,
  2840. ]);
  2841. }
  2842. /**
  2843. * Get queries for Table privileges to change or copy user
  2844. *
  2845. * @param string $userHostCondition user host condition to
  2846. * select relevant table privileges
  2847. * @param array $queries queries array
  2848. * @param string $username username
  2849. * @param string $hostname host name
  2850. *
  2851. * @return array
  2852. */
  2853. public function getTablePrivsQueriesForChangeOrCopyUser(
  2854. $userHostCondition,
  2855. array $queries,
  2856. $username,
  2857. $hostname
  2858. ) {
  2859. $res = $this->dbi->query(
  2860. 'SELECT `Db`, `Table_name`, `Table_priv` FROM `mysql`.`tables_priv`'
  2861. . $userHostCondition
  2862. );
  2863. while ($row = $res->fetchAssoc()) {
  2864. $res2 = $this->dbi->query(
  2865. 'SELECT `Column_name`, `Column_priv`'
  2866. . ' FROM `mysql`.`columns_priv`'
  2867. . ' WHERE `User`'
  2868. . ' = \'' . $this->dbi->escapeString($_POST['old_username']) . "'"
  2869. . ' AND `Host`'
  2870. . ' = \'' . $this->dbi->escapeString($_POST['old_username']) . '\''
  2871. . ' AND `Db`'
  2872. . ' = \'' . $this->dbi->escapeString($row['Db']) . "'"
  2873. . ' AND `Table_name`'
  2874. . ' = \'' . $this->dbi->escapeString($row['Table_name']) . "'"
  2875. . ';'
  2876. );
  2877. $tmpPrivs1 = $this->extractPrivInfo($row);
  2878. $tmpPrivs2 = [
  2879. 'Select' => [],
  2880. 'Insert' => [],
  2881. 'Update' => [],
  2882. 'References' => [],
  2883. ];
  2884. while ($row2 = $res2->fetchAssoc()) {
  2885. $tmpArray = explode(',', $row2['Column_priv']);
  2886. if (in_array('Select', $tmpArray)) {
  2887. $tmpPrivs2['Select'][] = $row2['Column_name'];
  2888. }
  2889. if (in_array('Insert', $tmpArray)) {
  2890. $tmpPrivs2['Insert'][] = $row2['Column_name'];
  2891. }
  2892. if (in_array('Update', $tmpArray)) {
  2893. $tmpPrivs2['Update'][] = $row2['Column_name'];
  2894. }
  2895. if (! in_array('References', $tmpArray)) {
  2896. continue;
  2897. }
  2898. $tmpPrivs2['References'][] = $row2['Column_name'];
  2899. }
  2900. if (count($tmpPrivs2['Select']) > 0 && ! in_array('SELECT', $tmpPrivs1)) {
  2901. $tmpPrivs1[] = 'SELECT (`' . implode('`, `', $tmpPrivs2['Select']) . '`)';
  2902. }
  2903. if (count($tmpPrivs2['Insert']) > 0 && ! in_array('INSERT', $tmpPrivs1)) {
  2904. $tmpPrivs1[] = 'INSERT (`' . implode('`, `', $tmpPrivs2['Insert']) . '`)';
  2905. }
  2906. if (count($tmpPrivs2['Update']) > 0 && ! in_array('UPDATE', $tmpPrivs1)) {
  2907. $tmpPrivs1[] = 'UPDATE (`' . implode('`, `', $tmpPrivs2['Update']) . '`)';
  2908. }
  2909. if (count($tmpPrivs2['References']) > 0 && ! in_array('REFERENCES', $tmpPrivs1)) {
  2910. $tmpPrivs1[] = 'REFERENCES (`' . implode('`, `', $tmpPrivs2['References']) . '`)';
  2911. }
  2912. $queries[] = 'GRANT ' . implode(', ', $tmpPrivs1)
  2913. . ' ON ' . Util::backquote($row['Db']) . '.'
  2914. . Util::backquote($row['Table_name'])
  2915. . ' TO \'' . $this->dbi->escapeString($username)
  2916. . '\'@\'' . $this->dbi->escapeString($hostname) . '\''
  2917. . (in_array('Grant', explode(',', $row['Table_priv']))
  2918. ? ' WITH GRANT OPTION;'
  2919. : ';');
  2920. }
  2921. return $queries;
  2922. }
  2923. /**
  2924. * Get queries for database specific privileges for change or copy user
  2925. *
  2926. * @param array $queries queries array with string
  2927. * @param string $username username
  2928. * @param string $hostname host name
  2929. *
  2930. * @return array
  2931. */
  2932. public function getDbSpecificPrivsQueriesForChangeOrCopyUser(
  2933. array $queries,
  2934. string $username,
  2935. string $hostname
  2936. ) {
  2937. $userHostCondition = ' WHERE `User`'
  2938. . ' = \'' . $this->dbi->escapeString($_POST['old_username']) . "'"
  2939. . ' AND `Host`'
  2940. . ' = \'' . $this->dbi->escapeString($_POST['old_hostname']) . '\';';
  2941. $res = $this->dbi->query('SELECT * FROM `mysql`.`db`' . $userHostCondition);
  2942. while ($row = $res->fetchAssoc()) {
  2943. $queries[] = 'GRANT ' . implode(', ', $this->extractPrivInfo($row))
  2944. . ' ON ' . Util::backquote($row['Db']) . '.*'
  2945. . ' TO \'' . $this->dbi->escapeString($username)
  2946. . '\'@\'' . $this->dbi->escapeString($hostname) . '\''
  2947. . ($row['Grant_priv'] === 'Y' ? ' WITH GRANT OPTION;' : ';');
  2948. }
  2949. return $this->getTablePrivsQueriesForChangeOrCopyUser($userHostCondition, $queries, $username, $hostname);
  2950. }
  2951. /**
  2952. * Prepares queries for adding users and
  2953. * also create database and return query and message
  2954. *
  2955. * @param bool $error whether user create or not
  2956. * @param string $realSqlQuery SQL query for add a user
  2957. * @param string $sqlQuery SQL query to be displayed
  2958. * @param string $username username
  2959. * @param string $hostname host name
  2960. * @param string $dbname database name
  2961. * @param string $alterRealSqlQuery SQL query for ALTER USER
  2962. * @param string $alterSqlQuery SQL query for ALTER USER to be displayed
  2963. *
  2964. * @return array<int,string|Message>
  2965. */
  2966. public function addUserAndCreateDatabase(
  2967. $error,
  2968. $realSqlQuery,
  2969. $sqlQuery,
  2970. $username,
  2971. $hostname,
  2972. $dbname,
  2973. $alterRealSqlQuery,
  2974. $alterSqlQuery,
  2975. bool $createDb1,
  2976. bool $createDb2,
  2977. bool $createDb3
  2978. ): array {
  2979. if ($error || (! empty($realSqlQuery) && ! $this->dbi->tryQuery($realSqlQuery))) {
  2980. $createDb1 = $createDb2 = $createDb3 = false;
  2981. $message = Message::rawError($this->dbi->getError());
  2982. } elseif ($alterRealSqlQuery !== '' && ! $this->dbi->tryQuery($alterRealSqlQuery)) {
  2983. $createDb1 = $createDb2 = $createDb3 = false;
  2984. $message = Message::rawError($this->dbi->getError());
  2985. } else {
  2986. $sqlQuery .= $alterSqlQuery;
  2987. $message = Message::success(__('You have added a new user.'));
  2988. }
  2989. if ($createDb1) {
  2990. // Create database with same name and grant all privileges
  2991. $query = 'CREATE DATABASE IF NOT EXISTS '
  2992. . Util::backquote($username) . ';';
  2993. $sqlQuery .= $query;
  2994. if (! $this->dbi->tryQuery($query)) {
  2995. $message = Message::rawError($this->dbi->getError());
  2996. }
  2997. /**
  2998. * Reload the navigation
  2999. */
  3000. $GLOBALS['reload'] = true;
  3001. $GLOBALS['db'] = $username;
  3002. $query = 'GRANT ALL PRIVILEGES ON '
  3003. . Util::backquote(
  3004. Util::escapeMysqlWildcards($username)
  3005. ) . '.* TO \''
  3006. . $this->dbi->escapeString($username)
  3007. . '\'@\'' . $this->dbi->escapeString($hostname) . '\';';
  3008. $sqlQuery .= $query;
  3009. if (! $this->dbi->tryQuery($query)) {
  3010. $message = Message::rawError($this->dbi->getError());
  3011. }
  3012. }
  3013. if ($createDb2) {
  3014. // Grant all privileges on wildcard name (username\_%)
  3015. $query = 'GRANT ALL PRIVILEGES ON '
  3016. . Util::backquote(
  3017. Util::escapeMysqlWildcards($username) . '\_%'
  3018. ) . '.* TO \''
  3019. . $this->dbi->escapeString($username)
  3020. . '\'@\'' . $this->dbi->escapeString($hostname) . '\';';
  3021. $sqlQuery .= $query;
  3022. if (! $this->dbi->tryQuery($query)) {
  3023. $message = Message::rawError($this->dbi->getError());
  3024. }
  3025. }
  3026. if ($createDb3) {
  3027. // Grant all privileges on the specified database to the new user
  3028. $query = 'GRANT ALL PRIVILEGES ON '
  3029. . Util::backquote($dbname) . '.* TO \''
  3030. . $this->dbi->escapeString($username)
  3031. . '\'@\'' . $this->dbi->escapeString($hostname) . '\';';
  3032. $sqlQuery .= $query;
  3033. if (! $this->dbi->tryQuery($query)) {
  3034. $message = Message::rawError($this->dbi->getError());
  3035. }
  3036. }
  3037. return [
  3038. $sqlQuery,
  3039. $message,
  3040. ];
  3041. }
  3042. /**
  3043. * Get the hashed string for password
  3044. *
  3045. * @param string $password password
  3046. *
  3047. * @return string
  3048. */
  3049. public function getHashedPassword($password)
  3050. {
  3051. $password = $this->dbi->escapeString($password);
  3052. $result = $this->dbi->fetchSingleRow("SELECT PASSWORD('" . $password . "') AS `password`;");
  3053. return $result['password'];
  3054. }
  3055. /**
  3056. * Check if MariaDB's 'simple_password_check'
  3057. * OR 'cracklib_password_check' is ACTIVE
  3058. */
  3059. public function checkIfMariaDBPwdCheckPluginActive(): bool
  3060. {
  3061. $serverVersion = $this->dbi->getVersion();
  3062. if (! (Compatibility::isMariaDb() && $serverVersion >= 100002)) {
  3063. return false;
  3064. }
  3065. $result = $this->dbi->tryQuery('SHOW PLUGINS SONAME LIKE \'%_password_check%\'');
  3066. /* Plugins are not working, for example directory does not exists */
  3067. if ($result === false) {
  3068. return false;
  3069. }
  3070. while ($row = $result->fetchAssoc()) {
  3071. if ($row['Status'] === 'ACTIVE') {
  3072. return true;
  3073. }
  3074. }
  3075. return false;
  3076. }
  3077. /**
  3078. * Get SQL queries for Display and Add user
  3079. *
  3080. * @param string $username username
  3081. * @param string $hostname host name
  3082. * @param string $password password
  3083. *
  3084. * @return array ($create_user_real, $create_user_show, $real_sql_query, $sql_query
  3085. * $password_set_real, $password_set_show, $alter_real_sql_query, $alter_sql_query)
  3086. */
  3087. public function getSqlQueriesForDisplayAndAddUser($username, $hostname, $password)
  3088. {
  3089. $slashedUsername = $this->dbi->escapeString($username);
  3090. $slashedHostname = $this->dbi->escapeString($hostname);
  3091. $slashedPassword = $this->dbi->escapeString($password);
  3092. $serverVersion = $this->dbi->getVersion();
  3093. $createUserStmt = sprintf('CREATE USER \'%s\'@\'%s\'', $slashedUsername, $slashedHostname);
  3094. $isMariaDBPwdPluginActive = $this->checkIfMariaDBPwdCheckPluginActive();
  3095. // See https://github.com/phpmyadmin/phpmyadmin/pull/11560#issuecomment-147158219
  3096. // for details regarding details of syntax usage for various versions
  3097. // 'IDENTIFIED WITH auth_plugin'
  3098. // is supported by MySQL 5.5.7+
  3099. if (Compatibility::isMySqlOrPerconaDb() && $serverVersion >= 50507 && isset($_POST['authentication_plugin'])) {
  3100. $createUserStmt .= ' IDENTIFIED WITH '
  3101. . $_POST['authentication_plugin'];
  3102. }
  3103. // 'IDENTIFIED VIA auth_plugin'
  3104. // is supported by MariaDB 5.2+
  3105. if (
  3106. Compatibility::isMariaDb()
  3107. && $serverVersion >= 50200
  3108. && isset($_POST['authentication_plugin'])
  3109. && ! $isMariaDBPwdPluginActive
  3110. ) {
  3111. $createUserStmt .= ' IDENTIFIED VIA '
  3112. . $_POST['authentication_plugin'];
  3113. }
  3114. $createUserReal = $createUserStmt;
  3115. $createUserShow = $createUserStmt;
  3116. $passwordSetStmt = 'SET PASSWORD FOR \'%s\'@\'%s\' = \'%s\'';
  3117. $passwordSetShow = sprintf($passwordSetStmt, $slashedUsername, $slashedHostname, '***');
  3118. $sqlQueryStmt = sprintf(
  3119. 'GRANT %s ON *.* TO \'%s\'@\'%s\'',
  3120. implode(', ', $this->extractPrivInfo()),
  3121. $slashedUsername,
  3122. $slashedHostname
  3123. );
  3124. $realSqlQuery = $sqlQuery = $sqlQueryStmt;
  3125. // Set the proper hashing method
  3126. if (isset($_POST['authentication_plugin'])) {
  3127. $this->setProperPasswordHashing($_POST['authentication_plugin']);
  3128. }
  3129. // Use 'CREATE USER ... WITH ... AS ..' syntax for
  3130. // newer MySQL versions
  3131. // and 'CREATE USER ... VIA .. USING ..' syntax for
  3132. // newer MariaDB versions
  3133. if (
  3134. (Compatibility::isMySqlOrPerconaDb() && $serverVersion >= 50706)
  3135. || (Compatibility::isMariaDb() && $serverVersion >= 50200)
  3136. ) {
  3137. $passwordSetReal = null;
  3138. // Required for binding '%' with '%s'
  3139. $createUserStmt = str_replace('%', '%%', $createUserStmt);
  3140. // MariaDB uses 'USING' whereas MySQL uses 'AS'
  3141. // but MariaDB with validation plugin needs cleartext password
  3142. if (Compatibility::isMariaDb() && ! $isMariaDBPwdPluginActive && isset($_POST['authentication_plugin'])) {
  3143. $createUserStmt .= ' USING \'%s\'';
  3144. } elseif (Compatibility::isMariaDb()) {
  3145. $createUserStmt .= ' IDENTIFIED BY \'%s\'';
  3146. } elseif (Compatibility::isMySqlOrPerconaDb() && $serverVersion >= 80011) {
  3147. if (! str_contains($createUserStmt, 'IDENTIFIED')) {
  3148. // Maybe the authentication_plugin was not posted and then a part is missing
  3149. $createUserStmt .= ' IDENTIFIED BY \'%s\'';
  3150. } else {
  3151. $createUserStmt .= ' BY \'%s\'';
  3152. }
  3153. } else {
  3154. $createUserStmt .= ' AS \'%s\'';
  3155. }
  3156. if ($_POST['pred_password'] === 'keep') {
  3157. $createUserReal = sprintf($createUserStmt, $slashedPassword);
  3158. $createUserShow = sprintf($createUserStmt, '***');
  3159. } elseif ($_POST['pred_password'] === 'none') {
  3160. $createUserReal = sprintf($createUserStmt, null);
  3161. $createUserShow = sprintf($createUserStmt, '***');
  3162. } else {
  3163. if (
  3164. ! ((Compatibility::isMariaDb() && $isMariaDBPwdPluginActive)
  3165. || Compatibility::isMySqlOrPerconaDb() && $serverVersion >= 80011)
  3166. ) {
  3167. $hashedPassword = $this->getHashedPassword($_POST['pma_pw']);
  3168. } else {
  3169. // MariaDB with validation plugin needs cleartext password
  3170. $hashedPassword = $_POST['pma_pw'];
  3171. }
  3172. $createUserReal = sprintf($createUserStmt, $hashedPassword);
  3173. $createUserShow = sprintf($createUserStmt, '***');
  3174. }
  3175. } else {
  3176. // Use 'SET PASSWORD' syntax for pre-5.7.6 MySQL versions
  3177. // and pre-5.2.0 MariaDB versions
  3178. if ($_POST['pred_password'] === 'keep') {
  3179. $passwordSetReal = sprintf($passwordSetStmt, $slashedUsername, $slashedHostname, $slashedPassword);
  3180. } elseif ($_POST['pred_password'] === 'none') {
  3181. $passwordSetReal = sprintf($passwordSetStmt, $slashedUsername, $slashedHostname, null);
  3182. } else {
  3183. $hashedPassword = $this->getHashedPassword($_POST['pma_pw']);
  3184. $passwordSetReal = sprintf($passwordSetStmt, $slashedUsername, $slashedHostname, $hashedPassword);
  3185. }
  3186. }
  3187. $alterRealSqlQuery = '';
  3188. $alterSqlQuery = '';
  3189. if (Compatibility::isMySqlOrPerconaDb() && $serverVersion >= 80011) {
  3190. $sqlQueryStmt = '';
  3191. if (
  3192. (isset($_POST['Grant_priv']) && $_POST['Grant_priv'] === 'Y')
  3193. || (isset($GLOBALS['Grant_priv']) && $GLOBALS['Grant_priv'] === 'Y')
  3194. ) {
  3195. $sqlQueryStmt = ' WITH GRANT OPTION';
  3196. }
  3197. $realSqlQuery .= $sqlQueryStmt;
  3198. $sqlQuery .= $sqlQueryStmt;
  3199. $alterSqlQueryStmt = sprintf('ALTER USER \'%s\'@\'%s\'', $slashedUsername, $slashedHostname);
  3200. $alterRealSqlQuery = $alterSqlQueryStmt;
  3201. $alterSqlQuery = $alterSqlQueryStmt;
  3202. }
  3203. // add REQUIRE clause
  3204. $requireClause = $this->getRequireClause();
  3205. $withClause = $this->getWithClauseForAddUserAndUpdatePrivs();
  3206. if (Compatibility::isMySqlOrPerconaDb() && $serverVersion >= 80011) {
  3207. $alterRealSqlQuery .= $requireClause;
  3208. $alterSqlQuery .= $requireClause;
  3209. $alterRealSqlQuery .= $withClause;
  3210. $alterSqlQuery .= $withClause;
  3211. } else {
  3212. $realSqlQuery .= $requireClause;
  3213. $sqlQuery .= $requireClause;
  3214. $realSqlQuery .= $withClause;
  3215. $sqlQuery .= $withClause;
  3216. }
  3217. if ($alterRealSqlQuery !== '') {
  3218. $alterRealSqlQuery .= ';';
  3219. $alterSqlQuery .= ';';
  3220. }
  3221. $createUserReal .= ';';
  3222. $createUserShow .= ';';
  3223. $realSqlQuery .= ';';
  3224. $sqlQuery .= ';';
  3225. // No Global GRANT_OPTION privilege
  3226. if (! $this->dbi->isGrantUser()) {
  3227. $realSqlQuery = '';
  3228. $sqlQuery = '';
  3229. }
  3230. // Use 'SET PASSWORD' for pre-5.7.6 MySQL versions
  3231. // and pre-5.2.0 MariaDB
  3232. if (
  3233. (Compatibility::isMySqlOrPerconaDb()
  3234. && $serverVersion >= 50706)
  3235. || (Compatibility::isMariaDb()
  3236. && $serverVersion >= 50200)
  3237. ) {
  3238. $passwordSetReal = null;
  3239. $passwordSetShow = null;
  3240. } else {
  3241. if ($passwordSetReal !== null) {
  3242. $passwordSetReal .= ';';
  3243. }
  3244. $passwordSetShow .= ';';
  3245. }
  3246. return [
  3247. $createUserReal,
  3248. $createUserShow,
  3249. $realSqlQuery,
  3250. $sqlQuery,
  3251. $passwordSetReal,
  3252. $passwordSetShow,
  3253. $alterRealSqlQuery,
  3254. $alterSqlQuery,
  3255. ];
  3256. }
  3257. /**
  3258. * Returns the type ('PROCEDURE' or 'FUNCTION') of the routine
  3259. *
  3260. * @param string $dbname database
  3261. * @param string $routineName routine
  3262. *
  3263. * @return string type
  3264. */
  3265. public function getRoutineType(string $dbname, string $routineName)
  3266. {
  3267. $routineData = $this->dbi->getRoutines($dbname);
  3268. $routineName = mb_strtolower($routineName);
  3269. foreach ($routineData as $routine) {
  3270. if (mb_strtolower($routine['name']) === $routineName) {
  3271. return $routine['type'];
  3272. }
  3273. }
  3274. return '';
  3275. }
  3276. /**
  3277. * @param string $username User name
  3278. * @param string $hostname Host name
  3279. * @param string $database Database name
  3280. * @param string $routine Routine name
  3281. *
  3282. * @return array
  3283. */
  3284. private function getRoutinePrivileges(
  3285. string $username,
  3286. string $hostname,
  3287. string $database,
  3288. string $routine
  3289. ): array {
  3290. $sql = 'SELECT `Proc_priv`'
  3291. . ' FROM `mysql`.`procs_priv`'
  3292. . " WHERE `User` = '" . $this->dbi->escapeString($username) . "'"
  3293. . " AND `Host` = '" . $this->dbi->escapeString($hostname) . "'"
  3294. . " AND `Db` = '"
  3295. . $this->dbi->escapeString(Util::unescapeMysqlWildcards($database)) . "'"
  3296. . " AND `Routine_name` LIKE '" . $this->dbi->escapeString($routine) . "';";
  3297. $privileges = $this->dbi->fetchValue($sql);
  3298. if ($privileges === false) {
  3299. $privileges = '';
  3300. }
  3301. return $this->parseProcPriv($privileges);
  3302. }
  3303. public function getFormForChangePassword(string $username, string $hostname, bool $editOthers): string
  3304. {
  3305. global $route;
  3306. $isPrivileges = $route === '/server/privileges';
  3307. $serverVersion = $this->dbi->getVersion();
  3308. $origAuthPlugin = $this->getCurrentAuthenticationPlugin('change', $username, $hostname);
  3309. $isNew = (Compatibility::isMySqlOrPerconaDb() && $serverVersion >= 50507)
  3310. || (Compatibility::isMariaDb() && $serverVersion >= 50200);
  3311. $hasMoreAuthPlugins = (Compatibility::isMySqlOrPerconaDb() && $serverVersion >= 50706)
  3312. || ($this->dbi->isSuperUser() && $editOthers);
  3313. $activeAuthPlugins = ['mysql_native_password' => __('Native MySQL authentication')];
  3314. if ($isNew && $hasMoreAuthPlugins) {
  3315. $activeAuthPlugins = $this->plugins->getAuthentication();
  3316. if (isset($activeAuthPlugins['mysql_old_password'])) {
  3317. unset($activeAuthPlugins['mysql_old_password']);
  3318. }
  3319. }
  3320. return $this->template->render('server/privileges/change_password', [
  3321. 'username' => $username,
  3322. 'hostname' => $hostname,
  3323. 'is_privileges' => $isPrivileges,
  3324. 'is_new' => $isNew,
  3325. 'has_more_auth_plugins' => $hasMoreAuthPlugins,
  3326. 'active_auth_plugins' => $activeAuthPlugins,
  3327. 'orig_auth_plugin' => $origAuthPlugin,
  3328. ]);
  3329. }
  3330. /**
  3331. * @see https://dev.mysql.com/doc/refman/en/account-locking.html
  3332. * @see https://mariadb.com/kb/en/account-locking/
  3333. *
  3334. * @return array<string, string|null>|null
  3335. */
  3336. private function getUserPrivileges(string $user, string $host, bool $hasAccountLocking): ?array
  3337. {
  3338. $query = 'SELECT * FROM `mysql`.`user` WHERE `User` = ? AND `Host` = ?;';
  3339. /** @var mysqli_stmt|false $statement */
  3340. $statement = $this->dbi->prepare($query);
  3341. if ($statement === false || ! $statement->bind_param('ss', $user, $host) || ! $statement->execute()) {
  3342. return null;
  3343. }
  3344. $result = new MysqliResult($statement->get_result());
  3345. /** @var array<string, string|null>|null $userPrivileges */
  3346. $userPrivileges = $result->fetchAssoc();
  3347. if ($userPrivileges === []) {
  3348. return null;
  3349. }
  3350. if (! $hasAccountLocking || ! $this->dbi->isMariaDB()) {
  3351. return $userPrivileges;
  3352. }
  3353. $userPrivileges['account_locked'] = 'N';
  3354. $query = 'SELECT * FROM `mysql`.`global_priv` WHERE `User` = ? AND `Host` = ?;';
  3355. /** @var mysqli_stmt|false $statement */
  3356. $statement = $this->dbi->prepare($query);
  3357. if ($statement === false || ! $statement->bind_param('ss', $user, $host) || ! $statement->execute()) {
  3358. return $userPrivileges;
  3359. }
  3360. $result = new MysqliResult($statement->get_result());
  3361. /** @var array<string, string|null>|null $globalPrivileges */
  3362. $globalPrivileges = $result->fetchAssoc();
  3363. if ($globalPrivileges === []) {
  3364. return $userPrivileges;
  3365. }
  3366. $privileges = json_decode($globalPrivileges['Priv'] ?? '[]', true);
  3367. if (! is_array($privileges)) {
  3368. return $userPrivileges;
  3369. }
  3370. if (isset($privileges['account_locked']) && $privileges['account_locked']) {
  3371. $userPrivileges['account_locked'] = 'Y';
  3372. }
  3373. return $userPrivileges;
  3374. }
  3375. }