Util.php 161 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716
  1. <?php
  2. /* vim: set expandtab sw=4 ts=4 sts=4: */
  3. /**
  4. * Hold the PhpMyAdmin\Util class
  5. *
  6. * @package PhpMyAdmin
  7. */
  8. namespace PhpMyAdmin;
  9. use PhpMyAdmin\Core;
  10. use PhpMyAdmin\DatabaseInterface;
  11. use PhpMyAdmin\FileListing;
  12. use PhpMyAdmin\Message;
  13. use PhpMyAdmin\Plugins\ImportPlugin;
  14. use PhpMyAdmin\Response;
  15. use PhpMyAdmin\Sanitize;
  16. use PhpMyAdmin\SqlParser\Context;
  17. use PhpMyAdmin\SqlParser\Lexer;
  18. use PhpMyAdmin\SqlParser\Parser;
  19. use PhpMyAdmin\SqlParser\Token;
  20. use PhpMyAdmin\SqlParser\Utils\Error as ParserError;
  21. use PhpMyAdmin\Template;
  22. use PhpMyAdmin\Url;
  23. /**
  24. * Misc functions used all over the scripts.
  25. *
  26. * @package PhpMyAdmin
  27. */
  28. class Util
  29. {
  30. /**
  31. * Checks whether configuration value tells to show icons.
  32. *
  33. * @param string $value Configuration option name
  34. *
  35. * @return boolean Whether to show icons.
  36. */
  37. public static function showIcons($value)
  38. {
  39. return in_array($GLOBALS['cfg'][$value], array('icons', 'both'));
  40. }
  41. /**
  42. * Checks whether configuration value tells to show text.
  43. *
  44. * @param string $value Configuration option name
  45. *
  46. * @return boolean Whether to show text.
  47. */
  48. public static function showText($value)
  49. {
  50. return in_array($GLOBALS['cfg'][$value], array('text', 'both'));
  51. }
  52. /**
  53. * Returns an HTML IMG tag for a particular icon from a theme,
  54. * which may be an actual file or an icon from a sprite.
  55. * This function takes into account the ActionLinksMode
  56. * configuration setting and wraps the image tag in a span tag.
  57. *
  58. * @param string $icon name of icon file
  59. * @param string $alternate alternate text
  60. * @param boolean $force_text whether to force alternate text to be displayed
  61. * @param boolean $menu_icon whether this icon is for the menu bar or not
  62. * @param string $control_param which directive controls the display
  63. *
  64. * @return string an html snippet
  65. */
  66. public static function getIcon(
  67. $icon,
  68. $alternate = '',
  69. $force_text = false,
  70. $menu_icon = false,
  71. $control_param = 'ActionLinksMode'
  72. ) {
  73. $include_icon = $include_text = false;
  74. if (self::showIcons($control_param)) {
  75. $include_icon = true;
  76. }
  77. if ($force_text
  78. || self::showText($control_param)
  79. ) {
  80. $include_text = true;
  81. }
  82. // Sometimes use a span (we rely on this in js/sql.js). But for menu bar
  83. // we don't need a span
  84. $button = $menu_icon ? '' : '<span class="nowrap">';
  85. if ($include_icon) {
  86. $button .= self::getImage($icon, $alternate);
  87. }
  88. if ($include_icon && $include_text) {
  89. $button .= '&nbsp;';
  90. }
  91. if ($include_text) {
  92. $button .= $alternate;
  93. }
  94. $button .= $menu_icon ? '' : '</span>';
  95. return $button;
  96. }
  97. /**
  98. * Returns an HTML IMG tag for a particular image from a theme
  99. *
  100. * The image name should match CSS class defined in icons.css.php
  101. *
  102. * @param string $image The name of the file to get
  103. * @param string $alternate Used to set 'alt' and 'title' attributes
  104. * of the image
  105. * @param array $attributes An associative array of other attributes
  106. *
  107. * @return string an html IMG tag
  108. */
  109. public static function getImage($image, $alternate = '', array $attributes = array())
  110. {
  111. $alternate = htmlspecialchars($alternate);
  112. // Set $url accordingly
  113. if (isset($GLOBALS['pmaThemeImage'])) {
  114. $url = $GLOBALS['pmaThemeImage'] . $image;
  115. } else {
  116. $url = './themes/pmahomme/' . $image;
  117. }
  118. if (isset($attributes['class'])) {
  119. $attributes['class'] = "icon ic_$image " . $attributes['class'];
  120. } else {
  121. $attributes['class'] = "icon ic_$image";
  122. }
  123. // set all other attributes
  124. $attr_str = '';
  125. foreach ($attributes as $key => $value) {
  126. if (! in_array($key, array('alt', 'title'))) {
  127. $attr_str .= " $key=\"$value\"";
  128. }
  129. }
  130. // override the alt attribute
  131. if (isset($attributes['alt'])) {
  132. $alt = $attributes['alt'];
  133. } else {
  134. $alt = $alternate;
  135. }
  136. // override the title attribute
  137. if (isset($attributes['title'])) {
  138. $title = $attributes['title'];
  139. } else {
  140. $title = $alternate;
  141. }
  142. // generate the IMG tag
  143. $template = '<img src="themes/dot.gif" title="%s" alt="%s"%s />';
  144. $retval = sprintf($template, $title, $alt, $attr_str);
  145. return $retval;
  146. }
  147. /**
  148. * Returns the formatted maximum size for an upload
  149. *
  150. * @param integer $max_upload_size the size
  151. *
  152. * @return string the message
  153. *
  154. * @access public
  155. */
  156. public static function getFormattedMaximumUploadSize($max_upload_size)
  157. {
  158. // I have to reduce the second parameter (sensitiveness) from 6 to 4
  159. // to avoid weird results like 512 kKib
  160. list($max_size, $max_unit) = self::formatByteDown($max_upload_size, 4);
  161. return '(' . sprintf(__('Max: %s%s'), $max_size, $max_unit) . ')';
  162. }
  163. /**
  164. * Generates a hidden field which should indicate to the browser
  165. * the maximum size for upload
  166. *
  167. * @param integer $max_size the size
  168. *
  169. * @return string the INPUT field
  170. *
  171. * @access public
  172. */
  173. public static function generateHiddenMaxFileSize($max_size)
  174. {
  175. return '<input type="hidden" name="MAX_FILE_SIZE" value="'
  176. . $max_size . '" />';
  177. }
  178. /**
  179. * Add slashes before "_" and "%" characters for using them in MySQL
  180. * database, table and field names.
  181. * Note: This function does not escape backslashes!
  182. *
  183. * @param string $name the string to escape
  184. *
  185. * @return string the escaped string
  186. *
  187. * @access public
  188. */
  189. public static function escapeMysqlWildcards($name)
  190. {
  191. return strtr($name, array('_' => '\\_', '%' => '\\%'));
  192. } // end of the 'escapeMysqlWildcards()' function
  193. /**
  194. * removes slashes before "_" and "%" characters
  195. * Note: This function does not unescape backslashes!
  196. *
  197. * @param string $name the string to escape
  198. *
  199. * @return string the escaped string
  200. *
  201. * @access public
  202. */
  203. public static function unescapeMysqlWildcards($name)
  204. {
  205. return strtr($name, array('\\_' => '_', '\\%' => '%'));
  206. } // end of the 'unescapeMysqlWildcards()' function
  207. /**
  208. * removes quotes (',",`) from a quoted string
  209. *
  210. * checks if the string is quoted and removes this quotes
  211. *
  212. * @param string $quoted_string string to remove quotes from
  213. * @param string $quote type of quote to remove
  214. *
  215. * @return string unqoted string
  216. */
  217. public static function unQuote($quoted_string, $quote = null)
  218. {
  219. $quotes = array();
  220. if ($quote === null) {
  221. $quotes[] = '`';
  222. $quotes[] = '"';
  223. $quotes[] = "'";
  224. } else {
  225. $quotes[] = $quote;
  226. }
  227. foreach ($quotes as $quote) {
  228. if (mb_substr($quoted_string, 0, 1) === $quote
  229. && mb_substr($quoted_string, -1, 1) === $quote
  230. ) {
  231. $unquoted_string = mb_substr($quoted_string, 1, -1);
  232. // replace escaped quotes
  233. $unquoted_string = str_replace(
  234. $quote . $quote,
  235. $quote,
  236. $unquoted_string
  237. );
  238. return $unquoted_string;
  239. }
  240. }
  241. return $quoted_string;
  242. }
  243. /**
  244. * format sql strings
  245. *
  246. * @param string $sqlQuery raw SQL string
  247. * @param boolean $truncate truncate the query if it is too long
  248. *
  249. * @return string the formatted sql
  250. *
  251. * @global array $cfg the configuration array
  252. *
  253. * @access public
  254. * @todo move into PMA_Sql
  255. */
  256. public static function formatSql($sqlQuery, $truncate = false)
  257. {
  258. global $cfg;
  259. if ($truncate
  260. && mb_strlen($sqlQuery) > $cfg['MaxCharactersInDisplayedSQL']
  261. ) {
  262. $sqlQuery = mb_substr(
  263. $sqlQuery,
  264. 0,
  265. $cfg['MaxCharactersInDisplayedSQL']
  266. ) . '[...]';
  267. }
  268. return '<code class="sql"><pre>' . "\n"
  269. . htmlspecialchars($sqlQuery) . "\n"
  270. . '</pre></code>';
  271. } // end of the "formatSql()" function
  272. /**
  273. * Displays a link to the documentation as an icon
  274. *
  275. * @param string $link documentation link
  276. * @param string $target optional link target
  277. * @param boolean $bbcode optional flag indicating whether to output bbcode
  278. *
  279. * @return string the html link
  280. *
  281. * @access public
  282. */
  283. public static function showDocLink($link, $target = 'documentation', $bbcode = false)
  284. {
  285. if($bbcode){
  286. return "[a@$link@$target][dochelpicon][/a]";
  287. }
  288. return '<a href="' . $link . '" target="' . $target . '">'
  289. . self::getImage('b_help', __('Documentation'))
  290. . '</a>';
  291. } // end of the 'showDocLink()' function
  292. /**
  293. * Get a URL link to the official MySQL documentation
  294. *
  295. * @param string $link contains name of page/anchor that is being linked
  296. * @param string $anchor anchor to page part
  297. *
  298. * @return string the URL link
  299. *
  300. * @access public
  301. */
  302. public static function getMySQLDocuURL($link, $anchor = '')
  303. {
  304. // Fixup for newly used names:
  305. $link = str_replace('_', '-', mb_strtolower($link));
  306. if (empty($link)) {
  307. $link = 'index';
  308. }
  309. $mysql = '5.5';
  310. $lang = 'en';
  311. if (isset($GLOBALS['dbi'])) {
  312. $serverVersion = $GLOBALS['dbi']->getVersion();
  313. if ($serverVersion >= 50700) {
  314. $mysql = '5.7';
  315. } elseif ($serverVersion >= 50600) {
  316. $mysql = '5.6';
  317. } elseif ($serverVersion >= 50500) {
  318. $mysql = '5.5';
  319. }
  320. }
  321. $url = 'https://dev.mysql.com/doc/refman/'
  322. . $mysql . '/' . $lang . '/' . $link . '.html';
  323. if (! empty($anchor)) {
  324. $url .= '#' . $anchor;
  325. }
  326. return Core::linkURL($url);
  327. }
  328. /**
  329. * Displays a link to the official MySQL documentation
  330. *
  331. * @param string $link contains name of page/anchor that is being linked
  332. * @param bool $big_icon whether to use big icon (like in left frame)
  333. * @param string $anchor anchor to page part
  334. * @param bool $just_open whether only the opening <a> tag should be returned
  335. *
  336. * @return string the html link
  337. *
  338. * @access public
  339. */
  340. public static function showMySQLDocu(
  341. $link,
  342. $big_icon = false,
  343. $anchor = '',
  344. $just_open = false
  345. ) {
  346. $url = self::getMySQLDocuURL($link, $anchor);
  347. $open_link = '<a href="' . $url . '" target="mysql_doc">';
  348. if ($just_open) {
  349. return $open_link;
  350. } elseif ($big_icon) {
  351. return $open_link
  352. . self::getImage('b_sqlhelp', __('Documentation')) . '</a>';
  353. }
  354. return self::showDocLink($url, 'mysql_doc');
  355. } // end of the 'showMySQLDocu()' function
  356. /**
  357. * Returns link to documentation.
  358. *
  359. * @param string $page Page in documentation
  360. * @param string $anchor Optional anchor in page
  361. *
  362. * @return string URL
  363. */
  364. public static function getDocuLink($page, $anchor = '')
  365. {
  366. /* Construct base URL */
  367. $url = $page . '.html';
  368. if (!empty($anchor)) {
  369. $url .= '#' . $anchor;
  370. }
  371. /* Check if we have built local documentation, however
  372. * provide consistent URL for testsuite
  373. */
  374. if (! defined('TESTSUITE') && @file_exists('doc/html/index.html')) {
  375. if ($GLOBALS['PMA_Config']->get('is_setup')) {
  376. return '../doc/html/' . $url;
  377. }
  378. return './doc/html/' . $url;
  379. }
  380. return Core::linkURL('https://docs.phpmyadmin.net/en/latest/' . $url);
  381. }
  382. /**
  383. * Displays a link to the phpMyAdmin documentation
  384. *
  385. * @param string $page Page in documentation
  386. * @param string $anchor Optional anchor in page
  387. * @param boolean $bbcode Optional flag indicating whether to output bbcode
  388. *
  389. * @return string the html link
  390. *
  391. * @access public
  392. */
  393. public static function showDocu($page, $anchor = '', $bbcode = false)
  394. {
  395. return self::showDocLink(self::getDocuLink($page, $anchor), 'documentation', $bbcode);
  396. } // end of the 'showDocu()' function
  397. /**
  398. * Displays a link to the PHP documentation
  399. *
  400. * @param string $target anchor in documentation
  401. *
  402. * @return string the html link
  403. *
  404. * @access public
  405. */
  406. public static function showPHPDocu($target)
  407. {
  408. $url = Core::getPHPDocLink($target);
  409. return self::showDocLink($url);
  410. } // end of the 'showPHPDocu()' function
  411. /**
  412. * Returns HTML code for a tooltip
  413. *
  414. * @param string $message the message for the tooltip
  415. *
  416. * @return string
  417. *
  418. * @access public
  419. */
  420. public static function showHint($message)
  421. {
  422. if ($GLOBALS['cfg']['ShowHint']) {
  423. $classClause = ' class="pma_hint"';
  424. } else {
  425. $classClause = '';
  426. }
  427. return '<span' . $classClause . '>'
  428. . self::getImage('b_help')
  429. . '<span class="hide">' . $message . '</span>'
  430. . '</span>';
  431. }
  432. /**
  433. * Displays a MySQL error message in the main panel when $exit is true.
  434. * Returns the error message otherwise.
  435. *
  436. * @param string|bool $server_msg Server's error message.
  437. * @param string $sql_query The SQL query that failed.
  438. * @param bool $is_modify_link Whether to show a "modify" link or not.
  439. * @param string $back_url URL for the "back" link (full path is
  440. * not required).
  441. * @param bool $exit Whether execution should be stopped or
  442. * the error message should be returned.
  443. *
  444. * @return string
  445. *
  446. * @global string $table The current table.
  447. * @global string $db The current database.
  448. *
  449. * @access public
  450. */
  451. public static function mysqlDie(
  452. $server_msg = '',
  453. $sql_query = '',
  454. $is_modify_link = true,
  455. $back_url = '',
  456. $exit = true
  457. ) {
  458. global $table, $db;
  459. /**
  460. * Error message to be built.
  461. * @var string $error_msg
  462. */
  463. $error_msg = '';
  464. // Checking for any server errors.
  465. if (empty($server_msg)) {
  466. $server_msg = $GLOBALS['dbi']->getError();
  467. }
  468. // Finding the query that failed, if not specified.
  469. if ((empty($sql_query) && (!empty($GLOBALS['sql_query'])))) {
  470. $sql_query = $GLOBALS['sql_query'];
  471. }
  472. $sql_query = trim($sql_query);
  473. /**
  474. * The lexer used for analysis.
  475. * @var Lexer $lexer
  476. */
  477. $lexer = new Lexer($sql_query);
  478. /**
  479. * The parser used for analysis.
  480. * @var Parser $parser
  481. */
  482. $parser = new Parser($lexer->list);
  483. /**
  484. * The errors found by the lexer and the parser.
  485. * @var array $errors
  486. */
  487. $errors = ParserError::get(array($lexer, $parser));
  488. if (empty($sql_query)) {
  489. $formatted_sql = '';
  490. } elseif (count($errors)) {
  491. $formatted_sql = htmlspecialchars($sql_query);
  492. } else {
  493. $formatted_sql = self::formatSql($sql_query, true);
  494. }
  495. $error_msg .= '<div class="error"><h1>' . __('Error') . '</h1>';
  496. // For security reasons, if the MySQL refuses the connection, the query
  497. // is hidden so no details are revealed.
  498. if ((!empty($sql_query)) && (!(mb_strstr($sql_query, 'connect')))) {
  499. // Static analysis errors.
  500. if (!empty($errors)) {
  501. $error_msg .= '<p><strong>' . __('Static analysis:')
  502. . '</strong></p>';
  503. $error_msg .= '<p>' . sprintf(
  504. __('%d errors were found during analysis.'),
  505. count($errors)
  506. ) . '</p>';
  507. $error_msg .= '<p><ol>';
  508. $error_msg .= implode(
  509. ParserError::format(
  510. $errors,
  511. '<li>%2$s (near "%4$s" at position %5$d)</li>'
  512. )
  513. );
  514. $error_msg .= '</ol></p>';
  515. }
  516. // Display the SQL query and link to MySQL documentation.
  517. $error_msg .= '<p><strong>' . __('SQL query:') . '</strong>' . "\n";
  518. $formattedSqlToLower = mb_strtolower($formatted_sql);
  519. // TODO: Show documentation for all statement types.
  520. if (mb_strstr($formattedSqlToLower, 'select')) {
  521. // please show me help to the error on select
  522. $error_msg .= self::showMySQLDocu('SELECT');
  523. }
  524. if ($is_modify_link) {
  525. $_url_params = array(
  526. 'sql_query' => $sql_query,
  527. 'show_query' => 1,
  528. );
  529. if (strlen($table) > 0) {
  530. $_url_params['db'] = $db;
  531. $_url_params['table'] = $table;
  532. $doedit_goto = '<a href="tbl_sql.php'
  533. . Url::getCommon($_url_params) . '">';
  534. } elseif (strlen($db) > 0) {
  535. $_url_params['db'] = $db;
  536. $doedit_goto = '<a href="db_sql.php'
  537. . Url::getCommon($_url_params) . '">';
  538. } else {
  539. $doedit_goto = '<a href="server_sql.php'
  540. . Url::getCommon($_url_params) . '">';
  541. }
  542. $error_msg .= $doedit_goto
  543. . self::getIcon('b_edit', __('Edit'))
  544. . '</a>';
  545. }
  546. $error_msg .= ' </p>' . "\n"
  547. . '<p>' . "\n"
  548. . $formatted_sql . "\n"
  549. . '</p>' . "\n";
  550. }
  551. // Display server's error.
  552. if (!empty($server_msg)) {
  553. $server_msg = preg_replace(
  554. "@((\015\012)|(\015)|(\012)){3,}@",
  555. "\n\n",
  556. $server_msg
  557. );
  558. // Adds a link to MySQL documentation.
  559. $error_msg .= '<p>' . "\n"
  560. . ' <strong>' . __('MySQL said: ') . '</strong>'
  561. . self::showMySQLDocu('Error-messages-server')
  562. . "\n"
  563. . '</p>' . "\n";
  564. // The error message will be displayed within a CODE segment.
  565. // To preserve original formatting, but allow word-wrapping,
  566. // a couple of replacements are done.
  567. // All non-single blanks and TAB-characters are replaced with their
  568. // HTML-counterpart
  569. $server_msg = str_replace(
  570. array(' ', "\t"),
  571. array('&nbsp;&nbsp;', '&nbsp;&nbsp;&nbsp;&nbsp;'),
  572. $server_msg
  573. );
  574. // Replace line breaks
  575. $server_msg = nl2br($server_msg);
  576. $error_msg .= '<code>' . $server_msg . '</code><br/>';
  577. }
  578. $error_msg .= '</div>';
  579. $_SESSION['Import_message']['message'] = $error_msg;
  580. if (!$exit) {
  581. return $error_msg;
  582. }
  583. /**
  584. * If this is an AJAX request, there is no "Back" link and
  585. * `Response()` is used to send the response.
  586. */
  587. $response = Response::getInstance();
  588. if ($response->isAjax()) {
  589. $response->setRequestStatus(false);
  590. $response->addJSON('message', $error_msg);
  591. exit;
  592. }
  593. if (!empty($back_url)) {
  594. if (mb_strstr($back_url, '?')) {
  595. $back_url .= '&amp;no_history=true';
  596. } else {
  597. $back_url .= '?no_history=true';
  598. }
  599. $_SESSION['Import_message']['go_back_url'] = $back_url;
  600. $error_msg .= '<fieldset class="tblFooters">'
  601. . '[ <a href="' . $back_url . '">' . __('Back') . '</a> ]'
  602. . '</fieldset>' . "\n\n";
  603. }
  604. exit($error_msg);
  605. }
  606. /**
  607. * Check the correct row count
  608. *
  609. * @param string $db the db name
  610. * @param array $table the table infos
  611. *
  612. * @return int $rowCount the possibly modified row count
  613. *
  614. */
  615. private static function _checkRowCount($db, array $table)
  616. {
  617. $rowCount = 0;
  618. if ($table['Rows'] === null) {
  619. // Do not check exact row count here,
  620. // if row count is invalid possibly the table is defect
  621. // and this would break the navigation panel;
  622. // but we can check row count if this is a view or the
  623. // information_schema database
  624. // since Table::countRecords() returns a limited row count
  625. // in this case.
  626. // set this because Table::countRecords() can use it
  627. $tbl_is_view = $table['TABLE_TYPE'] == 'VIEW';
  628. if ($tbl_is_view || $GLOBALS['dbi']->isSystemSchema($db)) {
  629. $rowCount = $GLOBALS['dbi']
  630. ->getTable($db, $table['Name'])
  631. ->countRecords();
  632. }
  633. }
  634. return $rowCount;
  635. }
  636. /**
  637. * returns array with tables of given db with extended information and grouped
  638. *
  639. * @param string $db name of db
  640. * @param string $tables name of tables
  641. * @param integer $limit_offset list offset
  642. * @param int|bool $limit_count max tables to return
  643. *
  644. * @return array (recursive) grouped table list
  645. */
  646. public static function getTableList(
  647. $db,
  648. $tables = null,
  649. $limit_offset = 0,
  650. $limit_count = false
  651. ) {
  652. $sep = $GLOBALS['cfg']['NavigationTreeTableSeparator'];
  653. if ($tables === null) {
  654. $tables = $GLOBALS['dbi']->getTablesFull(
  655. $db,
  656. '',
  657. false,
  658. $limit_offset,
  659. $limit_count
  660. );
  661. if ($GLOBALS['cfg']['NaturalOrder']) {
  662. uksort($tables, 'strnatcasecmp');
  663. }
  664. }
  665. if (count($tables) < 1) {
  666. return $tables;
  667. }
  668. $default = array(
  669. 'Name' => '',
  670. 'Rows' => 0,
  671. 'Comment' => '',
  672. 'disp_name' => '',
  673. );
  674. $table_groups = array();
  675. foreach ($tables as $table_name => $table) {
  676. $table['Rows'] = self::_checkRowCount($db, $table);
  677. // in $group we save the reference to the place in $table_groups
  678. // where to store the table info
  679. if ($GLOBALS['cfg']['NavigationTreeEnableGrouping']
  680. && $sep && mb_strstr($table_name, $sep)
  681. ) {
  682. $parts = explode($sep, $table_name);
  683. $group =& $table_groups;
  684. $i = 0;
  685. $group_name_full = '';
  686. $parts_cnt = count($parts) - 1;
  687. while (($i < $parts_cnt)
  688. && ($i < $GLOBALS['cfg']['NavigationTreeTableLevel'])
  689. ) {
  690. $group_name = $parts[$i] . $sep;
  691. $group_name_full .= $group_name;
  692. if (! isset($group[$group_name])) {
  693. $group[$group_name] = array();
  694. $group[$group_name]['is' . $sep . 'group'] = true;
  695. $group[$group_name]['tab' . $sep . 'count'] = 1;
  696. $group[$group_name]['tab' . $sep . 'group']
  697. = $group_name_full;
  698. } elseif (! isset($group[$group_name]['is' . $sep . 'group'])) {
  699. $table = $group[$group_name];
  700. $group[$group_name] = array();
  701. $group[$group_name][$group_name] = $table;
  702. $group[$group_name]['is' . $sep . 'group'] = true;
  703. $group[$group_name]['tab' . $sep . 'count'] = 1;
  704. $group[$group_name]['tab' . $sep . 'group']
  705. = $group_name_full;
  706. } else {
  707. $group[$group_name]['tab' . $sep . 'count']++;
  708. }
  709. $group =& $group[$group_name];
  710. $i++;
  711. }
  712. } else {
  713. if (! isset($table_groups[$table_name])) {
  714. $table_groups[$table_name] = array();
  715. }
  716. $group =& $table_groups;
  717. }
  718. $table['disp_name'] = $table['Name'];
  719. $group[$table_name] = array_merge($default, $table);
  720. }
  721. return $table_groups;
  722. }
  723. /* ----------------------- Set of misc functions ----------------------- */
  724. /**
  725. * Adds backquotes on both sides of a database, table or field name.
  726. * and escapes backquotes inside the name with another backquote
  727. *
  728. * example:
  729. * <code>
  730. * echo backquote('owner`s db'); // `owner``s db`
  731. *
  732. * </code>
  733. *
  734. * @param mixed $a_name the database, table or field name to "backquote"
  735. * or array of it
  736. * @param boolean $do_it a flag to bypass this function (used by dump
  737. * functions)
  738. *
  739. * @return mixed the "backquoted" database, table or field name
  740. *
  741. * @access public
  742. */
  743. public static function backquote($a_name, $do_it = true)
  744. {
  745. if (is_array($a_name)) {
  746. foreach ($a_name as &$data) {
  747. $data = self::backquote($data, $do_it);
  748. }
  749. return $a_name;
  750. }
  751. if (! $do_it) {
  752. if (!(Context::isKeyword($a_name) & Token::FLAG_KEYWORD_RESERVED)
  753. ) {
  754. return $a_name;
  755. }
  756. }
  757. // '0' is also empty for php :-(
  758. if (strlen($a_name) > 0 && $a_name !== '*') {
  759. return '`' . str_replace('`', '``', $a_name) . '`';
  760. }
  761. return $a_name;
  762. } // end of the 'backquote()' function
  763. /**
  764. * Adds backquotes on both sides of a database, table or field name.
  765. * in compatibility mode
  766. *
  767. * example:
  768. * <code>
  769. * echo backquoteCompat('owner`s db'); // `owner``s db`
  770. *
  771. * </code>
  772. *
  773. * @param mixed $a_name the database, table or field name to
  774. * "backquote" or array of it
  775. * @param string $compatibility string compatibility mode (used by dump
  776. * functions)
  777. * @param boolean $do_it a flag to bypass this function (used by dump
  778. * functions)
  779. *
  780. * @return mixed the "backquoted" database, table or field name
  781. *
  782. * @access public
  783. */
  784. public static function backquoteCompat(
  785. $a_name,
  786. $compatibility = 'MSSQL',
  787. $do_it = true
  788. ) {
  789. if (is_array($a_name)) {
  790. foreach ($a_name as &$data) {
  791. $data = self::backquoteCompat($data, $compatibility, $do_it);
  792. }
  793. return $a_name;
  794. }
  795. if (! $do_it) {
  796. if (!Context::isKeyword($a_name)) {
  797. return $a_name;
  798. }
  799. }
  800. // @todo add more compatibility cases (ORACLE for example)
  801. switch ($compatibility) {
  802. case 'MSSQL':
  803. $quote = '"';
  804. break;
  805. default:
  806. $quote = "`";
  807. break;
  808. }
  809. // '0' is also empty for php :-(
  810. if (strlen($a_name) > 0 && $a_name !== '*') {
  811. return $quote . $a_name . $quote;
  812. }
  813. return $a_name;
  814. } // end of the 'backquoteCompat()' function
  815. /**
  816. * Prepare the message and the query
  817. * usually the message is the result of the query executed
  818. *
  819. * @param Message|string $message the message to display
  820. * @param string $sql_query the query to display
  821. * @param string $type the type (level) of the message
  822. *
  823. * @return string
  824. *
  825. * @access public
  826. */
  827. public static function getMessage(
  828. $message,
  829. $sql_query = null,
  830. $type = 'notice'
  831. ) {
  832. global $cfg;
  833. $retval = '';
  834. if (null === $sql_query) {
  835. if (! empty($GLOBALS['display_query'])) {
  836. $sql_query = $GLOBALS['display_query'];
  837. } elseif (! empty($GLOBALS['unparsed_sql'])) {
  838. $sql_query = $GLOBALS['unparsed_sql'];
  839. } elseif (! empty($GLOBALS['sql_query'])) {
  840. $sql_query = $GLOBALS['sql_query'];
  841. } else {
  842. $sql_query = '';
  843. }
  844. }
  845. $render_sql = $cfg['ShowSQL'] == true && ! empty($sql_query) && $sql_query !== ';';
  846. if (isset($GLOBALS['using_bookmark_message'])) {
  847. $retval .= $GLOBALS['using_bookmark_message']->getDisplay();
  848. unset($GLOBALS['using_bookmark_message']);
  849. }
  850. if ($render_sql) {
  851. $retval .= '<div class="result_query">' . "\n";
  852. }
  853. if ($message instanceof Message) {
  854. if (isset($GLOBALS['special_message'])) {
  855. $message->addText($GLOBALS['special_message']);
  856. unset($GLOBALS['special_message']);
  857. }
  858. $retval .= $message->getDisplay();
  859. } else {
  860. $retval .= '<div class="' . $type . '">';
  861. $retval .= Sanitize::sanitize($message);
  862. if (isset($GLOBALS['special_message'])) {
  863. $retval .= Sanitize::sanitize($GLOBALS['special_message']);
  864. unset($GLOBALS['special_message']);
  865. }
  866. $retval .= '</div>';
  867. }
  868. if ($render_sql) {
  869. $query_too_big = false;
  870. $queryLength = mb_strlen($sql_query);
  871. if ($queryLength > $cfg['MaxCharactersInDisplayedSQL']) {
  872. // when the query is large (for example an INSERT of binary
  873. // data), the parser chokes; so avoid parsing the query
  874. $query_too_big = true;
  875. $query_base = mb_substr(
  876. $sql_query,
  877. 0,
  878. $cfg['MaxCharactersInDisplayedSQL']
  879. ) . '[...]';
  880. } else {
  881. $query_base = $sql_query;
  882. }
  883. // Html format the query to be displayed
  884. // If we want to show some sql code it is easiest to create it here
  885. /* SQL-Parser-Analyzer */
  886. if (! empty($GLOBALS['show_as_php'])) {
  887. $new_line = '\\n"<br />' . "\n" . '&nbsp;&nbsp;&nbsp;&nbsp;. "';
  888. $query_base = htmlspecialchars(addslashes($query_base));
  889. $query_base = preg_replace(
  890. '/((\015\012)|(\015)|(\012))/',
  891. $new_line,
  892. $query_base
  893. );
  894. $query_base = '<code class="php"><pre>' . "\n"
  895. . '$sql = "' . $query_base . '";' . "\n"
  896. . '</pre></code>';
  897. } elseif ($query_too_big) {
  898. $query_base = htmlspecialchars($query_base);
  899. } else {
  900. $query_base = self::formatSql($query_base);
  901. }
  902. // Prepares links that may be displayed to edit/explain the query
  903. // (don't go to default pages, we must go to the page
  904. // where the query box is available)
  905. // Basic url query part
  906. $url_params = array();
  907. if (! isset($GLOBALS['db'])) {
  908. $GLOBALS['db'] = '';
  909. }
  910. if (strlen($GLOBALS['db']) > 0) {
  911. $url_params['db'] = $GLOBALS['db'];
  912. if (strlen($GLOBALS['table']) > 0) {
  913. $url_params['table'] = $GLOBALS['table'];
  914. $edit_link = 'tbl_sql.php';
  915. } else {
  916. $edit_link = 'db_sql.php';
  917. }
  918. } else {
  919. $edit_link = 'server_sql.php';
  920. }
  921. // Want to have the query explained
  922. // but only explain a SELECT (that has not been explained)
  923. /* SQL-Parser-Analyzer */
  924. $explain_link = '';
  925. $is_select = preg_match('@^SELECT[[:space:]]+@i', $sql_query);
  926. if (! empty($cfg['SQLQuery']['Explain']) && ! $query_too_big) {
  927. $explain_params = $url_params;
  928. if ($is_select) {
  929. $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
  930. $explain_link = ' [&nbsp;'
  931. . self::linkOrButton(
  932. 'import.php' . Url::getCommon($explain_params),
  933. __('Explain SQL')
  934. ) . '&nbsp;]';
  935. } elseif (preg_match(
  936. '@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i',
  937. $sql_query
  938. )) {
  939. $explain_params['sql_query']
  940. = mb_substr($sql_query, 8);
  941. $explain_link = ' [&nbsp;'
  942. . self::linkOrButton(
  943. 'import.php' . Url::getCommon($explain_params),
  944. __('Skip Explain SQL')
  945. ) . ']';
  946. $url = 'https://mariadb.org/explain_analyzer/analyze/'
  947. . '?client=phpMyAdmin&raw_explain='
  948. . urlencode(self::_generateRowQueryOutput($sql_query));
  949. $explain_link .= ' ['
  950. . self::linkOrButton(
  951. htmlspecialchars('url.php?url=' . urlencode($url)),
  952. sprintf(__('Analyze Explain at %s'), 'mariadb.org'),
  953. array(),
  954. '_blank'
  955. ) . '&nbsp;]';
  956. }
  957. } //show explain
  958. $url_params['sql_query'] = $sql_query;
  959. $url_params['show_query'] = 1;
  960. // even if the query is big and was truncated, offer the chance
  961. // to edit it (unless it's enormous, see linkOrButton() )
  962. if (! empty($cfg['SQLQuery']['Edit'])
  963. && empty($GLOBALS['show_as_php'])
  964. ) {
  965. $edit_link .= Url::getCommon($url_params);
  966. $edit_link = ' [&nbsp;'
  967. . self::linkOrButton($edit_link, __('Edit'))
  968. . '&nbsp;]';
  969. } else {
  970. $edit_link = '';
  971. }
  972. // Also we would like to get the SQL formed in some nice
  973. // php-code
  974. if (! empty($cfg['SQLQuery']['ShowAsPHP']) && ! $query_too_big) {
  975. if (! empty($GLOBALS['show_as_php'])) {
  976. $php_link = ' [&nbsp;'
  977. . self::linkOrButton(
  978. 'import.php' . Url::getCommon($url_params),
  979. __('Without PHP code')
  980. )
  981. . '&nbsp;]';
  982. $php_link .= ' [&nbsp;'
  983. . self::linkOrButton(
  984. 'import.php' . Url::getCommon($url_params),
  985. __('Submit query')
  986. )
  987. . '&nbsp;]';
  988. } else {
  989. $php_params = $url_params;
  990. $php_params['show_as_php'] = 1;
  991. $php_link = ' [&nbsp;'
  992. . self::linkOrButton(
  993. 'import.php' . Url::getCommon($php_params),
  994. __('Create PHP code')
  995. )
  996. . '&nbsp;]';
  997. }
  998. } else {
  999. $php_link = '';
  1000. } //show as php
  1001. // Refresh query
  1002. if (! empty($cfg['SQLQuery']['Refresh'])
  1003. && ! isset($GLOBALS['show_as_php']) // 'Submit query' does the same
  1004. && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)
  1005. ) {
  1006. $refresh_link = 'import.php' . Url::getCommon($url_params);
  1007. $refresh_link = ' [&nbsp;'
  1008. . self::linkOrButton($refresh_link, __('Refresh')) . ']';
  1009. } else {
  1010. $refresh_link = '';
  1011. } //refresh
  1012. $retval .= '<div class="sqlOuter">';
  1013. $retval .= $query_base;
  1014. $retval .= '</div>';
  1015. $retval .= '<div class="tools print_ignore">';
  1016. $retval .= '<form action="sql.php" method="post">';
  1017. $retval .= Url::getHiddenInputs($GLOBALS['db'], $GLOBALS['table']);
  1018. $retval .= '<input type="hidden" name="sql_query" value="'
  1019. . htmlspecialchars($sql_query) . '" />';
  1020. // avoid displaying a Profiling checkbox that could
  1021. // be checked, which would reexecute an INSERT, for example
  1022. if (! empty($refresh_link) && self::profilingSupported()) {
  1023. $retval .= '<input type="hidden" name="profiling_form" value="1" />';
  1024. $retval .= Template::get('checkbox')
  1025. ->render(
  1026. array(
  1027. 'html_field_name' => 'profiling',
  1028. 'label' => __('Profiling'),
  1029. 'checked' => isset($_SESSION['profiling']),
  1030. 'onclick' => true,
  1031. 'html_field_id' => '',
  1032. )
  1033. );
  1034. }
  1035. $retval .= '</form>';
  1036. /**
  1037. * TODO: Should we have $cfg['SQLQuery']['InlineEdit']?
  1038. */
  1039. if (! empty($cfg['SQLQuery']['Edit'])
  1040. && ! $query_too_big
  1041. && empty($GLOBALS['show_as_php'])
  1042. ) {
  1043. $inline_edit_link = ' ['
  1044. . self::linkOrButton(
  1045. '#',
  1046. _pgettext('Inline edit query', 'Edit inline'),
  1047. array('class' => 'inline_edit_sql')
  1048. )
  1049. . ']';
  1050. } else {
  1051. $inline_edit_link = '';
  1052. }
  1053. $retval .= $inline_edit_link . $edit_link . $explain_link . $php_link
  1054. . $refresh_link;
  1055. $retval .= '</div>';
  1056. $retval .= '</div>';
  1057. }
  1058. return $retval;
  1059. } // end of the 'getMessage()' function
  1060. /**
  1061. * Execute an EXPLAIN query and formats results similar to MySQL command line
  1062. * utility.
  1063. *
  1064. * @param string $sqlQuery EXPLAIN query
  1065. *
  1066. * @return string query resuls
  1067. */
  1068. private static function _generateRowQueryOutput($sqlQuery)
  1069. {
  1070. $ret = '';
  1071. $result = $GLOBALS['dbi']->query($sqlQuery);
  1072. if ($result) {
  1073. $devider = '+';
  1074. $columnNames = '|';
  1075. $fieldsMeta = $GLOBALS['dbi']->getFieldsMeta($result);
  1076. foreach ($fieldsMeta as $meta) {
  1077. $devider .= '---+';
  1078. $columnNames .= ' ' . $meta->name . ' |';
  1079. }
  1080. $devider .= "\n";
  1081. $ret .= $devider . $columnNames . "\n" . $devider;
  1082. while ($row = $GLOBALS['dbi']->fetchRow($result)) {
  1083. $values = '|';
  1084. foreach ($row as $value) {
  1085. if (is_null($value)) {
  1086. $value = 'NULL';
  1087. }
  1088. $values .= ' ' . $value . ' |';
  1089. }
  1090. $ret .= $values . "\n";
  1091. }
  1092. $ret .= $devider;
  1093. }
  1094. return $ret;
  1095. }
  1096. /**
  1097. * Verifies if current MySQL server supports profiling
  1098. *
  1099. * @access public
  1100. *
  1101. * @return boolean whether profiling is supported
  1102. */
  1103. public static function profilingSupported()
  1104. {
  1105. if (!self::cacheExists('profiling_supported')) {
  1106. // 5.0.37 has profiling but for example, 5.1.20 does not
  1107. // (avoid a trip to the server for MySQL before 5.0.37)
  1108. // and do not set a constant as we might be switching servers
  1109. if ($GLOBALS['dbi']->fetchValue("SELECT @@have_profiling")
  1110. ) {
  1111. self::cacheSet('profiling_supported', true);
  1112. } else {
  1113. self::cacheSet('profiling_supported', false);
  1114. }
  1115. }
  1116. return self::cacheGet('profiling_supported');
  1117. }
  1118. /**
  1119. * Formats $value to byte view
  1120. *
  1121. * @param double|int $value the value to format
  1122. * @param int $limes the sensitiveness
  1123. * @param int $comma the number of decimals to retain
  1124. *
  1125. * @return array the formatted value and its unit
  1126. *
  1127. * @access public
  1128. */
  1129. public static function formatByteDown($value, $limes = 6, $comma = 0)
  1130. {
  1131. if ($value === null) {
  1132. return null;
  1133. }
  1134. $byteUnits = array(
  1135. /* l10n: shortcuts for Byte */
  1136. __('B'),
  1137. /* l10n: shortcuts for Kilobyte */
  1138. __('KiB'),
  1139. /* l10n: shortcuts for Megabyte */
  1140. __('MiB'),
  1141. /* l10n: shortcuts for Gigabyte */
  1142. __('GiB'),
  1143. /* l10n: shortcuts for Terabyte */
  1144. __('TiB'),
  1145. /* l10n: shortcuts for Petabyte */
  1146. __('PiB'),
  1147. /* l10n: shortcuts for Exabyte */
  1148. __('EiB')
  1149. );
  1150. $dh = pow(10, $comma);
  1151. $li = pow(10, $limes);
  1152. $unit = $byteUnits[0];
  1153. for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
  1154. $unitSize = $li * pow(10, $ex);
  1155. if (isset($byteUnits[$d]) && $value >= $unitSize) {
  1156. // use 1024.0 to avoid integer overflow on 64-bit machines
  1157. $value = round($value / (pow(1024, $d) / $dh)) /$dh;
  1158. $unit = $byteUnits[$d];
  1159. break 1;
  1160. } // end if
  1161. } // end for
  1162. if ($unit != $byteUnits[0]) {
  1163. // if the unit is not bytes (as represented in current language)
  1164. // reformat with max length of 5
  1165. // 4th parameter=true means do not reformat if value < 1
  1166. $return_value = self::formatNumber($value, 5, $comma, true);
  1167. } else {
  1168. // do not reformat, just handle the locale
  1169. $return_value = self::formatNumber($value, 0);
  1170. }
  1171. return array(trim($return_value), $unit);
  1172. } // end of the 'formatByteDown' function
  1173. /**
  1174. * Formats $value to the given length and appends SI prefixes
  1175. * with a $length of 0 no truncation occurs, number is only formatted
  1176. * to the current locale
  1177. *
  1178. * examples:
  1179. * <code>
  1180. * echo formatNumber(123456789, 6); // 123,457 k
  1181. * echo formatNumber(-123456789, 4, 2); // -123.46 M
  1182. * echo formatNumber(-0.003, 6); // -3 m
  1183. * echo formatNumber(0.003, 3, 3); // 0.003
  1184. * echo formatNumber(0.00003, 3, 2); // 0.03 m
  1185. * echo formatNumber(0, 6); // 0
  1186. * </code>
  1187. *
  1188. * @param double $value the value to format
  1189. * @param integer $digits_left number of digits left of the comma
  1190. * @param integer $digits_right number of digits right of the comma
  1191. * @param boolean $only_down do not reformat numbers below 1
  1192. * @param boolean $noTrailingZero removes trailing zeros right of the comma
  1193. * (default: true)
  1194. *
  1195. * @return string the formatted value and its unit
  1196. *
  1197. * @access public
  1198. */
  1199. public static function formatNumber(
  1200. $value,
  1201. $digits_left = 3,
  1202. $digits_right = 0,
  1203. $only_down = false,
  1204. $noTrailingZero = true
  1205. ) {
  1206. if ($value == 0) {
  1207. return '0';
  1208. }
  1209. $originalValue = $value;
  1210. //number_format is not multibyte safe, str_replace is safe
  1211. if ($digits_left === 0) {
  1212. $value = number_format(
  1213. $value,
  1214. $digits_right,
  1215. /* l10n: Decimal separator */
  1216. __('.'),
  1217. /* l10n: Thousands separator */
  1218. __(',')
  1219. );
  1220. if (($originalValue != 0) && (floatval($value) == 0)) {
  1221. $value = ' <' . (1 / pow(10, $digits_right));
  1222. }
  1223. return $value;
  1224. }
  1225. // this units needs no translation, ISO
  1226. $units = array(
  1227. -8 => 'y',
  1228. -7 => 'z',
  1229. -6 => 'a',
  1230. -5 => 'f',
  1231. -4 => 'p',
  1232. -3 => 'n',
  1233. -2 => '&micro;',
  1234. -1 => 'm',
  1235. 0 => ' ',
  1236. 1 => 'k',
  1237. 2 => 'M',
  1238. 3 => 'G',
  1239. 4 => 'T',
  1240. 5 => 'P',
  1241. 6 => 'E',
  1242. 7 => 'Z',
  1243. 8 => 'Y'
  1244. );
  1245. /* l10n: Decimal separator */
  1246. $decimal_sep = __('.');
  1247. /* l10n: Thousands separator */
  1248. $thousands_sep = __(',');
  1249. // check for negative value to retain sign
  1250. if ($value < 0) {
  1251. $sign = '-';
  1252. $value = abs($value);
  1253. } else {
  1254. $sign = '';
  1255. }
  1256. $dh = pow(10, $digits_right);
  1257. /*
  1258. * This gives us the right SI prefix already,
  1259. * but $digits_left parameter not incorporated
  1260. */
  1261. $d = floor(log10($value) / 3);
  1262. /*
  1263. * Lowering the SI prefix by 1 gives us an additional 3 zeros
  1264. * So if we have 3,6,9,12.. free digits ($digits_left - $cur_digits)
  1265. * to use, then lower the SI prefix
  1266. */
  1267. $cur_digits = floor(log10($value / pow(1000, $d))+1);
  1268. if ($digits_left > $cur_digits) {
  1269. $d -= floor(($digits_left - $cur_digits)/3);
  1270. }
  1271. if ($d < 0 && $only_down) {
  1272. $d = 0;
  1273. }
  1274. $value = round($value / (pow(1000, $d) / $dh)) /$dh;
  1275. $unit = $units[$d];
  1276. // number_format is not multibyte safe, str_replace is safe
  1277. $formattedValue = number_format(
  1278. $value,
  1279. $digits_right,
  1280. $decimal_sep,
  1281. $thousands_sep
  1282. );
  1283. // If we don't want any zeros, remove them now
  1284. if ($noTrailingZero && strpos($formattedValue, $decimal_sep) !== false) {
  1285. $formattedValue = preg_replace('/' . preg_quote($decimal_sep) . '?0+$/', '', $formattedValue);
  1286. }
  1287. if ($originalValue != 0 && floatval($value) == 0) {
  1288. return ' <' . number_format(
  1289. (1 / pow(10, $digits_right)),
  1290. $digits_right,
  1291. $decimal_sep,
  1292. $thousands_sep
  1293. )
  1294. . ' ' . $unit;
  1295. }
  1296. return $sign . $formattedValue . ' ' . $unit;
  1297. } // end of the 'formatNumber' function
  1298. /**
  1299. * Returns the number of bytes when a formatted size is given
  1300. *
  1301. * @param string $formatted_size the size expression (for example 8MB)
  1302. *
  1303. * @return integer The numerical part of the expression (for example 8)
  1304. */
  1305. public static function extractValueFromFormattedSize($formatted_size)
  1306. {
  1307. $return_value = -1;
  1308. if (preg_match('/^[0-9]+GB$/', $formatted_size)) {
  1309. $return_value = mb_substr($formatted_size, 0, -2)
  1310. * pow(1024, 3);
  1311. } elseif (preg_match('/^[0-9]+MB$/', $formatted_size)) {
  1312. $return_value = mb_substr($formatted_size, 0, -2)
  1313. * pow(1024, 2);
  1314. } elseif (preg_match('/^[0-9]+K$/', $formatted_size)) {
  1315. $return_value = mb_substr($formatted_size, 0, -1)
  1316. * pow(1024, 1);
  1317. }
  1318. return $return_value;
  1319. }// end of the 'extractValueFromFormattedSize' function
  1320. /**
  1321. * Writes localised date
  1322. *
  1323. * @param integer $timestamp the current timestamp
  1324. * @param string $format format
  1325. *
  1326. * @return string the formatted date
  1327. *
  1328. * @access public
  1329. */
  1330. public static function localisedDate($timestamp = -1, $format = '')
  1331. {
  1332. $month = array(
  1333. /* l10n: Short month name */
  1334. __('Jan'),
  1335. /* l10n: Short month name */
  1336. __('Feb'),
  1337. /* l10n: Short month name */
  1338. __('Mar'),
  1339. /* l10n: Short month name */
  1340. __('Apr'),
  1341. /* l10n: Short month name */
  1342. _pgettext('Short month name', 'May'),
  1343. /* l10n: Short month name */
  1344. __('Jun'),
  1345. /* l10n: Short month name */
  1346. __('Jul'),
  1347. /* l10n: Short month name */
  1348. __('Aug'),
  1349. /* l10n: Short month name */
  1350. __('Sep'),
  1351. /* l10n: Short month name */
  1352. __('Oct'),
  1353. /* l10n: Short month name */
  1354. __('Nov'),
  1355. /* l10n: Short month name */
  1356. __('Dec'));
  1357. $day_of_week = array(
  1358. /* l10n: Short week day name */
  1359. _pgettext('Short week day name', 'Sun'),
  1360. /* l10n: Short week day name */
  1361. __('Mon'),
  1362. /* l10n: Short week day name */
  1363. __('Tue'),
  1364. /* l10n: Short week day name */
  1365. __('Wed'),
  1366. /* l10n: Short week day name */
  1367. __('Thu'),
  1368. /* l10n: Short week day name */
  1369. __('Fri'),
  1370. /* l10n: Short week day name */
  1371. __('Sat'));
  1372. if ($format == '') {
  1373. /* l10n: See https://secure.php.net/manual/en/function.strftime.php */
  1374. $format = __('%B %d, %Y at %I:%M %p');
  1375. }
  1376. if ($timestamp == -1) {
  1377. $timestamp = time();
  1378. }
  1379. $date = preg_replace(
  1380. '@%[aA]@',
  1381. $day_of_week[(int)strftime('%w', $timestamp)],
  1382. $format
  1383. );
  1384. $date = preg_replace(
  1385. '@%[bB]@',
  1386. $month[(int)strftime('%m', $timestamp)-1],
  1387. $date
  1388. );
  1389. /* Fill in AM/PM */
  1390. $hours = (int)date('H', $timestamp);
  1391. if ($hours >= 12) {
  1392. $am_pm = _pgettext('AM/PM indication in time', 'PM');
  1393. } else {
  1394. $am_pm = _pgettext('AM/PM indication in time', 'AM');
  1395. }
  1396. $date = preg_replace('@%[pP]@', $am_pm, $date);
  1397. $ret = strftime($date, $timestamp);
  1398. // Some OSes such as Win8.1 Traditional Chinese version did not produce UTF-8
  1399. // output here. See https://github.com/phpmyadmin/phpmyadmin/issues/10598
  1400. if (mb_detect_encoding($ret, 'UTF-8', true) != 'UTF-8') {
  1401. $ret = date('Y-m-d H:i:s', $timestamp);
  1402. }
  1403. return $ret;
  1404. } // end of the 'localisedDate()' function
  1405. /**
  1406. * returns a tab for tabbed navigation.
  1407. * If the variables $link and $args ar left empty, an inactive tab is created
  1408. *
  1409. * @param array $tab array with all options
  1410. * @param array $url_params tab specific URL parameters
  1411. *
  1412. * @return string html code for one tab, a link if valid otherwise a span
  1413. *
  1414. * @access public
  1415. */
  1416. public static function getHtmlTab(array $tab, array $url_params = array())
  1417. {
  1418. // default values
  1419. $defaults = array(
  1420. 'text' => '',
  1421. 'class' => '',
  1422. 'active' => null,
  1423. 'link' => '',
  1424. 'sep' => '?',
  1425. 'attr' => '',
  1426. 'args' => '',
  1427. 'warning' => '',
  1428. 'fragment' => '',
  1429. 'id' => '',
  1430. );
  1431. $tab = array_merge($defaults, $tab);
  1432. // determine additional style-class
  1433. if (empty($tab['class'])) {
  1434. if (! empty($tab['active'])
  1435. || Core::isValid($GLOBALS['active_page'], 'identical', $tab['link'])
  1436. ) {
  1437. $tab['class'] = 'active';
  1438. } elseif (is_null($tab['active']) && empty($GLOBALS['active_page'])
  1439. && (basename($GLOBALS['PMA_PHP_SELF']) == $tab['link'])
  1440. ) {
  1441. $tab['class'] = 'active';
  1442. }
  1443. }
  1444. // build the link
  1445. if (! empty($tab['link'])) {
  1446. // If there are any tab specific URL parameters, merge those with
  1447. // the general URL parameters
  1448. if (! empty($tab['args']) && is_array($tab['args'])) {
  1449. $url_params = array_merge($url_params, $tab['args']);
  1450. }
  1451. $tab['link'] = htmlentities($tab['link']) . Url::getCommon($url_params);
  1452. }
  1453. if (! empty($tab['fragment'])) {
  1454. $tab['link'] .= $tab['fragment'];
  1455. }
  1456. // display icon
  1457. if (isset($tab['icon'])) {
  1458. // avoid generating an alt tag, because it only illustrates
  1459. // the text that follows and if browser does not display
  1460. // images, the text is duplicated
  1461. $tab['text'] = self::getIcon(
  1462. $tab['icon'],
  1463. $tab['text'],
  1464. false,
  1465. true,
  1466. 'TabsMode'
  1467. );
  1468. } elseif (empty($tab['text'])) {
  1469. // check to not display an empty link-text
  1470. $tab['text'] = '?';
  1471. trigger_error(
  1472. 'empty linktext in function ' . __FUNCTION__ . '()',
  1473. E_USER_NOTICE
  1474. );
  1475. }
  1476. //Set the id for the tab, if set in the params
  1477. $tabId = (empty($tab['id']) ? null : $tab['id']);
  1478. $item = array();
  1479. if (!empty($tab['link'])) {
  1480. $item = array(
  1481. 'content' => $tab['text'],
  1482. 'url' => array(
  1483. 'href' => empty($tab['link']) ? null : $tab['link'],
  1484. 'id' => $tabId,
  1485. 'class' => 'tab' . htmlentities($tab['class']),
  1486. ),
  1487. );
  1488. } else {
  1489. $item['content'] = '<span class="tab' . htmlentities($tab['class']) . '"'
  1490. . $tabId . '>' . $tab['text'] . '</span>';
  1491. }
  1492. $item['class'] = $tab['class'] == 'active' ? 'active' : '';
  1493. return Template::get('list/item')
  1494. ->render($item);
  1495. } // end of the 'getHtmlTab()' function
  1496. /**
  1497. * returns html-code for a tab navigation
  1498. *
  1499. * @param array $tabs one element per tab
  1500. * @param array $url_params additional URL parameters
  1501. * @param string $menu_id HTML id attribute for the menu container
  1502. * @param bool $resizable whether to add a "resizable" class
  1503. *
  1504. * @return string html-code for tab-navigation
  1505. */
  1506. public static function getHtmlTabs(
  1507. array $tabs,
  1508. array $url_params,
  1509. $menu_id,
  1510. $resizable = false
  1511. ) {
  1512. $class = '';
  1513. if ($resizable) {
  1514. $class = ' class="resizable-menu"';
  1515. }
  1516. $tab_navigation = '<div id="' . htmlentities($menu_id)
  1517. . 'container" class="menucontainer">'
  1518. . '<i class="scrollindicator scrollindicator--left"><a href="#" class="tab"></a></i>'
  1519. . '<div class="navigationbar"><ul id="' . htmlentities($menu_id) . '" ' . $class . '>';
  1520. foreach ($tabs as $tab) {
  1521. $tab_navigation .= self::getHtmlTab($tab, $url_params);
  1522. }
  1523. $tab_navigation .= '';
  1524. $tab_navigation .=
  1525. '<div class="clearfloat"></div>'
  1526. . '</ul></div>' . "\n"
  1527. . '<i class="scrollindicator scrollindicator--right"><a href="#" class="tab"></a></i>'
  1528. . '</div>' . "\n";
  1529. return $tab_navigation;
  1530. }
  1531. /**
  1532. * Displays a link, or a link with code to trigger POST request.
  1533. *
  1534. * POST is used in following cases:
  1535. *
  1536. * - URL is too long
  1537. * - URL components are over Suhosin limits
  1538. * - There is SQL query in the parameters
  1539. *
  1540. * @param string $url the URL
  1541. * @param string $message the link message
  1542. * @param mixed $tag_params string: js confirmation; array: additional tag
  1543. * params (f.e. style="")
  1544. * @param string $target target
  1545. *
  1546. * @return string the results to be echoed or saved in an array
  1547. */
  1548. public static function linkOrButton(
  1549. $url, $message, $tag_params = array(), $target = ''
  1550. ) {
  1551. $url_length = strlen($url);
  1552. if (! is_array($tag_params)) {
  1553. $tmp = $tag_params;
  1554. $tag_params = array();
  1555. if (! empty($tmp)) {
  1556. $tag_params['onclick'] = 'return confirmLink(this, \''
  1557. . Sanitize::escapeJsString($tmp) . '\')';
  1558. }
  1559. unset($tmp);
  1560. }
  1561. if (! empty($target)) {
  1562. $tag_params['target'] = $target;
  1563. if ($target === '_blank' && strncmp($url, 'url.php?', 8) == 0) {
  1564. $tag_params['rel'] = 'noopener noreferrer';
  1565. }
  1566. }
  1567. // Suhosin: Check that each query parameter is not above maximum
  1568. $in_suhosin_limits = true;
  1569. if ($url_length <= $GLOBALS['cfg']['LinkLengthLimit']) {
  1570. $suhosin_get_MaxValueLength = ini_get('suhosin.get.max_value_length');
  1571. if ($suhosin_get_MaxValueLength) {
  1572. $query_parts = self::splitURLQuery($url);
  1573. foreach ($query_parts as $query_pair) {
  1574. if (strpos($query_pair, '=') === false) {
  1575. continue;
  1576. }
  1577. list(, $eachval) = explode('=', $query_pair);
  1578. if (strlen($eachval) > $suhosin_get_MaxValueLength
  1579. ) {
  1580. $in_suhosin_limits = false;
  1581. break;
  1582. }
  1583. }
  1584. }
  1585. }
  1586. $tag_params_strings = array();
  1587. if (($url_length > $GLOBALS['cfg']['LinkLengthLimit'])
  1588. || ! $in_suhosin_limits
  1589. || strpos($url, 'sql_query=') !== false
  1590. ) {
  1591. $parts = explode('?', $url, 2);
  1592. /*
  1593. * The data-post indicates that client should do POST
  1594. * this is handled in js/ajax.js
  1595. */
  1596. $tag_params_strings[] = 'data-post="' . (isset($parts[1]) ? $parts[1] : '') . '"';
  1597. $url = $parts[0];
  1598. if(array_key_exists('class', $tag_params)
  1599. && strpos($tag_params['class'], 'create_view') !== false
  1600. ) {
  1601. $url .= '?' . explode('&', $parts[1], 2)[0];
  1602. }
  1603. }
  1604. foreach ($tag_params as $par_name => $par_value) {
  1605. $tag_params_strings[] = $par_name . '="' . htmlspecialchars($par_value) . '"';
  1606. }
  1607. // no whitespace within an <a> else Safari will make it part of the link
  1608. return '<a href="' . $url . '" '
  1609. . implode(' ', $tag_params_strings) . '>'
  1610. . $message . '</a>';
  1611. } // end of the 'linkOrButton()' function
  1612. /**
  1613. * Splits a URL string by parameter
  1614. *
  1615. * @param string $url the URL
  1616. *
  1617. * @return array the parameter/value pairs, for example [0] db=sakila
  1618. */
  1619. public static function splitURLQuery($url)
  1620. {
  1621. // decode encoded url separators
  1622. $separator = Url::getArgSeparator();
  1623. // on most places separator is still hard coded ...
  1624. if ($separator !== '&') {
  1625. // ... so always replace & with $separator
  1626. $url = str_replace(htmlentities('&'), $separator, $url);
  1627. $url = str_replace('&', $separator, $url);
  1628. }
  1629. $url = str_replace(htmlentities($separator), $separator, $url);
  1630. // end decode
  1631. $url_parts = parse_url($url);
  1632. if (! empty($url_parts['query'])) {
  1633. return explode($separator, $url_parts['query']);
  1634. }
  1635. return array();
  1636. }
  1637. /**
  1638. * Returns a given timespan value in a readable format.
  1639. *
  1640. * @param int $seconds the timespan
  1641. *
  1642. * @return string the formatted value
  1643. */
  1644. public static function timespanFormat($seconds)
  1645. {
  1646. $days = floor($seconds / 86400);
  1647. if ($days > 0) {
  1648. $seconds -= $days * 86400;
  1649. }
  1650. $hours = floor($seconds / 3600);
  1651. if ($days > 0 || $hours > 0) {
  1652. $seconds -= $hours * 3600;
  1653. }
  1654. $minutes = floor($seconds / 60);
  1655. if ($days > 0 || $hours > 0 || $minutes > 0) {
  1656. $seconds -= $minutes * 60;
  1657. }
  1658. return sprintf(
  1659. __('%s days, %s hours, %s minutes and %s seconds'),
  1660. (string)$days,
  1661. (string)$hours,
  1662. (string)$minutes,
  1663. (string)$seconds
  1664. );
  1665. }
  1666. /**
  1667. * Function added to avoid path disclosures.
  1668. * Called by each script that needs parameters, it displays
  1669. * an error message and, by default, stops the execution.
  1670. *
  1671. * @param string[] $params The names of the parameters needed by the calling
  1672. * script
  1673. * @param boolean $request Check parameters in request
  1674. *
  1675. * @return void
  1676. *
  1677. * @access public
  1678. */
  1679. public static function checkParameters($params, $request=false)
  1680. {
  1681. $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
  1682. $found_error = false;
  1683. $error_message = '';
  1684. if ($request) {
  1685. $array = $_REQUEST;
  1686. } else {
  1687. $array = $GLOBALS;
  1688. }
  1689. foreach ($params as $param) {
  1690. if (! isset($array[$param])) {
  1691. $error_message .= $reported_script_name
  1692. . ': ' . __('Missing parameter:') . ' '
  1693. . $param
  1694. . self::showDocu('faq', 'faqmissingparameters',true)
  1695. . '[br]';
  1696. $found_error = true;
  1697. }
  1698. }
  1699. if ($found_error) {
  1700. Core::fatalError($error_message);
  1701. }
  1702. } // end function
  1703. /**
  1704. * Function to generate unique condition for specified row.
  1705. *
  1706. * @param resource $handle current query result
  1707. * @param integer $fields_cnt number of fields
  1708. * @param array $fields_meta meta information about fields
  1709. * @param array $row current row
  1710. * @param boolean $force_unique generate condition only on pk
  1711. * or unique
  1712. * @param string|boolean $restrict_to_table restrict the unique condition
  1713. * to this table or false if
  1714. * none
  1715. * @param array|null $analyzed_sql_results the analyzed query
  1716. *
  1717. * @access public
  1718. *
  1719. * @return array the calculated condition and whether condition is unique
  1720. */
  1721. public static function getUniqueCondition(
  1722. $handle, $fields_cnt, array $fields_meta, array $row, $force_unique = false,
  1723. $restrict_to_table = false, $analyzed_sql_results = null
  1724. ) {
  1725. $primary_key = '';
  1726. $unique_key = '';
  1727. $nonprimary_condition = '';
  1728. $preferred_condition = '';
  1729. $primary_key_array = array();
  1730. $unique_key_array = array();
  1731. $nonprimary_condition_array = array();
  1732. $condition_array = array();
  1733. for ($i = 0; $i < $fields_cnt; ++$i) {
  1734. $con_val = '';
  1735. $field_flags = $GLOBALS['dbi']->fieldFlags($handle, $i);
  1736. $meta = $fields_meta[$i];
  1737. // do not use a column alias in a condition
  1738. if (! isset($meta->orgname) || strlen($meta->orgname) === 0) {
  1739. $meta->orgname = $meta->name;
  1740. if (!empty($analyzed_sql_results['statement']->expr)) {
  1741. foreach ($analyzed_sql_results['statement']->expr as $expr) {
  1742. if ((empty($expr->alias)) || (empty($expr->column))) {
  1743. continue;
  1744. }
  1745. if (strcasecmp($meta->name, $expr->alias) == 0) {
  1746. $meta->orgname = $expr->column;
  1747. break;
  1748. }
  1749. }
  1750. }
  1751. }
  1752. // Do not use a table alias in a condition.
  1753. // Test case is:
  1754. // select * from galerie x WHERE
  1755. //(select count(*) from galerie y where y.datum=x.datum)>1
  1756. //
  1757. // But orgtable is present only with mysqli extension so the
  1758. // fix is only for mysqli.
  1759. // Also, do not use the original table name if we are dealing with
  1760. // a view because this view might be updatable.
  1761. // (The isView() verification should not be costly in most cases
  1762. // because there is some caching in the function).
  1763. if (isset($meta->orgtable)
  1764. && ($meta->table != $meta->orgtable)
  1765. && ! $GLOBALS['dbi']->getTable($GLOBALS['db'], $meta->table)->isView()
  1766. ) {
  1767. $meta->table = $meta->orgtable;
  1768. }
  1769. // If this field is not from the table which the unique clause needs
  1770. // to be restricted to.
  1771. if ($restrict_to_table && $restrict_to_table != $meta->table) {
  1772. continue;
  1773. }
  1774. // to fix the bug where float fields (primary or not)
  1775. // can't be matched because of the imprecision of
  1776. // floating comparison, use CONCAT
  1777. // (also, the syntax "CONCAT(field) IS NULL"
  1778. // that we need on the next "if" will work)
  1779. if ($meta->type == 'real') {
  1780. $con_key = 'CONCAT(' . self::backquote($meta->table) . '.'
  1781. . self::backquote($meta->orgname) . ')';
  1782. } else {
  1783. $con_key = self::backquote($meta->table) . '.'
  1784. . self::backquote($meta->orgname);
  1785. } // end if... else...
  1786. $condition = ' ' . $con_key . ' ';
  1787. if (! isset($row[$i]) || is_null($row[$i])) {
  1788. $con_val = 'IS NULL';
  1789. } else {
  1790. // timestamp is numeric on some MySQL 4.1
  1791. // for real we use CONCAT above and it should compare to string
  1792. if ($meta->numeric
  1793. && ($meta->type != 'timestamp')
  1794. && ($meta->type != 'real')
  1795. ) {
  1796. $con_val = '= ' . $row[$i];
  1797. } elseif ((($meta->type == 'blob') || ($meta->type == 'string'))
  1798. && stristr($field_flags, 'BINARY')
  1799. && ! empty($row[$i])
  1800. ) {
  1801. // hexify only if this is a true not empty BLOB or a BINARY
  1802. // do not waste memory building a too big condition
  1803. if (mb_strlen($row[$i]) < 1000) {
  1804. // use a CAST if possible, to avoid problems
  1805. // if the field contains wildcard characters % or _
  1806. $con_val = '= CAST(0x' . bin2hex($row[$i]) . ' AS BINARY)';
  1807. } elseif ($fields_cnt == 1) {
  1808. // when this blob is the only field present
  1809. // try settling with length comparison
  1810. $condition = ' CHAR_LENGTH(' . $con_key . ') ';
  1811. $con_val = ' = ' . mb_strlen($row[$i]);
  1812. } else {
  1813. // this blob won't be part of the final condition
  1814. $con_val = null;
  1815. }
  1816. } elseif (in_array($meta->type, self::getGISDatatypes())
  1817. && ! empty($row[$i])
  1818. ) {
  1819. // do not build a too big condition
  1820. if (mb_strlen($row[$i]) < 5000) {
  1821. $condition .= '=0x' . bin2hex($row[$i]) . ' AND';
  1822. } else {
  1823. $condition = '';
  1824. }
  1825. } elseif ($meta->type == 'bit') {
  1826. $con_val = "= b'"
  1827. . self::printableBitValue($row[$i], $meta->length) . "'";
  1828. } else {
  1829. $con_val = '= \''
  1830. . $GLOBALS['dbi']->escapeString($row[$i]) . '\'';
  1831. }
  1832. }
  1833. if ($con_val != null) {
  1834. $condition .= $con_val . ' AND';
  1835. if ($meta->primary_key > 0) {
  1836. $primary_key .= $condition;
  1837. $primary_key_array[$con_key] = $con_val;
  1838. } elseif ($meta->unique_key > 0) {
  1839. $unique_key .= $condition;
  1840. $unique_key_array[$con_key] = $con_val;
  1841. }
  1842. $nonprimary_condition .= $condition;
  1843. $nonprimary_condition_array[$con_key] = $con_val;
  1844. }
  1845. } // end for
  1846. // Correction University of Virginia 19991216:
  1847. // prefer primary or unique keys for condition,
  1848. // but use conjunction of all values if no primary key
  1849. $clause_is_unique = true;
  1850. if ($primary_key) {
  1851. $preferred_condition = $primary_key;
  1852. $condition_array = $primary_key_array;
  1853. } elseif ($unique_key) {
  1854. $preferred_condition = $unique_key;
  1855. $condition_array = $unique_key_array;
  1856. } elseif (! $force_unique) {
  1857. $preferred_condition = $nonprimary_condition;
  1858. $condition_array = $nonprimary_condition_array;
  1859. $clause_is_unique = false;
  1860. }
  1861. $where_clause = trim(preg_replace('|\s?AND$|', '', $preferred_condition));
  1862. return(array($where_clause, $clause_is_unique, $condition_array));
  1863. } // end function
  1864. /**
  1865. * Generate the charset query part
  1866. *
  1867. * @param string $collation Collation
  1868. * @param boolean optional $override force 'CHARACTER SET' keyword
  1869. *
  1870. * @return string
  1871. */
  1872. static function getCharsetQueryPart($collation, $override = false)
  1873. {
  1874. list($charset) = explode('_', $collation);
  1875. $keyword = ' CHARSET=';
  1876. if ($override) {
  1877. $keyword = ' CHARACTER SET ';
  1878. }
  1879. return $keyword . $charset
  1880. . ($charset == $collation ? '' : ' COLLATE ' . $collation);
  1881. }
  1882. /**
  1883. * Generate a button or image tag
  1884. *
  1885. * @param string $button_name name of button element
  1886. * @param string $button_class class of button or image element
  1887. * @param string $text text to display
  1888. * @param string $image image to display
  1889. * @param string $value value
  1890. *
  1891. * @return string html content
  1892. *
  1893. * @access public
  1894. */
  1895. public static function getButtonOrImage(
  1896. $button_name, $button_class, $text, $image, $value = ''
  1897. ) {
  1898. if ($value == '') {
  1899. $value = $text;
  1900. }
  1901. if ($GLOBALS['cfg']['ActionLinksMode'] == 'text') {
  1902. return ' <input type="submit" name="' . $button_name . '"'
  1903. . ' value="' . htmlspecialchars($value) . '"'
  1904. . ' title="' . htmlspecialchars($text) . '" />' . "\n";
  1905. }
  1906. return '<button class="' . $button_class . '" type="submit"'
  1907. . ' name="' . $button_name . '" value="' . htmlspecialchars($value)
  1908. . '" title="' . htmlspecialchars($text) . '">' . "\n"
  1909. . self::getIcon($image, $text)
  1910. . '</button>' . "\n";
  1911. } // end function
  1912. /**
  1913. * Generate a pagination selector for browsing resultsets
  1914. *
  1915. * @param string $name The name for the request parameter
  1916. * @param int $rows Number of rows in the pagination set
  1917. * @param int $pageNow current page number
  1918. * @param int $nbTotalPage number of total pages
  1919. * @param int $showAll If the number of pages is lower than this
  1920. * variable, no pages will be omitted in pagination
  1921. * @param int $sliceStart How many rows at the beginning should always
  1922. * be shown?
  1923. * @param int $sliceEnd How many rows at the end should always be shown?
  1924. * @param int $percent Percentage of calculation page offsets to hop to a
  1925. * next page
  1926. * @param int $range Near the current page, how many pages should
  1927. * be considered "nearby" and displayed as well?
  1928. * @param string $prompt The prompt to display (sometimes empty)
  1929. *
  1930. * @return string
  1931. *
  1932. * @access public
  1933. */
  1934. public static function pageselector(
  1935. $name, $rows, $pageNow = 1, $nbTotalPage = 1, $showAll = 200,
  1936. $sliceStart = 5,
  1937. $sliceEnd = 5, $percent = 20, $range = 10, $prompt = ''
  1938. ) {
  1939. $increment = floor($nbTotalPage / $percent);
  1940. $pageNowMinusRange = ($pageNow - $range);
  1941. $pageNowPlusRange = ($pageNow + $range);
  1942. $gotopage = $prompt . ' <select class="pageselector ajax"';
  1943. $gotopage .= ' name="' . $name . '" >';
  1944. if ($nbTotalPage < $showAll) {
  1945. $pages = range(1, $nbTotalPage);
  1946. } else {
  1947. $pages = array();
  1948. // Always show first X pages
  1949. for ($i = 1; $i <= $sliceStart; $i++) {
  1950. $pages[] = $i;
  1951. }
  1952. // Always show last X pages
  1953. for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++) {
  1954. $pages[] = $i;
  1955. }
  1956. // Based on the number of results we add the specified
  1957. // $percent percentage to each page number,
  1958. // so that we have a representing page number every now and then to
  1959. // immediately jump to specific pages.
  1960. // As soon as we get near our currently chosen page ($pageNow -
  1961. // $range), every page number will be shown.
  1962. $i = $sliceStart;
  1963. $x = $nbTotalPage - $sliceEnd;
  1964. $met_boundary = false;
  1965. while ($i <= $x) {
  1966. if ($i >= $pageNowMinusRange && $i <= $pageNowPlusRange) {
  1967. // If our pageselector comes near the current page, we use 1
  1968. // counter increments
  1969. $i++;
  1970. $met_boundary = true;
  1971. } else {
  1972. // We add the percentage increment to our current page to
  1973. // hop to the next one in range
  1974. $i += $increment;
  1975. // Make sure that we do not cross our boundaries.
  1976. if ($i > $pageNowMinusRange && ! $met_boundary) {
  1977. $i = $pageNowMinusRange;
  1978. }
  1979. }
  1980. if ($i > 0 && $i <= $x) {
  1981. $pages[] = $i;
  1982. }
  1983. }
  1984. /*
  1985. Add page numbers with "geometrically increasing" distances.
  1986. This helps me a lot when navigating through giant tables.
  1987. Test case: table with 2.28 million sets, 76190 pages. Page of interest
  1988. is between 72376 and 76190.
  1989. Selecting page 72376.
  1990. Now, old version enumerated only +/- 10 pages around 72376 and the
  1991. percentage increment produced steps of about 3000.
  1992. The following code adds page numbers +/- 2,4,8,16,32,64,128,256 etc.
  1993. around the current page.
  1994. */
  1995. $i = $pageNow;
  1996. $dist = 1;
  1997. while ($i < $x) {
  1998. $dist = 2 * $dist;
  1999. $i = $pageNow + $dist;
  2000. if ($i > 0 && $i <= $x) {
  2001. $pages[] = $i;
  2002. }
  2003. }
  2004. $i = $pageNow;
  2005. $dist = 1;
  2006. while ($i > 0) {
  2007. $dist = 2 * $dist;
  2008. $i = $pageNow - $dist;
  2009. if ($i > 0 && $i <= $x) {
  2010. $pages[] = $i;
  2011. }
  2012. }
  2013. // Since because of ellipsing of the current page some numbers may be
  2014. // double, we unify our array:
  2015. sort($pages);
  2016. $pages = array_unique($pages);
  2017. }
  2018. foreach ($pages as $i) {
  2019. if ($i == $pageNow) {
  2020. $selected = 'selected="selected" style="font-weight: bold"';
  2021. } else {
  2022. $selected = '';
  2023. }
  2024. $gotopage .= ' <option ' . $selected
  2025. . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
  2026. }
  2027. $gotopage .= ' </select>';
  2028. return $gotopage;
  2029. } // end function
  2030. /**
  2031. * Prepare navigation for a list
  2032. *
  2033. * @param int $count number of elements in the list
  2034. * @param int $pos current position in the list
  2035. * @param array $_url_params url parameters
  2036. * @param string $script script name for form target
  2037. * @param string $frame target frame
  2038. * @param int $max_count maximum number of elements to display from
  2039. * the list
  2040. * @param string $name the name for the request parameter
  2041. * @param string[] $classes additional classes for the container
  2042. *
  2043. * @return string $list_navigator_html the html content
  2044. *
  2045. * @access public
  2046. *
  2047. * @todo use $pos from $_url_params
  2048. */
  2049. public static function getListNavigator(
  2050. $count, $pos, array $_url_params, $script, $frame, $max_count, $name = 'pos',
  2051. $classes = array()
  2052. ) {
  2053. // This is often coming from $cfg['MaxTableList'] and
  2054. // people sometimes set it to empty string
  2055. $max_count = intval($max_count);
  2056. if ($max_count <= 0) {
  2057. $max_count = 250;
  2058. }
  2059. $class = $frame == 'frame_navigation' ? ' class="ajax"' : '';
  2060. $list_navigator_html = '';
  2061. if ($max_count < $count) {
  2062. $classes[] = 'pageselector';
  2063. $list_navigator_html .= '<div class="' . implode(' ', $classes) . '">';
  2064. if ($frame != 'frame_navigation') {
  2065. $list_navigator_html .= __('Page number:');
  2066. }
  2067. // Move to the beginning or to the previous page
  2068. if ($pos > 0) {
  2069. $caption1 = ''; $caption2 = '';
  2070. if (self::showIcons('TableNavigationLinksMode')) {
  2071. $caption1 .= '&lt;&lt; ';
  2072. $caption2 .= '&lt; ';
  2073. }
  2074. if (self::showText('TableNavigationLinksMode')) {
  2075. $caption1 .= _pgettext('First page', 'Begin');
  2076. $caption2 .= _pgettext('Previous page', 'Previous');
  2077. }
  2078. $title1 = ' title="' . _pgettext('First page', 'Begin') . '"';
  2079. $title2 = ' title="' . _pgettext('Previous page', 'Previous') . '"';
  2080. $_url_params[$name] = 0;
  2081. $list_navigator_html .= '<a' . $class . $title1 . ' href="' . $script
  2082. . Url::getCommon($_url_params) . '">' . $caption1
  2083. . '</a>';
  2084. $_url_params[$name] = $pos - $max_count;
  2085. $list_navigator_html .= ' <a' . $class . $title2
  2086. . ' href="' . $script . Url::getCommon($_url_params) . '">'
  2087. . $caption2 . '</a>';
  2088. }
  2089. $list_navigator_html .= '<form action="' . basename($script)
  2090. . '" method="post">';
  2091. $list_navigator_html .= Url::getHiddenInputs($_url_params);
  2092. $list_navigator_html .= self::pageselector(
  2093. $name,
  2094. $max_count,
  2095. floor(($pos + 1) / $max_count) + 1,
  2096. ceil($count / $max_count)
  2097. );
  2098. $list_navigator_html .= '</form>';
  2099. if ($pos + $max_count < $count) {
  2100. $caption3 = ''; $caption4 = '';
  2101. if (self::showText('TableNavigationLinksMode')) {
  2102. $caption3 .= _pgettext('Next page', 'Next');
  2103. $caption4 .= _pgettext('Last page', 'End');
  2104. }
  2105. if (self::showIcons('TableNavigationLinksMode')) {
  2106. $caption3 .= ' &gt;';
  2107. $caption4 .= ' &gt;&gt;';
  2108. if (! self::showText('TableNavigationLinksMode')) {
  2109. }
  2110. }
  2111. $title3 = ' title="' . _pgettext('Next page', 'Next') . '"';
  2112. $title4 = ' title="' . _pgettext('Last page', 'End') . '"';
  2113. $_url_params[$name] = $pos + $max_count;
  2114. $list_navigator_html .= '<a' . $class . $title3 . ' href="' . $script
  2115. . Url::getCommon($_url_params) . '" >' . $caption3
  2116. . '</a>';
  2117. $_url_params[$name] = floor($count / $max_count) * $max_count;
  2118. if ($_url_params[$name] == $count) {
  2119. $_url_params[$name] = $count - $max_count;
  2120. }
  2121. $list_navigator_html .= ' <a' . $class . $title4
  2122. . ' href="' . $script . Url::getCommon($_url_params) . '" >'
  2123. . $caption4 . '</a>';
  2124. }
  2125. $list_navigator_html .= '</div>' . "\n";
  2126. }
  2127. return $list_navigator_html;
  2128. }
  2129. /**
  2130. * replaces %u in given path with current user name
  2131. *
  2132. * example:
  2133. * <code>
  2134. * $user_dir = userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
  2135. *
  2136. * </code>
  2137. *
  2138. * @param string $dir with wildcard for user
  2139. *
  2140. * @return string per user directory
  2141. */
  2142. public static function userDir($dir)
  2143. {
  2144. // add trailing slash
  2145. if (mb_substr($dir, -1) != '/') {
  2146. $dir .= '/';
  2147. }
  2148. return str_replace('%u', Core::securePath($GLOBALS['cfg']['Server']['user']), $dir);
  2149. }
  2150. /**
  2151. * returns html code for db link to default db page
  2152. *
  2153. * @param string $database database
  2154. *
  2155. * @return string html link to default db page
  2156. */
  2157. public static function getDbLink($database = null)
  2158. {
  2159. if (strlen($database) === 0) {
  2160. if (strlen($GLOBALS['db']) === 0) {
  2161. return '';
  2162. }
  2163. $database = $GLOBALS['db'];
  2164. } else {
  2165. $database = self::unescapeMysqlWildcards($database);
  2166. }
  2167. return '<a href="'
  2168. . self::getScriptNameForOption(
  2169. $GLOBALS['cfg']['DefaultTabDatabase'], 'database'
  2170. )
  2171. . Url::getCommon(array('db' => $database)) . '" title="'
  2172. . htmlspecialchars(
  2173. sprintf(
  2174. __('Jump to database “%s”.'),
  2175. $database
  2176. )
  2177. )
  2178. . '">' . htmlspecialchars($database) . '</a>';
  2179. }
  2180. /**
  2181. * Prepare a lightbulb hint explaining a known external bug
  2182. * that affects a functionality
  2183. *
  2184. * @param string $functionality localized message explaining the func.
  2185. * @param string $component 'mysql' (eventually, 'php')
  2186. * @param string $minimum_version of this component
  2187. * @param string $bugref bug reference for this component
  2188. *
  2189. * @return String
  2190. */
  2191. public static function getExternalBug(
  2192. $functionality, $component, $minimum_version, $bugref
  2193. ) {
  2194. $ext_but_html = '';
  2195. if (($component == 'mysql') && ($GLOBALS['dbi']->getVersion() < $minimum_version)) {
  2196. $ext_but_html .= self::showHint(
  2197. sprintf(
  2198. __('The %s functionality is affected by a known bug, see %s'),
  2199. $functionality,
  2200. Core::linkURL('https://bugs.mysql.com/') . $bugref
  2201. )
  2202. );
  2203. }
  2204. return $ext_but_html;
  2205. }
  2206. /**
  2207. * Generates a set of radio HTML fields
  2208. *
  2209. * @param string $html_field_name the radio HTML field
  2210. * @param array $choices the choices values and labels
  2211. * @param string $checked_choice the choice to check by default
  2212. * @param boolean $line_break whether to add HTML line break after a choice
  2213. * @param boolean $escape_label whether to use htmlspecialchars() on label
  2214. * @param string $class enclose each choice with a div of this class
  2215. * @param string $id_prefix prefix for the id attribute, name will be
  2216. * used if this is not supplied
  2217. *
  2218. * @return string set of html radio fiels
  2219. */
  2220. public static function getRadioFields(
  2221. $html_field_name, array $choices, $checked_choice = '',
  2222. $line_break = true, $escape_label = true, $class = '',
  2223. $id_prefix = ''
  2224. ) {
  2225. $radio_html = '';
  2226. foreach ($choices as $choice_value => $choice_label) {
  2227. if (! $id_prefix) {
  2228. $id_prefix = $html_field_name;
  2229. }
  2230. $html_field_id = $id_prefix . '_' . $choice_value;
  2231. if ($choice_value == $checked_choice){
  2232. $checked = 1;
  2233. }
  2234. else{
  2235. $checked = 0;
  2236. }
  2237. $radio_html .= Template::get('radio_fields')->render([
  2238. 'class' => $class,
  2239. 'html_field_name' => $html_field_name,
  2240. 'html_field_id' => $html_field_id,
  2241. 'choice_value' => $choice_value,
  2242. 'is_line_break' => $line_break,
  2243. 'choice_label' => $choice_label,
  2244. 'escape_label' => $escape_label,
  2245. 'checked' => $checked
  2246. ]);
  2247. }
  2248. return $radio_html;
  2249. }
  2250. /**
  2251. * Generates and returns an HTML dropdown
  2252. *
  2253. * @param string $select_name name for the select element
  2254. * @param array $choices choices values
  2255. * @param string $active_choice the choice to select by default
  2256. * @param string $id id of the select element; can be different in
  2257. * case the dropdown is present more than once
  2258. * on the page
  2259. * @param string $class class for the select element
  2260. * @param string $placeholder Placeholder for dropdown if nothing else
  2261. * is selected
  2262. *
  2263. * @return string html content
  2264. *
  2265. * @todo support titles
  2266. */
  2267. public static function getDropdown(
  2268. $select_name, array $choices, $active_choice, $id, $class = '', $placeholder = null
  2269. ) {
  2270. $resultOptions = [];
  2271. $selected = false;
  2272. foreach ($choices as $one_choice_value => $one_choice_label) {
  2273. $resultOptions[$one_choice_value]['value'] = $one_choice_value;
  2274. $resultOptions[$one_choice_value]['selected'] = false;
  2275. if ($one_choice_value == $active_choice) {
  2276. $resultOptions[$one_choice_value]['selected'] = true;
  2277. $selected = true;
  2278. }
  2279. $resultOptions[$one_choice_value]['label'] = $one_choice_label;
  2280. }
  2281. return Template::get('dropdown')->render([
  2282. 'select_name' => $select_name,
  2283. 'id' => $id,
  2284. 'class' => $class,
  2285. 'placeholder' => $placeholder,
  2286. 'selected' => $selected,
  2287. 'result_options' => $resultOptions,
  2288. ]);
  2289. }
  2290. /**
  2291. * Generates a slider effect (jQjuery)
  2292. * Takes care of generating the initial <div> and the link
  2293. * controlling the slider; you have to generate the </div> yourself
  2294. * after the sliding section.
  2295. *
  2296. * @param string $id the id of the <div> on which to apply the effect
  2297. * @param string $message the message to show as a link
  2298. * @param string|null $overrideDefault override InitialSlidersState config
  2299. *
  2300. * @return string html div element
  2301. *
  2302. */
  2303. public static function getDivForSliderEffect($id = '', $message = '', $overrideDefault = null)
  2304. {
  2305. return Template::get('div_for_slider_effect')->render([
  2306. 'id' => $id,
  2307. 'initial_sliders_state' => ($overrideDefault != null) ? $overrideDefault : $GLOBALS['cfg']['InitialSlidersState'],
  2308. 'message' => $message,
  2309. ]);
  2310. }
  2311. /**
  2312. * Creates an AJAX sliding toggle button
  2313. * (or and equivalent form when AJAX is disabled)
  2314. *
  2315. * @param string $action The URL for the request to be executed
  2316. * @param string $select_name The name for the dropdown box
  2317. * @param array $options An array of options (see PhpMyAdmin\Rte\Footer)
  2318. * @param string $callback A JS snippet to execute when the request is
  2319. * successfully processed
  2320. *
  2321. * @return string HTML code for the toggle button
  2322. */
  2323. public static function toggleButton($action, $select_name, array $options, $callback)
  2324. {
  2325. // Do the logic first
  2326. $link = "$action&amp;" . urlencode($select_name) . "=";
  2327. $link_on = $link . urlencode($options[1]['value']);
  2328. $link_off = $link . urlencode($options[0]['value']);
  2329. if ($options[1]['selected'] == true) {
  2330. $state = 'on';
  2331. } elseif ($options[0]['selected'] == true) {
  2332. $state = 'off';
  2333. } else {
  2334. $state = 'on';
  2335. }
  2336. return Template::get('toggle_button')->render(
  2337. [
  2338. 'pma_theme_image' => $GLOBALS['pmaThemeImage'],
  2339. 'text_dir' => $GLOBALS['text_dir'],
  2340. 'link_on' => $link_on,
  2341. 'link_off' => $link_off,
  2342. 'toggle_on' => $options[1]['label'],
  2343. 'toggle_off' => $options[0]['label'],
  2344. 'callback' => $callback,
  2345. 'state' => $state
  2346. ]);
  2347. } // end toggleButton()
  2348. /**
  2349. * Clears cache content which needs to be refreshed on user change.
  2350. *
  2351. * @return void
  2352. */
  2353. public static function clearUserCache()
  2354. {
  2355. self::cacheUnset('is_superuser');
  2356. self::cacheUnset('is_createuser');
  2357. self::cacheUnset('is_grantuser');
  2358. }
  2359. /**
  2360. * Calculates session cache key
  2361. *
  2362. * @return string
  2363. */
  2364. public static function cacheKey()
  2365. {
  2366. if (isset($GLOBALS['cfg']['Server']['user'])) {
  2367. return 'server_' . $GLOBALS['server'] . '_' . $GLOBALS['cfg']['Server']['user'];
  2368. }
  2369. return 'server_' . $GLOBALS['server'];
  2370. }
  2371. /**
  2372. * Verifies if something is cached in the session
  2373. *
  2374. * @param string $var variable name
  2375. *
  2376. * @return boolean
  2377. */
  2378. public static function cacheExists($var)
  2379. {
  2380. return isset($_SESSION['cache'][self::cacheKey()][$var]);
  2381. }
  2382. /**
  2383. * Gets cached information from the session
  2384. *
  2385. * @param string $var variable name
  2386. * @param \Closure $callback callback to fetch the value
  2387. *
  2388. * @return mixed
  2389. */
  2390. public static function cacheGet($var, $callback = null)
  2391. {
  2392. if (self::cacheExists($var)) {
  2393. return $_SESSION['cache'][self::cacheKey()][$var];
  2394. }
  2395. if ($callback) {
  2396. $val = $callback();
  2397. self::cacheSet($var, $val);
  2398. return $val;
  2399. }
  2400. return null;
  2401. }
  2402. /**
  2403. * Caches information in the session
  2404. *
  2405. * @param string $var variable name
  2406. * @param mixed $val value
  2407. *
  2408. * @return mixed
  2409. */
  2410. public static function cacheSet($var, $val = null)
  2411. {
  2412. $_SESSION['cache'][self::cacheKey()][$var] = $val;
  2413. }
  2414. /**
  2415. * Removes cached information from the session
  2416. *
  2417. * @param string $var variable name
  2418. *
  2419. * @return void
  2420. */
  2421. public static function cacheUnset($var)
  2422. {
  2423. unset($_SESSION['cache'][self::cacheKey()][$var]);
  2424. }
  2425. /**
  2426. * Converts a bit value to printable format;
  2427. * in MySQL a BIT field can be from 1 to 64 bits so we need this
  2428. * function because in PHP, decbin() supports only 32 bits
  2429. * on 32-bit servers
  2430. *
  2431. * @param integer $value coming from a BIT field
  2432. * @param integer $length length
  2433. *
  2434. * @return string the printable value
  2435. */
  2436. public static function printableBitValue($value, $length)
  2437. {
  2438. // if running on a 64-bit server or the length is safe for decbin()
  2439. if (PHP_INT_SIZE == 8 || $length < 33) {
  2440. $printable = decbin($value);
  2441. } else {
  2442. // FIXME: does not work for the leftmost bit of a 64-bit value
  2443. $i = 0;
  2444. $printable = '';
  2445. while ($value >= pow(2, $i)) {
  2446. ++$i;
  2447. }
  2448. if ($i != 0) {
  2449. --$i;
  2450. }
  2451. while ($i >= 0) {
  2452. if ($value - pow(2, $i) < 0) {
  2453. $printable = '0' . $printable;
  2454. } else {
  2455. $printable = '1' . $printable;
  2456. $value = $value - pow(2, $i);
  2457. }
  2458. --$i;
  2459. }
  2460. $printable = strrev($printable);
  2461. }
  2462. $printable = str_pad($printable, $length, '0', STR_PAD_LEFT);
  2463. return $printable;
  2464. }
  2465. /**
  2466. * Verifies whether the value contains a non-printable character
  2467. *
  2468. * @param string $value value
  2469. *
  2470. * @return integer
  2471. */
  2472. public static function containsNonPrintableAscii($value)
  2473. {
  2474. return preg_match('@[^[:print:]]@', $value);
  2475. }
  2476. /**
  2477. * Converts a BIT type default value
  2478. * for example, b'010' becomes 010
  2479. *
  2480. * @param string $bit_default_value value
  2481. *
  2482. * @return string the converted value
  2483. */
  2484. public static function convertBitDefaultValue($bit_default_value)
  2485. {
  2486. return rtrim(ltrim($bit_default_value, "b'"), "'");
  2487. }
  2488. /**
  2489. * Extracts the various parts from a column spec
  2490. *
  2491. * @param string $columnspec Column specification
  2492. *
  2493. * @return array associative array containing type, spec_in_brackets
  2494. * and possibly enum_set_values (another array)
  2495. */
  2496. public static function extractColumnSpec($columnspec)
  2497. {
  2498. $first_bracket_pos = mb_strpos($columnspec, '(');
  2499. if ($first_bracket_pos) {
  2500. $spec_in_brackets = chop(
  2501. mb_substr(
  2502. $columnspec,
  2503. $first_bracket_pos + 1,
  2504. mb_strrpos($columnspec, ')') - $first_bracket_pos - 1
  2505. )
  2506. );
  2507. // convert to lowercase just to be sure
  2508. $type = mb_strtolower(
  2509. chop(mb_substr($columnspec, 0, $first_bracket_pos))
  2510. );
  2511. } else {
  2512. // Split trailing attributes such as unsigned,
  2513. // binary, zerofill and get data type name
  2514. $type_parts = explode(' ', $columnspec);
  2515. $type = mb_strtolower($type_parts[0]);
  2516. $spec_in_brackets = '';
  2517. }
  2518. if ('enum' == $type || 'set' == $type) {
  2519. // Define our working vars
  2520. $enum_set_values = self::parseEnumSetValues($columnspec, false);
  2521. $printtype = $type
  2522. . '(' . str_replace("','", "', '", $spec_in_brackets) . ')';
  2523. $binary = false;
  2524. $unsigned = false;
  2525. $zerofill = false;
  2526. } else {
  2527. $enum_set_values = array();
  2528. /* Create printable type name */
  2529. $printtype = mb_strtolower($columnspec);
  2530. // Strip the "BINARY" attribute, except if we find "BINARY(" because
  2531. // this would be a BINARY or VARBINARY column type;
  2532. // by the way, a BLOB should not show the BINARY attribute
  2533. // because this is not accepted in MySQL syntax.
  2534. if (preg_match('@binary@', $printtype)
  2535. && ! preg_match('@binary[\(]@', $printtype)
  2536. ) {
  2537. $printtype = preg_replace('@binary@', '', $printtype);
  2538. $binary = true;
  2539. } else {
  2540. $binary = false;
  2541. }
  2542. $printtype = preg_replace(
  2543. '@zerofill@', '', $printtype, -1, $zerofill_cnt
  2544. );
  2545. $zerofill = ($zerofill_cnt > 0);
  2546. $printtype = preg_replace(
  2547. '@unsigned@', '', $printtype, -1, $unsigned_cnt
  2548. );
  2549. $unsigned = ($unsigned_cnt > 0);
  2550. $printtype = trim($printtype);
  2551. }
  2552. $attribute = ' ';
  2553. if ($binary) {
  2554. $attribute = 'BINARY';
  2555. }
  2556. if ($unsigned) {
  2557. $attribute = 'UNSIGNED';
  2558. }
  2559. if ($zerofill) {
  2560. $attribute = 'UNSIGNED ZEROFILL';
  2561. }
  2562. $can_contain_collation = false;
  2563. if (! $binary
  2564. && preg_match(
  2565. "@^(char|varchar|text|tinytext|mediumtext|longtext|set|enum)@", $type
  2566. )
  2567. ) {
  2568. $can_contain_collation = true;
  2569. }
  2570. // for the case ENUM('&#8211;','&ldquo;')
  2571. $displayed_type = htmlspecialchars($printtype);
  2572. if (mb_strlen($printtype) > $GLOBALS['cfg']['LimitChars']) {
  2573. $displayed_type = '<abbr title="' . htmlspecialchars($printtype) . '">';
  2574. $displayed_type .= htmlspecialchars(
  2575. mb_substr(
  2576. $printtype, 0, $GLOBALS['cfg']['LimitChars']
  2577. ) . '...'
  2578. );
  2579. $displayed_type .= '</abbr>';
  2580. }
  2581. return array(
  2582. 'type' => $type,
  2583. 'spec_in_brackets' => $spec_in_brackets,
  2584. 'enum_set_values' => $enum_set_values,
  2585. 'print_type' => $printtype,
  2586. 'binary' => $binary,
  2587. 'unsigned' => $unsigned,
  2588. 'zerofill' => $zerofill,
  2589. 'attribute' => $attribute,
  2590. 'can_contain_collation' => $can_contain_collation,
  2591. 'displayed_type' => $displayed_type
  2592. );
  2593. }
  2594. /**
  2595. * Verifies if this table's engine supports foreign keys
  2596. *
  2597. * @param string $engine engine
  2598. *
  2599. * @return boolean
  2600. */
  2601. public static function isForeignKeySupported($engine)
  2602. {
  2603. $engine = strtoupper($engine);
  2604. if (($engine == 'INNODB') || ($engine == 'PBXT')) {
  2605. return true;
  2606. } elseif ($engine == 'NDBCLUSTER' || $engine == 'NDB') {
  2607. $ndbver = strtolower(
  2608. $GLOBALS['dbi']->fetchValue("SELECT @@ndb_version_string")
  2609. );
  2610. if (substr($ndbver, 0, 4) == 'ndb-') {
  2611. $ndbver = substr($ndbver, 4);
  2612. }
  2613. return version_compare($ndbver, 7.3, '>=');
  2614. }
  2615. return false;
  2616. }
  2617. /**
  2618. * Is Foreign key check enabled?
  2619. *
  2620. * @return bool
  2621. */
  2622. public static function isForeignKeyCheck()
  2623. {
  2624. if ($GLOBALS['cfg']['DefaultForeignKeyChecks'] === 'enable') {
  2625. return true;
  2626. } elseif ($GLOBALS['cfg']['DefaultForeignKeyChecks'] === 'disable') {
  2627. return false;
  2628. }
  2629. return ($GLOBALS['dbi']->getVariable('FOREIGN_KEY_CHECKS') == 'ON');
  2630. }
  2631. /**
  2632. * Get HTML for Foreign key check checkbox
  2633. *
  2634. * @return string HTML for checkbox
  2635. */
  2636. public static function getFKCheckbox()
  2637. {
  2638. return Template::get('fk_checkbox')->render([
  2639. 'checked' => self::isForeignKeyCheck(),
  2640. ]);
  2641. }
  2642. /**
  2643. * Handle foreign key check request
  2644. *
  2645. * @return bool Default foreign key checks value
  2646. */
  2647. public static function handleDisableFKCheckInit()
  2648. {
  2649. $default_fk_check_value
  2650. = $GLOBALS['dbi']->getVariable('FOREIGN_KEY_CHECKS') == 'ON';
  2651. if (isset($_REQUEST['fk_checks'])) {
  2652. if (empty($_REQUEST['fk_checks'])) {
  2653. // Disable foreign key checks
  2654. $GLOBALS['dbi']->setVariable('FOREIGN_KEY_CHECKS', 'OFF');
  2655. } else {
  2656. // Enable foreign key checks
  2657. $GLOBALS['dbi']->setVariable('FOREIGN_KEY_CHECKS', 'ON');
  2658. }
  2659. } // else do nothing, go with default
  2660. return $default_fk_check_value;
  2661. }
  2662. /**
  2663. * Cleanup changes done for foreign key check
  2664. *
  2665. * @param bool $default_fk_check_value original value for 'FOREIGN_KEY_CHECKS'
  2666. *
  2667. * @return void
  2668. */
  2669. public static function handleDisableFKCheckCleanup($default_fk_check_value)
  2670. {
  2671. $GLOBALS['dbi']->setVariable(
  2672. 'FOREIGN_KEY_CHECKS', $default_fk_check_value ? 'ON' : 'OFF'
  2673. );
  2674. }
  2675. /**
  2676. * Converts GIS data to Well Known Text format
  2677. *
  2678. * @param string $data GIS data
  2679. * @param bool $includeSRID Add SRID to the WKT
  2680. *
  2681. * @return string GIS data in Well Know Text format
  2682. */
  2683. public static function asWKT($data, $includeSRID = false)
  2684. {
  2685. // Convert to WKT format
  2686. $hex = bin2hex($data);
  2687. $wktsql = "SELECT ASTEXT(x'" . $hex . "')";
  2688. if ($includeSRID) {
  2689. $wktsql .= ", SRID(x'" . $hex . "')";
  2690. }
  2691. $wktresult = $GLOBALS['dbi']->tryQuery(
  2692. $wktsql
  2693. );
  2694. $wktarr = $GLOBALS['dbi']->fetchRow($wktresult, 0);
  2695. $wktval = $wktarr[0];
  2696. if ($includeSRID) {
  2697. $srid = $wktarr[1];
  2698. $wktval = "'" . $wktval . "'," . $srid;
  2699. }
  2700. @$GLOBALS['dbi']->freeResult($wktresult);
  2701. return $wktval;
  2702. }
  2703. /**
  2704. * If the string starts with a \r\n pair (0x0d0a) add an extra \n
  2705. *
  2706. * @param string $string string
  2707. *
  2708. * @return string with the chars replaced
  2709. */
  2710. public static function duplicateFirstNewline($string)
  2711. {
  2712. $first_occurence = mb_strpos($string, "\r\n");
  2713. if ($first_occurence === 0) {
  2714. $string = "\n" . $string;
  2715. }
  2716. return $string;
  2717. }
  2718. /**
  2719. * Get the action word corresponding to a script name
  2720. * in order to display it as a title in navigation panel
  2721. *
  2722. * @param string $target a valid value for $cfg['NavigationTreeDefaultTabTable'],
  2723. * $cfg['NavigationTreeDefaultTabTable2'],
  2724. * $cfg['DefaultTabTable'] or $cfg['DefaultTabDatabase']
  2725. *
  2726. * @return string Title for the $cfg value
  2727. */
  2728. public static function getTitleForTarget($target)
  2729. {
  2730. $mapping = array(
  2731. 'structure' => __('Structure'),
  2732. 'sql' => __('SQL'),
  2733. 'search' =>__('Search'),
  2734. 'insert' =>__('Insert'),
  2735. 'browse' => __('Browse'),
  2736. 'operations' => __('Operations'),
  2737. // For backward compatiblity
  2738. // Values for $cfg['DefaultTabTable']
  2739. 'tbl_structure.php' => __('Structure'),
  2740. 'tbl_sql.php' => __('SQL'),
  2741. 'tbl_select.php' =>__('Search'),
  2742. 'tbl_change.php' =>__('Insert'),
  2743. 'sql.php' => __('Browse'),
  2744. // Values for $cfg['DefaultTabDatabase']
  2745. 'db_structure.php' => __('Structure'),
  2746. 'db_sql.php' => __('SQL'),
  2747. 'db_search.php' => __('Search'),
  2748. 'db_operations.php' => __('Operations'),
  2749. );
  2750. return isset($mapping[$target]) ? $mapping[$target] : false;
  2751. }
  2752. /**
  2753. * Get the script name corresponding to a plain English config word
  2754. * in order to append in links on navigation and main panel
  2755. *
  2756. * @param string $target a valid value for
  2757. * $cfg['NavigationTreeDefaultTabTable'],
  2758. * $cfg['NavigationTreeDefaultTabTable2'],
  2759. * $cfg['DefaultTabTable'], $cfg['DefaultTabDatabase'] or
  2760. * $cfg['DefaultTabServer']
  2761. * @param string $location one out of 'server', 'table', 'database'
  2762. *
  2763. * @return string script name corresponding to the config word
  2764. */
  2765. public static function getScriptNameForOption($target, $location)
  2766. {
  2767. if ($location == 'server') {
  2768. // Values for $cfg['DefaultTabServer']
  2769. switch ($target) {
  2770. case 'welcome':
  2771. return 'index.php';
  2772. case 'databases':
  2773. return 'server_databases.php';
  2774. case 'status':
  2775. return 'server_status.php';
  2776. case 'variables':
  2777. return 'server_variables.php';
  2778. case 'privileges':
  2779. return 'server_privileges.php';
  2780. }
  2781. } elseif ($location == 'database') {
  2782. // Values for $cfg['DefaultTabDatabase']
  2783. switch ($target) {
  2784. case 'structure':
  2785. return 'db_structure.php';
  2786. case 'sql':
  2787. return 'db_sql.php';
  2788. case 'search':
  2789. return 'db_search.php';
  2790. case 'operations':
  2791. return 'db_operations.php';
  2792. }
  2793. } elseif ($location == 'table') {
  2794. // Values for $cfg['DefaultTabTable'],
  2795. // $cfg['NavigationTreeDefaultTabTable'] and
  2796. // $cfg['NavigationTreeDefaultTabTable2']
  2797. switch ($target) {
  2798. case 'structure':
  2799. return 'tbl_structure.php';
  2800. case 'sql':
  2801. return 'tbl_sql.php';
  2802. case 'search':
  2803. return 'tbl_select.php';
  2804. case 'insert':
  2805. return 'tbl_change.php';
  2806. case 'browse':
  2807. return 'sql.php';
  2808. }
  2809. }
  2810. return $target;
  2811. }
  2812. /**
  2813. * Formats user string, expanding @VARIABLES@, accepting strftime format
  2814. * string.
  2815. *
  2816. * @param string $string Text where to do expansion.
  2817. * @param array|string $escape Function to call for escaping variable values.
  2818. * Can also be an array of:
  2819. * - the escape method name
  2820. * - the class that contains the method
  2821. * - location of the class (for inclusion)
  2822. * @param array $updates Array with overrides for default parameters
  2823. * (obtained from GLOBALS).
  2824. *
  2825. * @return string
  2826. */
  2827. public static function expandUserString(
  2828. $string, $escape = null, array $updates = array()
  2829. ) {
  2830. /* Content */
  2831. $vars = array();
  2832. $vars['http_host'] = Core::getenv('HTTP_HOST');
  2833. $vars['server_name'] = $GLOBALS['cfg']['Server']['host'];
  2834. $vars['server_verbose'] = $GLOBALS['cfg']['Server']['verbose'];
  2835. if (empty($GLOBALS['cfg']['Server']['verbose'])) {
  2836. $vars['server_verbose_or_name'] = $GLOBALS['cfg']['Server']['host'];
  2837. } else {
  2838. $vars['server_verbose_or_name'] = $GLOBALS['cfg']['Server']['verbose'];
  2839. }
  2840. $vars['database'] = $GLOBALS['db'];
  2841. $vars['table'] = $GLOBALS['table'];
  2842. $vars['phpmyadmin_version'] = 'phpMyAdmin ' . PMA_VERSION;
  2843. /* Update forced variables */
  2844. foreach ($updates as $key => $val) {
  2845. $vars[$key] = $val;
  2846. }
  2847. /* Replacement mapping */
  2848. /*
  2849. * The __VAR__ ones are for backward compatibility, because user
  2850. * might still have it in cookies.
  2851. */
  2852. $replace = array(
  2853. '@HTTP_HOST@' => $vars['http_host'],
  2854. '@SERVER@' => $vars['server_name'],
  2855. '__SERVER__' => $vars['server_name'],
  2856. '@VERBOSE@' => $vars['server_verbose'],
  2857. '@VSERVER@' => $vars['server_verbose_or_name'],
  2858. '@DATABASE@' => $vars['database'],
  2859. '__DB__' => $vars['database'],
  2860. '@TABLE@' => $vars['table'],
  2861. '__TABLE__' => $vars['table'],
  2862. '@PHPMYADMIN@' => $vars['phpmyadmin_version'],
  2863. );
  2864. /* Optional escaping */
  2865. if (! is_null($escape)) {
  2866. if (is_array($escape)) {
  2867. $escape_class = new $escape[1];
  2868. $escape_method = $escape[0];
  2869. }
  2870. foreach ($replace as $key => $val) {
  2871. if (is_array($escape)) {
  2872. $replace[$key] = $escape_class->$escape_method($val);
  2873. } else {
  2874. $replace[$key] = ($escape == 'backquote')
  2875. ? self::$escape($val)
  2876. : $escape($val);
  2877. }
  2878. }
  2879. }
  2880. /* Backward compatibility in 3.5.x */
  2881. if (mb_strpos($string, '@FIELDS@') !== false) {
  2882. $string = strtr($string, array('@FIELDS@' => '@COLUMNS@'));
  2883. }
  2884. /* Fetch columns list if required */
  2885. if (mb_strpos($string, '@COLUMNS@') !== false) {
  2886. $columns_list = $GLOBALS['dbi']->getColumns(
  2887. $GLOBALS['db'], $GLOBALS['table']
  2888. );
  2889. // sometimes the table no longer exists at this point
  2890. if (! is_null($columns_list)) {
  2891. $column_names = array();
  2892. foreach ($columns_list as $column) {
  2893. if (! is_null($escape)) {
  2894. $column_names[] = self::$escape($column['Field']);
  2895. } else {
  2896. $column_names[] = $column['Field'];
  2897. }
  2898. }
  2899. $replace['@COLUMNS@'] = implode(',', $column_names);
  2900. } else {
  2901. $replace['@COLUMNS@'] = '*';
  2902. }
  2903. }
  2904. /* Do the replacement */
  2905. return strtr(strftime($string), $replace);
  2906. }
  2907. /**
  2908. * Prepare the form used to browse anywhere on the local server for a file to
  2909. * import
  2910. *
  2911. * @param string $max_upload_size maximum upload size
  2912. *
  2913. * @return String
  2914. */
  2915. public static function getBrowseUploadFileBlock($max_upload_size)
  2916. {
  2917. $block_html = '';
  2918. if ($GLOBALS['is_upload'] && ! empty($GLOBALS['cfg']['UploadDir'])) {
  2919. $block_html .= '<label for="radio_import_file">';
  2920. } else {
  2921. $block_html .= '<label for="input_import_file">';
  2922. }
  2923. $block_html .= __("Browse your computer:") . '</label>'
  2924. . '<div id="upload_form_status" class="hide"></div>'
  2925. . '<div id="upload_form_status_info" class="hide"></div>'
  2926. . '<input type="file" name="import_file" id="input_import_file" />'
  2927. . self::getFormattedMaximumUploadSize($max_upload_size) . "\n"
  2928. // some browsers should respect this :)
  2929. . self::generateHiddenMaxFileSize($max_upload_size) . "\n";
  2930. return $block_html;
  2931. }
  2932. /**
  2933. * Prepare the form used to select a file to import from the server upload
  2934. * directory
  2935. *
  2936. * @param ImportPlugin[] $import_list array of import plugins
  2937. * @param string $uploaddir upload directory
  2938. *
  2939. * @return String
  2940. */
  2941. public static function getSelectUploadFileBlock($import_list, $uploaddir)
  2942. {
  2943. $block_html = '';
  2944. $block_html .= '<label for="radio_local_import_file">'
  2945. . sprintf(
  2946. __("Select from the web server upload directory <b>%s</b>:"),
  2947. htmlspecialchars(self::userDir($uploaddir))
  2948. )
  2949. . '</label>';
  2950. $extensions = '';
  2951. foreach ($import_list as $import_plugin) {
  2952. if (! empty($extensions)) {
  2953. $extensions .= '|';
  2954. }
  2955. $extensions .= $import_plugin->getProperties()->getExtension();
  2956. }
  2957. $matcher = '@\.(' . $extensions . ')(\.('
  2958. . FileListing::supportedDecompressions() . '))?$@';
  2959. $active = (isset($GLOBALS['timeout_passed']) && $GLOBALS['timeout_passed']
  2960. && isset($GLOBALS['local_import_file']))
  2961. ? $GLOBALS['local_import_file']
  2962. : '';
  2963. $files = FileListing::getFileSelectOptions(
  2964. self::userDir($uploaddir),
  2965. $matcher,
  2966. $active
  2967. );
  2968. if ($files === false) {
  2969. Message::error(
  2970. __('The directory you set for upload work cannot be reached.')
  2971. )->display();
  2972. } elseif (! empty($files)) {
  2973. $block_html .= "\n"
  2974. . ' <select style="margin: 5px" size="1" '
  2975. . 'name="local_import_file" '
  2976. . 'id="select_local_import_file">' . "\n"
  2977. . ' <option value="">&nbsp;</option>' . "\n"
  2978. . $files
  2979. . ' </select>' . "\n";
  2980. } elseif (empty($files)) {
  2981. $block_html .= '<i>' . __('There are no files to upload!') . '</i>';
  2982. }
  2983. return $block_html;
  2984. }
  2985. /**
  2986. * Build titles and icons for action links
  2987. *
  2988. * @return array the action titles
  2989. */
  2990. public static function buildActionTitles()
  2991. {
  2992. $titles = array();
  2993. $titles['Browse'] = self::getIcon('b_browse', __('Browse'));
  2994. $titles['NoBrowse'] = self::getIcon('bd_browse', __('Browse'));
  2995. $titles['Search'] = self::getIcon('b_select', __('Search'));
  2996. $titles['NoSearch'] = self::getIcon('bd_select', __('Search'));
  2997. $titles['Insert'] = self::getIcon('b_insrow', __('Insert'));
  2998. $titles['NoInsert'] = self::getIcon('bd_insrow', __('Insert'));
  2999. $titles['Structure'] = self::getIcon('b_props', __('Structure'));
  3000. $titles['Drop'] = self::getIcon('b_drop', __('Drop'));
  3001. $titles['NoDrop'] = self::getIcon('bd_drop', __('Drop'));
  3002. $titles['Empty'] = self::getIcon('b_empty', __('Empty'));
  3003. $titles['NoEmpty'] = self::getIcon('bd_empty', __('Empty'));
  3004. $titles['Edit'] = self::getIcon('b_edit', __('Edit'));
  3005. $titles['NoEdit'] = self::getIcon('bd_edit', __('Edit'));
  3006. $titles['Export'] = self::getIcon('b_export', __('Export'));
  3007. $titles['NoExport'] = self::getIcon('bd_export', __('Export'));
  3008. $titles['Execute'] = self::getIcon('b_nextpage', __('Execute'));
  3009. $titles['NoExecute'] = self::getIcon('bd_nextpage', __('Execute'));
  3010. // For Favorite/NoFavorite, we need icon only.
  3011. $titles['Favorite'] = self::getIcon('b_favorite', '');
  3012. $titles['NoFavorite']= self::getIcon('b_no_favorite', '');
  3013. return $titles;
  3014. }
  3015. /**
  3016. * This function processes the datatypes supported by the DB,
  3017. * as specified in Types->getColumns() and either returns an array
  3018. * (useful for quickly checking if a datatype is supported)
  3019. * or an HTML snippet that creates a drop-down list.
  3020. *
  3021. * @param bool $html Whether to generate an html snippet or an array
  3022. * @param string $selected The value to mark as selected in HTML mode
  3023. *
  3024. * @return mixed An HTML snippet or an array of datatypes.
  3025. *
  3026. */
  3027. public static function getSupportedDatatypes($html = false, $selected = '')
  3028. {
  3029. if ($html) {
  3030. // NOTE: the SELECT tag in not included in this snippet.
  3031. $retval = '';
  3032. foreach ($GLOBALS['dbi']->types->getColumns() as $key => $value) {
  3033. if (is_array($value)) {
  3034. $retval .= "<optgroup label='" . htmlspecialchars($key) . "'>";
  3035. foreach ($value as $subvalue) {
  3036. if ($subvalue == $selected) {
  3037. $retval .= sprintf(
  3038. '<option selected="selected" title="%s">%s</option>',
  3039. $GLOBALS['dbi']->types->getTypeDescription($subvalue),
  3040. $subvalue
  3041. );
  3042. } elseif ($subvalue === '-') {
  3043. $retval .= '<option disabled="disabled">';
  3044. $retval .= $subvalue;
  3045. $retval .= '</option>';
  3046. } else {
  3047. $retval .= sprintf(
  3048. '<option title="%s">%s</option>',
  3049. $GLOBALS['dbi']->types->getTypeDescription($subvalue),
  3050. $subvalue
  3051. );
  3052. }
  3053. }
  3054. $retval .= '</optgroup>';
  3055. } else {
  3056. if ($selected == $value) {
  3057. $retval .= sprintf(
  3058. '<option selected="selected" title="%s">%s</option>',
  3059. $GLOBALS['dbi']->types->getTypeDescription($value),
  3060. $value
  3061. );
  3062. } else {
  3063. $retval .= sprintf(
  3064. '<option title="%s">%s</option>',
  3065. $GLOBALS['dbi']->types->getTypeDescription($value),
  3066. $value
  3067. );
  3068. }
  3069. }
  3070. }
  3071. } else {
  3072. $retval = array();
  3073. foreach ($GLOBALS['dbi']->types->getColumns() as $value) {
  3074. if (is_array($value)) {
  3075. foreach ($value as $subvalue) {
  3076. if ($subvalue !== '-') {
  3077. $retval[] = $subvalue;
  3078. }
  3079. }
  3080. } else {
  3081. if ($value !== '-') {
  3082. $retval[] = $value;
  3083. }
  3084. }
  3085. }
  3086. }
  3087. return $retval;
  3088. } // end getSupportedDatatypes()
  3089. /**
  3090. * Returns a list of datatypes that are not (yet) handled by PMA.
  3091. * Used by: tbl_change.php and libraries/db_routines.inc.php
  3092. *
  3093. * @return array list of datatypes
  3094. */
  3095. public static function unsupportedDatatypes()
  3096. {
  3097. $no_support_types = array();
  3098. return $no_support_types;
  3099. }
  3100. /**
  3101. * Return GIS data types
  3102. *
  3103. * @param bool $upper_case whether to return values in upper case
  3104. *
  3105. * @return string[] GIS data types
  3106. */
  3107. public static function getGISDatatypes($upper_case = false)
  3108. {
  3109. $gis_data_types = array(
  3110. 'geometry',
  3111. 'point',
  3112. 'linestring',
  3113. 'polygon',
  3114. 'multipoint',
  3115. 'multilinestring',
  3116. 'multipolygon',
  3117. 'geometrycollection'
  3118. );
  3119. if ($upper_case) {
  3120. for ($i = 0, $nb = count($gis_data_types); $i < $nb; $i++) {
  3121. $gis_data_types[$i]
  3122. = mb_strtoupper($gis_data_types[$i]);
  3123. }
  3124. }
  3125. return $gis_data_types;
  3126. }
  3127. /**
  3128. * Generates GIS data based on the string passed.
  3129. *
  3130. * @param string $gis_string GIS string
  3131. *
  3132. * @return string GIS data enclosed in 'GeomFromText' function
  3133. */
  3134. public static function createGISData($gis_string)
  3135. {
  3136. $gis_string = trim($gis_string);
  3137. $geom_types = '(POINT|MULTIPOINT|LINESTRING|MULTILINESTRING|'
  3138. . 'POLYGON|MULTIPOLYGON|GEOMETRYCOLLECTION)';
  3139. if (preg_match("/^'" . $geom_types . "\(.*\)',[0-9]*$/i", $gis_string)) {
  3140. return 'GeomFromText(' . $gis_string . ')';
  3141. } elseif (preg_match("/^" . $geom_types . "\(.*\)$/i", $gis_string)) {
  3142. return "GeomFromText('" . $gis_string . "')";
  3143. }
  3144. return $gis_string;
  3145. }
  3146. /**
  3147. * Returns the names and details of the functions
  3148. * that can be applied on geometry data types.
  3149. *
  3150. * @param string $geom_type if provided the output is limited to the functions
  3151. * that are applicable to the provided geometry type.
  3152. * @param bool $binary if set to false functions that take two geometries
  3153. * as arguments will not be included.
  3154. * @param bool $display if set to true separators will be added to the
  3155. * output array.
  3156. *
  3157. * @return array names and details of the functions that can be applied on
  3158. * geometry data types.
  3159. */
  3160. public static function getGISFunctions(
  3161. $geom_type = null, $binary = true, $display = false
  3162. ) {
  3163. $funcs = array();
  3164. if ($display) {
  3165. $funcs[] = array('display' => ' ');
  3166. }
  3167. // Unary functions common to all geometry types
  3168. $funcs['Dimension'] = array('params' => 1, 'type' => 'int');
  3169. $funcs['Envelope'] = array('params' => 1, 'type' => 'Polygon');
  3170. $funcs['GeometryType'] = array('params' => 1, 'type' => 'text');
  3171. $funcs['SRID'] = array('params' => 1, 'type' => 'int');
  3172. $funcs['IsEmpty'] = array('params' => 1, 'type' => 'int');
  3173. $funcs['IsSimple'] = array('params' => 1, 'type' => 'int');
  3174. $geom_type = trim(mb_strtolower($geom_type));
  3175. if ($display && $geom_type != 'geometry' && $geom_type != 'multipoint') {
  3176. $funcs[] = array('display' => '--------');
  3177. }
  3178. // Unary functions that are specific to each geometry type
  3179. if ($geom_type == 'point') {
  3180. $funcs['X'] = array('params' => 1, 'type' => 'float');
  3181. $funcs['Y'] = array('params' => 1, 'type' => 'float');
  3182. } elseif ($geom_type == 'multipoint') {
  3183. // no functions here
  3184. } elseif ($geom_type == 'linestring') {
  3185. $funcs['EndPoint'] = array('params' => 1, 'type' => 'point');
  3186. $funcs['GLength'] = array('params' => 1, 'type' => 'float');
  3187. $funcs['NumPoints'] = array('params' => 1, 'type' => 'int');
  3188. $funcs['StartPoint'] = array('params' => 1, 'type' => 'point');
  3189. $funcs['IsRing'] = array('params' => 1, 'type' => 'int');
  3190. } elseif ($geom_type == 'multilinestring') {
  3191. $funcs['GLength'] = array('params' => 1, 'type' => 'float');
  3192. $funcs['IsClosed'] = array('params' => 1, 'type' => 'int');
  3193. } elseif ($geom_type == 'polygon') {
  3194. $funcs['Area'] = array('params' => 1, 'type' => 'float');
  3195. $funcs['ExteriorRing'] = array('params' => 1, 'type' => 'linestring');
  3196. $funcs['NumInteriorRings'] = array('params' => 1, 'type' => 'int');
  3197. } elseif ($geom_type == 'multipolygon') {
  3198. $funcs['Area'] = array('params' => 1, 'type' => 'float');
  3199. $funcs['Centroid'] = array('params' => 1, 'type' => 'point');
  3200. // Not yet implemented in MySQL
  3201. //$funcs['PointOnSurface'] = array('params' => 1, 'type' => 'point');
  3202. } elseif ($geom_type == 'geometrycollection') {
  3203. $funcs['NumGeometries'] = array('params' => 1, 'type' => 'int');
  3204. }
  3205. // If we are asked for binary functions as well
  3206. if ($binary) {
  3207. // section separator
  3208. if ($display) {
  3209. $funcs[] = array('display' => '--------');
  3210. }
  3211. if ($GLOBALS['dbi']->getVersion() < 50601) {
  3212. $funcs['Crosses'] = array('params' => 2, 'type' => 'int');
  3213. $funcs['Contains'] = array('params' => 2, 'type' => 'int');
  3214. $funcs['Disjoint'] = array('params' => 2, 'type' => 'int');
  3215. $funcs['Equals'] = array('params' => 2, 'type' => 'int');
  3216. $funcs['Intersects'] = array('params' => 2, 'type' => 'int');
  3217. $funcs['Overlaps'] = array('params' => 2, 'type' => 'int');
  3218. $funcs['Touches'] = array('params' => 2, 'type' => 'int');
  3219. $funcs['Within'] = array('params' => 2, 'type' => 'int');
  3220. } else {
  3221. // If MySQl version is greater than or equal 5.6.1,
  3222. // use the ST_ prefix.
  3223. $funcs['ST_Crosses'] = array('params' => 2, 'type' => 'int');
  3224. $funcs['ST_Contains'] = array('params' => 2, 'type' => 'int');
  3225. $funcs['ST_Disjoint'] = array('params' => 2, 'type' => 'int');
  3226. $funcs['ST_Equals'] = array('params' => 2, 'type' => 'int');
  3227. $funcs['ST_Intersects'] = array('params' => 2, 'type' => 'int');
  3228. $funcs['ST_Overlaps'] = array('params' => 2, 'type' => 'int');
  3229. $funcs['ST_Touches'] = array('params' => 2, 'type' => 'int');
  3230. $funcs['ST_Within'] = array('params' => 2, 'type' => 'int');
  3231. }
  3232. if ($display) {
  3233. $funcs[] = array('display' => '--------');
  3234. }
  3235. // Minimum bounding rectangle functions
  3236. $funcs['MBRContains'] = array('params' => 2, 'type' => 'int');
  3237. $funcs['MBRDisjoint'] = array('params' => 2, 'type' => 'int');
  3238. $funcs['MBREquals'] = array('params' => 2, 'type' => 'int');
  3239. $funcs['MBRIntersects'] = array('params' => 2, 'type' => 'int');
  3240. $funcs['MBROverlaps'] = array('params' => 2, 'type' => 'int');
  3241. $funcs['MBRTouches'] = array('params' => 2, 'type' => 'int');
  3242. $funcs['MBRWithin'] = array('params' => 2, 'type' => 'int');
  3243. }
  3244. return $funcs;
  3245. }
  3246. /**
  3247. * Returns default function for a particular column.
  3248. *
  3249. * @param array $field Data about the column for which
  3250. * to generate the dropdown
  3251. * @param bool $insert_mode Whether the operation is 'insert'
  3252. *
  3253. * @global array $cfg PMA configuration
  3254. * @global mixed $data data of currently edited row
  3255. * (used to detect whether to choose defaults)
  3256. *
  3257. * @return string An HTML snippet of a dropdown list with function
  3258. * names appropriate for the requested column.
  3259. */
  3260. public static function getDefaultFunctionForField(array $field, $insert_mode)
  3261. {
  3262. /*
  3263. * @todo Except for $cfg, no longer use globals but pass as parameters
  3264. * from higher levels
  3265. */
  3266. global $cfg, $data;
  3267. $default_function = '';
  3268. // Can we get field class based values?
  3269. $current_class = $GLOBALS['dbi']->types->getTypeClass($field['True_Type']);
  3270. if (! empty($current_class)) {
  3271. if (isset($cfg['DefaultFunctions']['FUNC_' . $current_class])) {
  3272. $default_function
  3273. = $cfg['DefaultFunctions']['FUNC_' . $current_class];
  3274. }
  3275. }
  3276. // what function defined as default?
  3277. // for the first timestamp we don't set the default function
  3278. // if there is a default value for the timestamp
  3279. // (not including CURRENT_TIMESTAMP)
  3280. // and the column does not have the
  3281. // ON UPDATE DEFAULT TIMESTAMP attribute.
  3282. if (($field['True_Type'] == 'timestamp')
  3283. && $field['first_timestamp']
  3284. && empty($field['Default'])
  3285. && empty($data)
  3286. && $field['Extra'] != 'on update CURRENT_TIMESTAMP'
  3287. && $field['Null'] == 'NO'
  3288. ) {
  3289. $default_function = $cfg['DefaultFunctions']['first_timestamp'];
  3290. }
  3291. // For primary keys of type char(36) or varchar(36) UUID if the default
  3292. // function
  3293. // Only applies to insert mode, as it would silently trash data on updates.
  3294. if ($insert_mode
  3295. && $field['Key'] == 'PRI'
  3296. && ($field['Type'] == 'char(36)' || $field['Type'] == 'varchar(36)')
  3297. ) {
  3298. $default_function = $cfg['DefaultFunctions']['FUNC_UUID'];
  3299. }
  3300. return $default_function;
  3301. }
  3302. /**
  3303. * Creates a dropdown box with MySQL functions for a particular column.
  3304. *
  3305. * @param array $field Data about the column for which
  3306. * to generate the dropdown
  3307. * @param bool $insert_mode Whether the operation is 'insert'
  3308. * @param array $foreignData Foreign data
  3309. *
  3310. * @return string An HTML snippet of a dropdown list with function
  3311. * names appropriate for the requested column.
  3312. */
  3313. public static function getFunctionsForField(array $field, $insert_mode, array $foreignData)
  3314. {
  3315. $default_function = self::getDefaultFunctionForField($field, $insert_mode);
  3316. $dropdown_built = array();
  3317. // Create the output
  3318. $retval = '<option></option>' . "\n";
  3319. // loop on the dropdown array and print all available options for that
  3320. // field.
  3321. $functions = $GLOBALS['dbi']->types->getFunctions($field['True_Type']);
  3322. foreach ($functions as $function) {
  3323. $retval .= '<option';
  3324. if (isset($foreignData['foreign_link']) && $foreignData['foreign_link'] !== false && $default_function === $function) {
  3325. $retval .= ' selected="selected"';
  3326. }
  3327. $retval .= '>' . $function . '</option>' . "\n";
  3328. $dropdown_built[$function] = true;
  3329. }
  3330. // Create separator before all functions list
  3331. if (count($functions) > 0) {
  3332. $retval .= '<option value="" disabled="disabled">--------</option>'
  3333. . "\n";
  3334. }
  3335. // For compatibility's sake, do not let out all other functions. Instead
  3336. // print a separator (blank) and then show ALL functions which weren't
  3337. // shown yet.
  3338. $functions = $GLOBALS['dbi']->types->getAllFunctions();
  3339. foreach ($functions as $function) {
  3340. // Skip already included functions
  3341. if (isset($dropdown_built[$function])) {
  3342. continue;
  3343. }
  3344. $retval .= '<option';
  3345. if ($default_function === $function) {
  3346. $retval .= ' selected="selected"';
  3347. }
  3348. $retval .= '>' . $function . '</option>' . "\n";
  3349. } // end for
  3350. return $retval;
  3351. } // end getFunctionsForField()
  3352. /**
  3353. * Checks if the current user has a specific privilege and returns true if the
  3354. * user indeed has that privilege or false if (s)he doesn't. This function must
  3355. * only be used for features that are available since MySQL 5, because it
  3356. * relies on the INFORMATION_SCHEMA database to be present.
  3357. *
  3358. * Example: currentUserHasPrivilege('CREATE ROUTINE', 'mydb');
  3359. * // Checks if the currently logged in user has the global
  3360. * // 'CREATE ROUTINE' privilege or, if not, checks if the
  3361. * // user has this privilege on database 'mydb'.
  3362. *
  3363. * @param string $priv The privilege to check
  3364. * @param mixed $db null, to only check global privileges
  3365. * string, db name where to also check for privileges
  3366. * @param mixed $tbl null, to only check global/db privileges
  3367. * string, table name where to also check for privileges
  3368. *
  3369. * @return bool
  3370. */
  3371. public static function currentUserHasPrivilege($priv, $db = null, $tbl = null)
  3372. {
  3373. // Get the username for the current user in the format
  3374. // required to use in the information schema database.
  3375. list($user, $host) = $GLOBALS['dbi']->getCurrentUserAndHost();
  3376. if ($user === '') { // MySQL is started with --skip-grant-tables
  3377. return true;
  3378. }
  3379. $username = "''";
  3380. $username .= str_replace("'", "''", $user);
  3381. $username .= "''@''";
  3382. $username .= str_replace("'", "''", $host);
  3383. $username .= "''";
  3384. // Prepare the query
  3385. $query = "SELECT `PRIVILEGE_TYPE` FROM `INFORMATION_SCHEMA`.`%s` "
  3386. . "WHERE GRANTEE='%s' AND PRIVILEGE_TYPE='%s'";
  3387. // Check global privileges first.
  3388. $user_privileges = $GLOBALS['dbi']->fetchValue(
  3389. sprintf(
  3390. $query,
  3391. 'USER_PRIVILEGES',
  3392. $username,
  3393. $priv
  3394. )
  3395. );
  3396. if ($user_privileges) {
  3397. return true;
  3398. }
  3399. // If a database name was provided and user does not have the
  3400. // required global privilege, try database-wise permissions.
  3401. if ($db !== null) {
  3402. $query .= " AND '%s' LIKE `TABLE_SCHEMA`";
  3403. $schema_privileges = $GLOBALS['dbi']->fetchValue(
  3404. sprintf(
  3405. $query,
  3406. 'SCHEMA_PRIVILEGES',
  3407. $username,
  3408. $priv,
  3409. $GLOBALS['dbi']->escapeString($db)
  3410. )
  3411. );
  3412. if ($schema_privileges) {
  3413. return true;
  3414. }
  3415. } else {
  3416. // There was no database name provided and the user
  3417. // does not have the correct global privilege.
  3418. return false;
  3419. }
  3420. // If a table name was also provided and we still didn't
  3421. // find any valid privileges, try table-wise privileges.
  3422. if ($tbl !== null) {
  3423. // need to escape wildcards in db and table names, see bug #3518484
  3424. $tbl = str_replace(array('%', '_'), array('\%', '\_'), $tbl);
  3425. $query .= " AND TABLE_NAME='%s'";
  3426. $table_privileges = $GLOBALS['dbi']->fetchValue(
  3427. sprintf(
  3428. $query,
  3429. 'TABLE_PRIVILEGES',
  3430. $username,
  3431. $priv,
  3432. $GLOBALS['dbi']->escapeString($db),
  3433. $GLOBALS['dbi']->escapeString($tbl)
  3434. )
  3435. );
  3436. if ($table_privileges) {
  3437. return true;
  3438. }
  3439. }
  3440. // If we reached this point, the user does not
  3441. // have even valid table-wise privileges.
  3442. return false;
  3443. }
  3444. /**
  3445. * Returns server type for current connection
  3446. *
  3447. * Known types are: MariaDB, Percona and MySQL (default)
  3448. *
  3449. * @return string
  3450. */
  3451. public static function getServerType()
  3452. {
  3453. if ($GLOBALS['dbi']->isMariaDB()) {
  3454. return 'MariaDB';
  3455. }
  3456. if ($GLOBALS['dbi']->isPercona()) {
  3457. return 'Percona Server';
  3458. }
  3459. return 'MySQL';
  3460. }
  3461. /**
  3462. * Returns information about SSL status for current connection
  3463. *
  3464. * @return string
  3465. */
  3466. public static function getServerSSL()
  3467. {
  3468. $server = $GLOBALS['cfg']['Server'];
  3469. $class = 'caution';
  3470. if (! $server['ssl']) {
  3471. $message = __('SSL is not being used');
  3472. if (! empty($server['socket']) || $server['host'] == '127.0.0.1' || $server['host'] == 'localhost') {
  3473. $class = '';
  3474. }
  3475. } elseif (! $server['ssl_verify']) {
  3476. $message = __('SSL is used with disabled verification');
  3477. } elseif (empty($server['ssl_ca']) && empty($server['ssl_ca'])) {
  3478. $message = __('SSL is used without certification authority');
  3479. } else {
  3480. $class = '';
  3481. $message = __('SSL is used');
  3482. }
  3483. return '<span class="' . $class . '">' . $message . '</span> ' . self::showDocu('setup', 'ssl');
  3484. }
  3485. /**
  3486. * Prepare HTML code for display button.
  3487. *
  3488. * @return String
  3489. */
  3490. public static function getButton()
  3491. {
  3492. return '<p class="print_ignore">'
  3493. . '<input type="button" class="button" id="print" value="'
  3494. . __('Print') . '" />'
  3495. . '</p>';
  3496. }
  3497. /**
  3498. * Parses ENUM/SET values
  3499. *
  3500. * @param string $definition The definition of the column
  3501. * for which to parse the values
  3502. * @param bool $escapeHtml Whether to escape html entities
  3503. *
  3504. * @return array
  3505. */
  3506. public static function parseEnumSetValues($definition, $escapeHtml = true)
  3507. {
  3508. $values_string = htmlentities($definition, ENT_COMPAT, "UTF-8");
  3509. // There is a JS port of the below parser in functions.js
  3510. // If you are fixing something here,
  3511. // you need to also update the JS port.
  3512. $values = array();
  3513. $in_string = false;
  3514. $buffer = '';
  3515. for ($i = 0, $length = mb_strlen($values_string);
  3516. $i < $length;
  3517. $i++
  3518. ) {
  3519. $curr = mb_substr($values_string, $i, 1);
  3520. $next = ($i == mb_strlen($values_string) - 1)
  3521. ? ''
  3522. : mb_substr($values_string, $i + 1, 1);
  3523. if (! $in_string && $curr == "'") {
  3524. $in_string = true;
  3525. } elseif (($in_string && $curr == "\\") && $next == "\\") {
  3526. $buffer .= "&#92;";
  3527. $i++;
  3528. } elseif (($in_string && $next == "'")
  3529. && ($curr == "'" || $curr == "\\")
  3530. ) {
  3531. $buffer .= "&#39;";
  3532. $i++;
  3533. } elseif ($in_string && $curr == "'") {
  3534. $in_string = false;
  3535. $values[] = $buffer;
  3536. $buffer = '';
  3537. } elseif ($in_string) {
  3538. $buffer .= $curr;
  3539. }
  3540. }
  3541. if (strlen($buffer) > 0) {
  3542. // The leftovers in the buffer are the last value (if any)
  3543. $values[] = $buffer;
  3544. }
  3545. if (! $escapeHtml) {
  3546. foreach ($values as $key => $value) {
  3547. $values[$key] = html_entity_decode($value, ENT_QUOTES, 'UTF-8');
  3548. }
  3549. }
  3550. return $values;
  3551. }
  3552. /**
  3553. * Get regular expression which occur first inside the given sql query.
  3554. *
  3555. * @param array $regex_array Comparing regular expressions.
  3556. * @param String $query SQL query to be checked.
  3557. *
  3558. * @return String Matching regular expression.
  3559. */
  3560. public static function getFirstOccurringRegularExpression(array $regex_array, $query)
  3561. {
  3562. $minimum_first_occurence_index = null;
  3563. $regex = null;
  3564. foreach ($regex_array as $test_regex) {
  3565. if (preg_match($test_regex, $query, $matches, PREG_OFFSET_CAPTURE)) {
  3566. if (is_null($minimum_first_occurence_index)
  3567. || ($matches[0][1] < $minimum_first_occurence_index)
  3568. ) {
  3569. $regex = $test_regex;
  3570. $minimum_first_occurence_index = $matches[0][1];
  3571. }
  3572. }
  3573. }
  3574. return $regex;
  3575. }
  3576. /**
  3577. * Return the list of tabs for the menu with corresponding names
  3578. *
  3579. * @param string $level 'server', 'db' or 'table' level
  3580. *
  3581. * @return array list of tabs for the menu
  3582. */
  3583. public static function getMenuTabList($level = null)
  3584. {
  3585. $tabList = array(
  3586. 'server' => array(
  3587. 'databases' => __('Databases'),
  3588. 'sql' => __('SQL'),
  3589. 'status' => __('Status'),
  3590. 'rights' => __('Users'),
  3591. 'export' => __('Export'),
  3592. 'import' => __('Import'),
  3593. 'settings' => __('Settings'),
  3594. 'binlog' => __('Binary log'),
  3595. 'replication' => __('Replication'),
  3596. 'vars' => __('Variables'),
  3597. 'charset' => __('Charsets'),
  3598. 'plugins' => __('Plugins'),
  3599. 'engine' => __('Engines')
  3600. ),
  3601. 'db' => array(
  3602. 'structure' => __('Structure'),
  3603. 'sql' => __('SQL'),
  3604. 'search' => __('Search'),
  3605. 'query' => __('Query'),
  3606. 'export' => __('Export'),
  3607. 'import' => __('Import'),
  3608. 'operation' => __('Operations'),
  3609. 'privileges' => __('Privileges'),
  3610. 'routines' => __('Routines'),
  3611. 'events' => __('Events'),
  3612. 'triggers' => __('Triggers'),
  3613. 'tracking' => __('Tracking'),
  3614. 'designer' => __('Designer'),
  3615. 'central_columns' => __('Central columns')
  3616. ),
  3617. 'table' => array(
  3618. 'browse' => __('Browse'),
  3619. 'structure' => __('Structure'),
  3620. 'sql' => __('SQL'),
  3621. 'search' => __('Search'),
  3622. 'insert' => __('Insert'),
  3623. 'export' => __('Export'),
  3624. 'import' => __('Import'),
  3625. 'privileges' => __('Privileges'),
  3626. 'operation' => __('Operations'),
  3627. 'tracking' => __('Tracking'),
  3628. 'triggers' => __('Triggers'),
  3629. )
  3630. );
  3631. if ($level == null) {
  3632. return $tabList;
  3633. } elseif (array_key_exists($level, $tabList)) {
  3634. return $tabList[$level];
  3635. }
  3636. return null;
  3637. }
  3638. /**
  3639. * Add fractional seconds to time, datetime and timestamp strings.
  3640. * If the string contains fractional seconds,
  3641. * pads it with 0s up to 6 decimal places.
  3642. *
  3643. * @param string $value time, datetime or timestamp strings
  3644. *
  3645. * @return string time, datetime or timestamp strings with fractional seconds
  3646. */
  3647. public static function addMicroseconds($value)
  3648. {
  3649. if (empty($value) || $value == 'CURRENT_TIMESTAMP'
  3650. || $value == 'current_timestamp()') {
  3651. return $value;
  3652. }
  3653. if (mb_strpos($value, '.') === false) {
  3654. return $value . '.000000';
  3655. }
  3656. $value .= '000000';
  3657. return mb_substr(
  3658. $value,
  3659. 0,
  3660. mb_strpos($value, '.') + 7
  3661. );
  3662. }
  3663. /**
  3664. * Reads the file, detects the compression MIME type, closes the file
  3665. * and returns the MIME type
  3666. *
  3667. * @param resource $file the file handle
  3668. *
  3669. * @return string the MIME type for compression, or 'none'
  3670. */
  3671. public static function getCompressionMimeType($file)
  3672. {
  3673. $test = fread($file, 4);
  3674. $len = strlen($test);
  3675. fclose($file);
  3676. if ($len >= 2 && $test[0] == chr(31) && $test[1] == chr(139)) {
  3677. return 'application/gzip';
  3678. }
  3679. if ($len >= 3 && substr($test, 0, 3) == 'BZh') {
  3680. return 'application/bzip2';
  3681. }
  3682. if ($len >= 4 && $test == "PK\003\004") {
  3683. return 'application/zip';
  3684. }
  3685. return 'none';
  3686. }
  3687. /**
  3688. * Renders a single link for the top of the navigation panel
  3689. *
  3690. * @param string $link The url for the link
  3691. * @param bool $showText Whether to show the text or to
  3692. * only use it for title attributes
  3693. * @param string $text The text to display and use for title attributes
  3694. * @param bool $showIcon Whether to show the icon
  3695. * @param string $icon The filename of the icon to show
  3696. * @param string $linkId Value to use for the ID attribute
  3697. * @param boolean $disableAjax Whether to disable ajax page loading for this link
  3698. * @param string $linkTarget The name of the target frame for the link
  3699. * @param array $classes HTML classes to apply
  3700. *
  3701. * @return string HTML code for one link
  3702. */
  3703. public static function getNavigationLink(
  3704. $link,
  3705. $showText,
  3706. $text,
  3707. $showIcon,
  3708. $icon,
  3709. $linkId = '',
  3710. $disableAjax = false,
  3711. $linkTarget = '',
  3712. array $classes = array()
  3713. ) {
  3714. $retval = '<a href="' . $link . '"';
  3715. if (! empty($linkId)) {
  3716. $retval .= ' id="' . $linkId . '"';
  3717. }
  3718. if (! empty($linkTarget)) {
  3719. $retval .= ' target="' . $linkTarget . '"';
  3720. }
  3721. if ($disableAjax) {
  3722. $classes[] = 'disableAjax';
  3723. }
  3724. if (!empty($classes)) {
  3725. $retval .= ' class="' . join(" ", $classes) . '"';
  3726. }
  3727. $retval .= ' title="' . $text . '">';
  3728. if ($showIcon) {
  3729. $retval .= self::getImage(
  3730. $icon,
  3731. $text
  3732. );
  3733. }
  3734. if ($showText) {
  3735. $retval .= $text;
  3736. }
  3737. $retval .= '</a>';
  3738. if ($showText) {
  3739. $retval .= '<br />';
  3740. }
  3741. return $retval;
  3742. }
  3743. /**
  3744. * Provide COLLATE clause, if required, to perform case sensitive comparisons
  3745. * for queries on information_schema.
  3746. *
  3747. * @return string COLLATE clause if needed or empty string.
  3748. */
  3749. public static function getCollateForIS()
  3750. {
  3751. $names = $GLOBALS['dbi']->getLowerCaseNames();
  3752. if ($names === '0') {
  3753. return "COLLATE utf8_bin";
  3754. } elseif ($names === '2') {
  3755. return "COLLATE utf8_general_ci";
  3756. }
  3757. return "";
  3758. }
  3759. /**
  3760. * Process the index data.
  3761. *
  3762. * @param array $indexes index data
  3763. *
  3764. * @return array processes index data
  3765. */
  3766. public static function processIndexData(array $indexes)
  3767. {
  3768. $lastIndex = '';
  3769. $primary = '';
  3770. $pk_array = array(); // will be use to emphasis prim. keys in the table
  3771. $indexes_info = array();
  3772. $indexes_data = array();
  3773. // view
  3774. foreach ($indexes as $row) {
  3775. // Backups the list of primary keys
  3776. if ($row['Key_name'] == 'PRIMARY') {
  3777. $primary .= $row['Column_name'] . ', ';
  3778. $pk_array[$row['Column_name']] = 1;
  3779. }
  3780. // Retains keys informations
  3781. if ($row['Key_name'] != $lastIndex) {
  3782. $indexes[] = $row['Key_name'];
  3783. $lastIndex = $row['Key_name'];
  3784. }
  3785. $indexes_info[$row['Key_name']]['Sequences'][] = $row['Seq_in_index'];
  3786. $indexes_info[$row['Key_name']]['Non_unique'] = $row['Non_unique'];
  3787. if (isset($row['Cardinality'])) {
  3788. $indexes_info[$row['Key_name']]['Cardinality'] = $row['Cardinality'];
  3789. }
  3790. // I don't know what does following column mean....
  3791. // $indexes_info[$row['Key_name']]['Packed'] = $row['Packed'];
  3792. $indexes_info[$row['Key_name']]['Comment'] = $row['Comment'];
  3793. $indexes_data[$row['Key_name']][$row['Seq_in_index']]['Column_name']
  3794. = $row['Column_name'];
  3795. if (isset($row['Sub_part'])) {
  3796. $indexes_data[$row['Key_name']][$row['Seq_in_index']]['Sub_part']
  3797. = $row['Sub_part'];
  3798. }
  3799. } // end while
  3800. return array($primary, $pk_array, $indexes_info, $indexes_data);
  3801. }
  3802. /**
  3803. * Function to get html for the start row and number of rows panel
  3804. *
  3805. * @param string $sql_query sql query
  3806. *
  3807. * @return string html
  3808. */
  3809. public static function getStartAndNumberOfRowsPanel($sql_query)
  3810. {
  3811. $pos = isset($_REQUEST['pos'])
  3812. ? $_REQUEST['pos']
  3813. : $_SESSION['tmpval']['pos'];
  3814. if (isset($_REQUEST['session_max_rows'])) {
  3815. $rows = $_REQUEST['session_max_rows'];
  3816. } else {
  3817. if ($_SESSION['tmpval']['max_rows'] != 'all') {
  3818. $rows = $_SESSION['tmpval']['max_rows'];
  3819. } else {
  3820. $rows = $GLOBALS['cfg']['MaxRows'];
  3821. }
  3822. }
  3823. return Template::get('start_and_number_of_rows_panel')
  3824. ->render(
  3825. array(
  3826. 'pos' => $pos,
  3827. 'unlim_num_rows' => intval($_REQUEST['unlim_num_rows']),
  3828. 'rows' => $rows,
  3829. 'sql_query' => $sql_query,
  3830. )
  3831. );
  3832. }
  3833. /**
  3834. * Returns whether the database server supports virtual columns
  3835. *
  3836. * @return bool
  3837. */
  3838. public static function isVirtualColumnsSupported()
  3839. {
  3840. $serverType = self::getServerType();
  3841. $serverVersion = $GLOBALS['dbi']->getVersion();
  3842. return $serverType == 'MySQL' && $serverVersion >= 50705
  3843. || ($serverType == 'MariaDB' && $serverVersion >= 50200);
  3844. }
  3845. /**
  3846. * Returns the proper class clause according to the column type
  3847. *
  3848. * @param string $type the column type
  3849. *
  3850. * @return string $class_clause the HTML class clause
  3851. */
  3852. public static function getClassForType($type)
  3853. {
  3854. if ('set' == $type
  3855. || 'enum' == $type
  3856. ) {
  3857. $class_clause = '';
  3858. } else {
  3859. $class_clause = ' class="nowrap"';
  3860. }
  3861. return $class_clause;
  3862. }
  3863. /**
  3864. * Gets the list of tables in the current db and information about these
  3865. * tables if possible
  3866. *
  3867. * @param string $db database name
  3868. * @param string $sub_part part of script name
  3869. *
  3870. * @return array
  3871. *
  3872. */
  3873. public static function getDbInfo($db, $sub_part)
  3874. {
  3875. global $cfg;
  3876. /**
  3877. * limits for table list
  3878. */
  3879. if (! isset($_SESSION['tmpval']['table_limit_offset'])
  3880. || $_SESSION['tmpval']['table_limit_offset_db'] != $db
  3881. ) {
  3882. $_SESSION['tmpval']['table_limit_offset'] = 0;
  3883. $_SESSION['tmpval']['table_limit_offset_db'] = $db;
  3884. }
  3885. if (isset($_REQUEST['pos'])) {
  3886. $_SESSION['tmpval']['table_limit_offset'] = (int) $_REQUEST['pos'];
  3887. }
  3888. $pos = $_SESSION['tmpval']['table_limit_offset'];
  3889. /**
  3890. * whether to display extended stats
  3891. */
  3892. $is_show_stats = $cfg['ShowStats'];
  3893. /**
  3894. * whether selected db is information_schema
  3895. */
  3896. $db_is_system_schema = false;
  3897. if ($GLOBALS['dbi']->isSystemSchema($db)) {
  3898. $is_show_stats = false;
  3899. $db_is_system_schema = true;
  3900. }
  3901. /**
  3902. * information about tables in db
  3903. */
  3904. $tables = array();
  3905. $tooltip_truename = array();
  3906. $tooltip_aliasname = array();
  3907. // Special speedup for newer MySQL Versions (in 4.0 format changed)
  3908. if (true === $cfg['SkipLockedTables']) {
  3909. $db_info_result = $GLOBALS['dbi']->query(
  3910. 'SHOW OPEN TABLES FROM ' . self::backquote($db) . ' WHERE In_use > 0;'
  3911. );
  3912. // Blending out tables in use
  3913. if ($db_info_result && $GLOBALS['dbi']->numRows($db_info_result) > 0) {
  3914. $tables = self::getTablesWhenOpen($db, $db_info_result);
  3915. } elseif ($db_info_result) {
  3916. $GLOBALS['dbi']->freeResult($db_info_result);
  3917. }
  3918. }
  3919. if (empty($tables)) {
  3920. // Set some sorting defaults
  3921. $sort = 'Name';
  3922. $sort_order = 'ASC';
  3923. if (isset($_REQUEST['sort'])) {
  3924. $sortable_name_mappings = array(
  3925. 'table' => 'Name',
  3926. 'records' => 'Rows',
  3927. 'type' => 'Engine',
  3928. 'collation' => 'Collation',
  3929. 'size' => 'Data_length',
  3930. 'overhead' => 'Data_free',
  3931. 'creation' => 'Create_time',
  3932. 'last_update' => 'Update_time',
  3933. 'last_check' => 'Check_time',
  3934. 'comment' => 'Comment',
  3935. );
  3936. // Make sure the sort type is implemented
  3937. if (isset($sortable_name_mappings[$_REQUEST['sort']])) {
  3938. $sort = $sortable_name_mappings[$_REQUEST['sort']];
  3939. if ($_REQUEST['sort_order'] == 'DESC') {
  3940. $sort_order = 'DESC';
  3941. }
  3942. }
  3943. }
  3944. $groupWithSeparator = false;
  3945. $tbl_type = null;
  3946. $limit_offset = 0;
  3947. $limit_count = false;
  3948. $groupTable = array();
  3949. if (! empty($_REQUEST['tbl_group']) || ! empty($_REQUEST['tbl_type'])) {
  3950. if (! empty($_REQUEST['tbl_type'])) {
  3951. // only tables for selected type
  3952. $tbl_type = $_REQUEST['tbl_type'];
  3953. }
  3954. if (! empty($_REQUEST['tbl_group'])) {
  3955. // only tables for selected group
  3956. $tbl_group = $_REQUEST['tbl_group'];
  3957. // include the table with the exact name of the group if such
  3958. // exists
  3959. $groupTable = $GLOBALS['dbi']->getTablesFull(
  3960. $db, $tbl_group, false, $limit_offset,
  3961. $limit_count, $sort, $sort_order, $tbl_type
  3962. );
  3963. $groupWithSeparator = $tbl_group
  3964. . $GLOBALS['cfg']['NavigationTreeTableSeparator'];
  3965. }
  3966. } else {
  3967. // all tables in db
  3968. // - get the total number of tables
  3969. // (needed for proper working of the MaxTableList feature)
  3970. $tables = $GLOBALS['dbi']->getTables($db);
  3971. $total_num_tables = count($tables);
  3972. if (isset($sub_part) && $sub_part == '_export') {
  3973. // (don't fetch only a subset if we are coming from
  3974. // db_export.php, because I think it's too risky to display only
  3975. // a subset of the table names when exporting a db)
  3976. /**
  3977. *
  3978. * @todo Page selector for table names?
  3979. */
  3980. } else {
  3981. // fetch the details for a possible limited subset
  3982. $limit_offset = $pos;
  3983. $limit_count = true;
  3984. }
  3985. }
  3986. $tables = array_merge(
  3987. $groupTable,
  3988. $GLOBALS['dbi']->getTablesFull(
  3989. $db, $groupWithSeparator, ($groupWithSeparator !== false),
  3990. $limit_offset, $limit_count, $sort, $sort_order, $tbl_type
  3991. )
  3992. );
  3993. }
  3994. $num_tables = count($tables);
  3995. // (needed for proper working of the MaxTableList feature)
  3996. if (! isset($total_num_tables)) {
  3997. $total_num_tables = $num_tables;
  3998. }
  3999. /**
  4000. * If coming from a Show MySQL link on the home page,
  4001. * put something in $sub_part
  4002. */
  4003. if (empty($sub_part)) {
  4004. $sub_part = '_structure';
  4005. }
  4006. return array(
  4007. $tables,
  4008. $num_tables,
  4009. $total_num_tables,
  4010. $sub_part,
  4011. $is_show_stats,
  4012. $db_is_system_schema,
  4013. $tooltip_truename,
  4014. $tooltip_aliasname,
  4015. $pos
  4016. );
  4017. }
  4018. /**
  4019. * Gets the list of tables in the current db, taking into account
  4020. * that they might be "in use"
  4021. *
  4022. * @param string $db database name
  4023. * @param object $db_info_result result set
  4024. *
  4025. * @return array $tables list of tables
  4026. *
  4027. */
  4028. public static function getTablesWhenOpen($db, $db_info_result)
  4029. {
  4030. $sot_cache = $tables = array();
  4031. while ($tmp = $GLOBALS['dbi']->fetchAssoc($db_info_result)) {
  4032. $sot_cache[$tmp['Table']] = true;
  4033. }
  4034. $GLOBALS['dbi']->freeResult($db_info_result);
  4035. // is there at least one "in use" table?
  4036. if (isset($sot_cache)) {
  4037. $tblGroupSql = "";
  4038. $whereAdded = false;
  4039. if (Core::isValid($_REQUEST['tbl_group'])) {
  4040. $group = self::escapeMysqlWildcards($_REQUEST['tbl_group']);
  4041. $groupWithSeparator = self::escapeMysqlWildcards(
  4042. $_REQUEST['tbl_group']
  4043. . $GLOBALS['cfg']['NavigationTreeTableSeparator']
  4044. );
  4045. $tblGroupSql .= " WHERE ("
  4046. . self::backquote('Tables_in_' . $db)
  4047. . " LIKE '" . $groupWithSeparator . "%'"
  4048. . " OR "
  4049. . self::backquote('Tables_in_' . $db)
  4050. . " LIKE '" . $group . "')";
  4051. $whereAdded = true;
  4052. }
  4053. if (Core::isValid($_REQUEST['tbl_type'], array('table', 'view'))) {
  4054. $tblGroupSql .= $whereAdded ? " AND" : " WHERE";
  4055. if ($_REQUEST['tbl_type'] == 'view') {
  4056. $tblGroupSql .= " `Table_type` != 'BASE TABLE'";
  4057. } else {
  4058. $tblGroupSql .= " `Table_type` = 'BASE TABLE'";
  4059. }
  4060. }
  4061. $db_info_result = $GLOBALS['dbi']->query(
  4062. 'SHOW FULL TABLES FROM ' . self::backquote($db) . $tblGroupSql,
  4063. null, DatabaseInterface::QUERY_STORE
  4064. );
  4065. unset($tblGroupSql, $whereAdded);
  4066. if ($db_info_result && $GLOBALS['dbi']->numRows($db_info_result) > 0) {
  4067. $names = array();
  4068. while ($tmp = $GLOBALS['dbi']->fetchRow($db_info_result)) {
  4069. if (! isset($sot_cache[$tmp[0]])) {
  4070. $names[] = $tmp[0];
  4071. } else { // table in use
  4072. $tables[$tmp[0]] = array(
  4073. 'TABLE_NAME' => $tmp[0],
  4074. 'ENGINE' => '',
  4075. 'TABLE_TYPE' => '',
  4076. 'TABLE_ROWS' => 0,
  4077. 'TABLE_COMMENT' => '',
  4078. );
  4079. }
  4080. } // end while
  4081. if (count($names) > 0) {
  4082. $tables = array_merge(
  4083. $tables,
  4084. $GLOBALS['dbi']->getTablesFull($db, $names)
  4085. );
  4086. }
  4087. if ($GLOBALS['cfg']['NaturalOrder']) {
  4088. uksort($tables, 'strnatcasecmp');
  4089. }
  4090. } elseif ($db_info_result) {
  4091. $GLOBALS['dbi']->freeResult($db_info_result);
  4092. }
  4093. unset($sot_cache);
  4094. }
  4095. return $tables;
  4096. }
  4097. /**
  4098. * Returs list of used PHP extensions.
  4099. *
  4100. * @return array of strings
  4101. */
  4102. public static function listPHPExtensions()
  4103. {
  4104. $result = array();
  4105. if (DatabaseInterface::checkDbExtension('mysqli')) {
  4106. $result[] = 'mysqli';
  4107. } else {
  4108. $result[] = 'mysql';
  4109. }
  4110. if (extension_loaded('curl')) {
  4111. $result[] = 'curl';
  4112. }
  4113. if (extension_loaded('mbstring')) {
  4114. $result[] = 'mbstring';
  4115. }
  4116. return $result;
  4117. }
  4118. /**
  4119. * Converts given (request) paramter to string
  4120. *
  4121. * @param mixed $value Value to convert
  4122. *
  4123. * @return string
  4124. */
  4125. public static function requestString($value)
  4126. {
  4127. while (is_array($value) || is_object($value)) {
  4128. $value = reset($value);
  4129. }
  4130. return trim((string)$value);
  4131. }
  4132. /**
  4133. * Generates random string consisting of ASCII chars
  4134. *
  4135. * @param integer $length Length of string
  4136. *
  4137. * @return string
  4138. */
  4139. public static function generateRandom($length)
  4140. {
  4141. $result = '';
  4142. if (class_exists('phpseclib\\Crypt\\Random')) {
  4143. $random_func = array('phpseclib\\Crypt\\Random', 'string');
  4144. } else {
  4145. $random_func = 'openssl_random_pseudo_bytes';
  4146. }
  4147. while (strlen($result) < $length) {
  4148. // Get random byte and strip highest bit
  4149. // to get ASCII only range
  4150. $byte = ord($random_func(1)) & 0x7f;
  4151. // We want only ASCII chars
  4152. if ($byte > 32) {
  4153. $result .= chr($byte);
  4154. }
  4155. }
  4156. return $result;
  4157. }
  4158. /**
  4159. * Wraper around PHP date function
  4160. *
  4161. * @param string $format Date format string
  4162. *
  4163. * @return string
  4164. */
  4165. public static function date($format)
  4166. {
  4167. if (defined('TESTSUITE')) {
  4168. return '0000-00-00 00:00:00';
  4169. }
  4170. return date($format);
  4171. }
  4172. /**
  4173. * Wrapper around php's set_time_limit
  4174. *
  4175. * @return void
  4176. */
  4177. public static function setTimeLimit()
  4178. {
  4179. // The function can be disabled in php.ini
  4180. if (function_exists('set_time_limit')) {
  4181. @set_time_limit($GLOBALS['cfg']['ExecTimeLimit']);
  4182. }
  4183. }
  4184. /**
  4185. * Access to a multidimensional array by dot notation
  4186. *
  4187. * @param array $array List of values
  4188. * @param string|array $path Path to searched value
  4189. * @param mixed $default Default value
  4190. *
  4191. * @return mixed Searched value
  4192. */
  4193. public static function getValueByKey(array $array, $path, $default = null)
  4194. {
  4195. if (is_string($path)) {
  4196. $path = explode('.', $path);
  4197. }
  4198. $p = array_shift($path);
  4199. while (isset($p)) {
  4200. if (!isset($array[$p])) {
  4201. return $default;
  4202. }
  4203. $array = $array[$p];
  4204. $p = array_shift($path);
  4205. }
  4206. return $array;
  4207. }
  4208. /**
  4209. * Creates a clickable column header for table information
  4210. *
  4211. * @param string $title Title to use for the link
  4212. * @param string $sort Corresponds to sortable data name mapped
  4213. * in Util::getDbInfo
  4214. * @param string $initialSortOrder Initial sort order
  4215. *
  4216. * @return string Link to be displayed in the table header
  4217. */
  4218. public static function sortableTableHeader($title, $sort, $initialSortOrder = 'ASC')
  4219. {
  4220. $requestedSort = 'table';
  4221. $requestedSortOrder = $futureSortOrder = $initialSortOrder;
  4222. // If the user requested a sort
  4223. if (isset($_REQUEST['sort'])) {
  4224. $requestedSort = $_REQUEST['sort'];
  4225. if (isset($_REQUEST['sort_order'])) {
  4226. $requestedSortOrder = $_REQUEST['sort_order'];
  4227. }
  4228. }
  4229. $orderImg = '';
  4230. $orderLinkParams = array();
  4231. $orderLinkParams['title'] = __('Sort');
  4232. // If this column was requested to be sorted.
  4233. if ($requestedSort == $sort) {
  4234. if ($requestedSortOrder == 'ASC') {
  4235. $futureSortOrder = 'DESC';
  4236. // current sort order is ASC
  4237. $orderImg = ' ' . self::getImage(
  4238. 's_asc',
  4239. __('Ascending'),
  4240. array('class' => 'sort_arrow', 'title' => '')
  4241. );
  4242. $orderImg .= ' ' . self::getImage(
  4243. 's_desc',
  4244. __('Descending'),
  4245. array('class' => 'sort_arrow hide', 'title' => '')
  4246. );
  4247. // but on mouse over, show the reverse order (DESC)
  4248. $orderLinkParams['onmouseover'] = "$('.sort_arrow').toggle();";
  4249. // on mouse out, show current sort order (ASC)
  4250. $orderLinkParams['onmouseout'] = "$('.sort_arrow').toggle();";
  4251. } else {
  4252. $futureSortOrder = 'ASC';
  4253. // current sort order is DESC
  4254. $orderImg = ' ' . self::getImage(
  4255. 's_asc',
  4256. __('Ascending'),
  4257. array('class' => 'sort_arrow hide', 'title' => '')
  4258. );
  4259. $orderImg .= ' ' . self::getImage(
  4260. 's_desc',
  4261. __('Descending'),
  4262. array('class' => 'sort_arrow', 'title' => '')
  4263. );
  4264. // but on mouse over, show the reverse order (ASC)
  4265. $orderLinkParams['onmouseover'] = "$('.sort_arrow').toggle();";
  4266. // on mouse out, show current sort order (DESC)
  4267. $orderLinkParams['onmouseout'] = "$('.sort_arrow').toggle();";
  4268. }
  4269. }
  4270. $urlParams = array(
  4271. 'db' => $_REQUEST['db'],
  4272. 'pos' => 0, // We set the position back to 0 every time they sort.
  4273. 'sort' => $sort,
  4274. 'sort_order' => $futureSortOrder,
  4275. );
  4276. if (Core::isValid($_REQUEST['tbl_type'], array('view', 'table'))) {
  4277. $urlParams['tbl_type'] = $_REQUEST['tbl_type'];
  4278. }
  4279. if (! empty($_REQUEST['tbl_group'])) {
  4280. $urlParams['tbl_group'] = $_REQUEST['tbl_group'];
  4281. }
  4282. $url = 'db_structure.php' . Url::getCommon($urlParams);
  4283. return self::linkOrButton($url, $title . $orderImg, $orderLinkParams);
  4284. }
  4285. }