Util.php 164 KB

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