Privileges.php 138 KB

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