PageRenderTime 40ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/phpMyAdmin/libraries/common.lib.php

https://bitbucket.org/izubizarreta/https-bitbucket.org-bityvip
PHP | 3882 lines | 2423 code | 309 blank | 1150 comment | 576 complexity | 9d04b0512a995647389ad91712d76ecf MD5 | raw file
Possible License(s): LGPL-3.0, LGPL-2.0, JSON, GPL-2.0, BSD-3-Clause, LGPL-2.1, MIT
  1. <?php
  2. /* vim: set expandtab sw=4 ts=4 sts=4: */
  3. /**
  4. * Misc functions used all over the scripts.
  5. *
  6. * @package PhpMyAdmin
  7. */
  8. /**
  9. * Detects which function to use for PMA_pow.
  10. *
  11. * @return string Function name.
  12. */
  13. function PMA_detect_pow()
  14. {
  15. if (function_exists('bcpow')) {
  16. // BCMath Arbitrary Precision Mathematics Function
  17. return 'bcpow';
  18. } elseif (function_exists('gmp_pow')) {
  19. // GMP Function
  20. return 'gmp_pow';
  21. } else {
  22. // PHP function
  23. return 'pow';
  24. }
  25. }
  26. /**
  27. * Exponential expression / raise number into power
  28. *
  29. * @param string $base base to raise
  30. * @param string $exp exponent to use
  31. * @param mixed $use_function pow function to use, or false for auto-detect
  32. *
  33. * @return mixed string or float
  34. */
  35. function PMA_pow($base, $exp, $use_function = false)
  36. {
  37. static $pow_function = null;
  38. if (null == $pow_function) {
  39. $pow_function = PMA_detect_pow();
  40. }
  41. if (! $use_function) {
  42. $use_function = $pow_function;
  43. }
  44. if ($exp < 0 && 'pow' != $use_function) {
  45. return false;
  46. }
  47. switch ($use_function) {
  48. case 'bcpow' :
  49. // bcscale() needed for testing PMA_pow() with base values < 1
  50. bcscale(10);
  51. $pow = bcpow($base, $exp);
  52. break;
  53. case 'gmp_pow' :
  54. $pow = gmp_strval(gmp_pow($base, $exp));
  55. break;
  56. case 'pow' :
  57. $base = (float) $base;
  58. $exp = (int) $exp;
  59. $pow = pow($base, $exp);
  60. break;
  61. default:
  62. $pow = $use_function($base, $exp);
  63. }
  64. return $pow;
  65. }
  66. /**
  67. * Returns an HTML IMG tag for a particular icon from a theme,
  68. * which may be an actual file or an icon from a sprite.
  69. * This function takes into account the PropertiesIconic
  70. * configuration setting and wraps the image tag in a span tag.
  71. *
  72. * @param string $icon name of icon file
  73. * @param string $alternate alternate text
  74. * @param boolean $force_text whether to force alternate text to be displayed
  75. *
  76. * @return string an html snippet
  77. */
  78. function PMA_getIcon($icon, $alternate = '', $force_text = false)
  79. {
  80. // $cfg['PropertiesIconic'] is true or both
  81. $include_icon = ($GLOBALS['cfg']['PropertiesIconic'] !== false);
  82. // $cfg['PropertiesIconic'] is false or both
  83. // OR we have no $include_icon
  84. $include_text = ($force_text || true !== $GLOBALS['cfg']['PropertiesIconic']);
  85. // Always use a span (we rely on this in js/sql.js)
  86. $button = '<span class="nowrap">';
  87. if ($include_icon) {
  88. $button .= PMA_getImage($icon, $alternate);
  89. }
  90. if ($include_icon && $include_text) {
  91. $button .= ' ';
  92. }
  93. if ($include_text) {
  94. $button .= $alternate;
  95. }
  96. $button .= '</span>';
  97. return $button;
  98. }
  99. /**
  100. * Returns an HTML IMG tag for a particular image from a theme,
  101. * which may be an actual file or an icon from a sprite
  102. *
  103. * @param string $image The name of the file to get
  104. * @param string $alternate Used to set 'alt' and 'title' attributes of the image
  105. * @param array $attributes An associative array of other attributes
  106. *
  107. * @return string an html IMG tag
  108. */
  109. function PMA_getImage($image, $alternate = '', $attributes = array())
  110. {
  111. static $sprites; // cached list of available sprites (if any)
  112. $url = '';
  113. $is_sprite = false;
  114. $alternate = htmlspecialchars($alternate);
  115. // If it's the first time this function is called
  116. if (! isset($sprites)) {
  117. // Try to load the list of sprites
  118. if (is_readable($_SESSION['PMA_Theme']->getPath() . '/sprites.lib.php')) {
  119. include_once $_SESSION['PMA_Theme']->getPath() . '/sprites.lib.php';
  120. $sprites = PMA_sprites();
  121. } else {
  122. // No sprites are available for this theme
  123. $sprites = array();
  124. }
  125. }
  126. // Check if we have the requested image as a sprite
  127. // and set $url accordingly
  128. $class = str_replace(array('.gif','.png'), '', $image);
  129. if (array_key_exists($class, $sprites)) {
  130. $is_sprite = true;
  131. $url = 'themes/dot.gif';
  132. } else {
  133. $url = $GLOBALS['pmaThemeImage'] . $image;
  134. }
  135. // set class attribute
  136. if ($is_sprite) {
  137. if (isset($attributes['class'])) {
  138. $attributes['class'] = "icon ic_$class " . $attributes['class'];
  139. } else {
  140. $attributes['class'] = "icon ic_$class";
  141. }
  142. }
  143. // set all other attributes
  144. $attr_str = '';
  145. foreach ($attributes as $key => $value) {
  146. if (! in_array($key, array('alt', 'title'))) {
  147. $attr_str .= " $key=\"$value\"";
  148. }
  149. }
  150. // override the alt attribute
  151. if (isset($attributes['alt'])) {
  152. $alt = $attributes['alt'];
  153. } else {
  154. $alt = $alternate;
  155. }
  156. // override the title attribute
  157. if (isset($attributes['title'])) {
  158. $title = $attributes['title'];
  159. } else {
  160. $title = $alternate;
  161. }
  162. // generate the IMG tag
  163. $template = '<img src="%s" title="%s" alt="%s"%s />';
  164. $retval = sprintf($template, $url, $title, $alt, $attr_str);
  165. return $retval;
  166. }
  167. /**
  168. * Displays the maximum size for an upload
  169. *
  170. * @param integer $max_upload_size the size
  171. *
  172. * @return string the message
  173. *
  174. * @access public
  175. */
  176. function PMA_displayMaximumUploadSize($max_upload_size)
  177. {
  178. // I have to reduce the second parameter (sensitiveness) from 6 to 4
  179. // to avoid weird results like 512 kKib
  180. list($max_size, $max_unit) = PMA_formatByteDown($max_upload_size, 4);
  181. return '(' . sprintf(__('Max: %s%s'), $max_size, $max_unit) . ')';
  182. }
  183. /**
  184. * Generates a hidden field which should indicate to the browser
  185. * the maximum size for upload
  186. *
  187. * @param integer $max_size the size
  188. *
  189. * @return string the INPUT field
  190. *
  191. * @access public
  192. */
  193. function PMA_generateHiddenMaxFileSize($max_size)
  194. {
  195. return '<input type="hidden" name="MAX_FILE_SIZE" value="' .$max_size . '" />';
  196. }
  197. /**
  198. * Add slashes before "'" and "\" characters so a value containing them can
  199. * be used in a sql comparison.
  200. *
  201. * @param string $a_string the string to slash
  202. * @param bool $is_like whether the string will be used in a 'LIKE' clause
  203. * (it then requires two more escaped sequences) or not
  204. * @param bool $crlf whether to treat cr/lfs as escape-worthy entities
  205. * (converts \n to \\n, \r to \\r)
  206. * @param bool $php_code whether this function is used as part of the
  207. * "Create PHP code" dialog
  208. *
  209. * @return string the slashed string
  210. *
  211. * @access public
  212. */
  213. function PMA_sqlAddSlashes($a_string = '', $is_like = false, $crlf = false, $php_code = false)
  214. {
  215. if ($is_like) {
  216. $a_string = str_replace('\\', '\\\\\\\\', $a_string);
  217. } else {
  218. $a_string = str_replace('\\', '\\\\', $a_string);
  219. }
  220. if ($crlf) {
  221. $a_string = strtr(
  222. $a_string,
  223. array("\n" => '\n', "\r" => '\r', "\t" => '\t')
  224. );
  225. }
  226. if ($php_code) {
  227. $a_string = str_replace('\'', '\\\'', $a_string);
  228. } else {
  229. $a_string = str_replace('\'', '\'\'', $a_string);
  230. }
  231. return $a_string;
  232. } // end of the 'PMA_sqlAddSlashes()' function
  233. /**
  234. * Add slashes before "_" and "%" characters for using them in MySQL
  235. * database, table and field names.
  236. * Note: This function does not escape backslashes!
  237. *
  238. * @param string $name the string to escape
  239. *
  240. * @return string the escaped string
  241. *
  242. * @access public
  243. */
  244. function PMA_escape_mysql_wildcards($name)
  245. {
  246. return strtr($name, array('_' => '\\_', '%' => '\\%'));
  247. } // end of the 'PMA_escape_mysql_wildcards()' function
  248. /**
  249. * removes slashes before "_" and "%" characters
  250. * Note: This function does not unescape backslashes!
  251. *
  252. * @param string $name the string to escape
  253. *
  254. * @return string the escaped string
  255. *
  256. * @access public
  257. */
  258. function PMA_unescape_mysql_wildcards($name)
  259. {
  260. return strtr($name, array('\\_' => '_', '\\%' => '%'));
  261. } // end of the 'PMA_unescape_mysql_wildcards()' function
  262. /**
  263. * removes quotes (',",`) from a quoted string
  264. *
  265. * checks if the sting is quoted and removes this quotes
  266. *
  267. * @param string $quoted_string string to remove quotes from
  268. * @param string $quote type of quote to remove
  269. *
  270. * @return string unqoted string
  271. */
  272. function PMA_unQuote($quoted_string, $quote = null)
  273. {
  274. $quotes = array();
  275. if (null === $quote) {
  276. $quotes[] = '`';
  277. $quotes[] = '"';
  278. $quotes[] = "'";
  279. } else {
  280. $quotes[] = $quote;
  281. }
  282. foreach ($quotes as $quote) {
  283. if (substr($quoted_string, 0, 1) === $quote
  284. && substr($quoted_string, -1, 1) === $quote
  285. ) {
  286. $unquoted_string = substr($quoted_string, 1, -1);
  287. // replace escaped quotes
  288. $unquoted_string = str_replace(
  289. $quote . $quote,
  290. $quote,
  291. $unquoted_string
  292. );
  293. return $unquoted_string;
  294. }
  295. }
  296. return $quoted_string;
  297. }
  298. /**
  299. * format sql strings
  300. *
  301. * @param mixed $parsed_sql pre-parsed SQL structure
  302. * @param string $unparsed_sql raw SQL string
  303. *
  304. * @return string the formatted sql
  305. *
  306. * @global array the configuration array
  307. * @global boolean whether the current statement is a multiple one or not
  308. *
  309. * @access public
  310. * @todo move into PMA_Sql
  311. */
  312. function PMA_formatSql($parsed_sql, $unparsed_sql = '')
  313. {
  314. global $cfg;
  315. // Check that we actually have a valid set of parsed data
  316. // well, not quite
  317. // first check for the SQL parser having hit an error
  318. if (PMA_SQP_isError()) {
  319. return htmlspecialchars($parsed_sql['raw']);
  320. }
  321. // then check for an array
  322. if (! is_array($parsed_sql)) {
  323. // We don't so just return the input directly
  324. // This is intended to be used for when the SQL Parser is turned off
  325. $formatted_sql = "<pre>\n";
  326. if ($cfg['SQP']['fmtType'] == 'none' && $unparsed_sql != '') {
  327. $formatted_sql .= $unparsed_sql;
  328. } else {
  329. $formatted_sql .= $parsed_sql;
  330. }
  331. $formatted_sql .= "\n</pre>";
  332. return $formatted_sql;
  333. }
  334. $formatted_sql = '';
  335. switch ($cfg['SQP']['fmtType']) {
  336. case 'none':
  337. if ($unparsed_sql != '') {
  338. $formatted_sql = '<span class="inner_sql"><pre>' . "\n"
  339. . PMA_SQP_formatNone(array('raw' => $unparsed_sql)) . "\n"
  340. . '</pre></span>';
  341. } else {
  342. $formatted_sql = PMA_SQP_formatNone($parsed_sql);
  343. }
  344. break;
  345. case 'html':
  346. $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'color');
  347. break;
  348. case 'text':
  349. $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'text');
  350. break;
  351. default:
  352. break;
  353. } // end switch
  354. return $formatted_sql;
  355. } // end of the "PMA_formatSql()" function
  356. /**
  357. * Displays a link to the official MySQL documentation
  358. *
  359. * @param string $chapter chapter of "HTML, one page per chapter" documentation
  360. * @param string $link contains name of page/anchor that is being linked
  361. * @param bool $big_icon whether to use big icon (like in left frame)
  362. * @param string $anchor anchor to page part
  363. * @param bool $just_open whether only the opening <a> tag should be returned
  364. *
  365. * @return string the html link
  366. *
  367. * @access public
  368. */
  369. function PMA_showMySQLDocu($chapter, $link, $big_icon = false, $anchor = '', $just_open = false)
  370. {
  371. global $cfg;
  372. if ($cfg['MySQLManualType'] == 'none' || empty($cfg['MySQLManualBase'])) {
  373. return '';
  374. }
  375. // Fixup for newly used names:
  376. $chapter = str_replace('_', '-', strtolower($chapter));
  377. $link = str_replace('_', '-', strtolower($link));
  378. switch ($cfg['MySQLManualType']) {
  379. case 'chapters':
  380. if (empty($chapter)) {
  381. $chapter = 'index';
  382. }
  383. if (empty($anchor)) {
  384. $anchor = $link;
  385. }
  386. $url = $cfg['MySQLManualBase'] . '/' . $chapter . '.html#' . $anchor;
  387. break;
  388. case 'big':
  389. if (empty($anchor)) {
  390. $anchor = $link;
  391. }
  392. $url = $cfg['MySQLManualBase'] . '#' . $anchor;
  393. break;
  394. case 'searchable':
  395. if (empty($link)) {
  396. $link = 'index';
  397. }
  398. $url = $cfg['MySQLManualBase'] . '/' . $link . '.html';
  399. if (!empty($anchor)) {
  400. $url .= '#' . $anchor;
  401. }
  402. break;
  403. case 'viewable':
  404. default:
  405. if (empty($link)) {
  406. $link = 'index';
  407. }
  408. $mysql = '5.5';
  409. $lang = 'en';
  410. if (defined('PMA_MYSQL_INT_VERSION')) {
  411. if (PMA_MYSQL_INT_VERSION >= 50600) {
  412. $mysql = '5.6';
  413. } else if (PMA_MYSQL_INT_VERSION >= 50500) {
  414. $mysql = '5.5';
  415. } else if (PMA_MYSQL_INT_VERSION >= 50100) {
  416. $mysql = '5.1';
  417. } else {
  418. $mysql = '5.0';
  419. }
  420. }
  421. $url = $cfg['MySQLManualBase'] . '/' . $mysql . '/' . $lang . '/' . $link . '.html';
  422. if (!empty($anchor)) {
  423. $url .= '#' . $anchor;
  424. }
  425. break;
  426. }
  427. $open_link = '<a href="' . PMA_linkURL($url) . '" target="mysql_doc">';
  428. if ($just_open) {
  429. return $open_link;
  430. } elseif ($big_icon) {
  431. return $open_link . PMA_getImage('b_sqlhelp.png', __('Documentation')) . '</a>';
  432. } elseif ($GLOBALS['cfg']['ReplaceHelpImg']) {
  433. return $open_link . PMA_getImage('b_help.png', __('Documentation')) . '</a>';
  434. } else {
  435. return '[' . $open_link . __('Documentation') . '</a>]';
  436. }
  437. } // end of the 'PMA_showMySQLDocu()' function
  438. /**
  439. * Displays a link to the phpMyAdmin documentation
  440. *
  441. * @param string $anchor anchor in documentation
  442. *
  443. * @return string the html link
  444. *
  445. * @access public
  446. */
  447. function PMA_showDocu($anchor)
  448. {
  449. if ($GLOBALS['cfg']['ReplaceHelpImg']) {
  450. return '<a href="Documentation.html#' . $anchor . '" target="documentation">'
  451. . PMA_getImage('b_help.png', __('Documentation'))
  452. . '</a>';
  453. } else {
  454. return '[<a href="Documentation.html#' . $anchor . '" target="documentation">'
  455. . __('Documentation') . '</a>]';
  456. }
  457. } // end of the 'PMA_showDocu()' function
  458. /**
  459. * Displays a link to the PHP documentation
  460. *
  461. * @param string $target anchor in documentation
  462. *
  463. * @return string the html link
  464. *
  465. * @access public
  466. */
  467. function PMA_showPHPDocu($target)
  468. {
  469. $url = PMA_getPHPDocLink($target);
  470. if ($GLOBALS['cfg']['ReplaceHelpImg']) {
  471. return '<a href="' . $url . '" target="documentation">'
  472. . PMA_getImage('b_help.png', __('Documentation'))
  473. . '</a>';
  474. } else {
  475. return '[<a href="' . $url . '" target="documentation">' . __('Documentation') . '</a>]';
  476. }
  477. } // end of the 'PMA_showPHPDocu()' function
  478. /**
  479. * returns HTML for a footnote marker and add the messsage to the footnotes
  480. *
  481. * @param string $message the error message
  482. * @param bool $bbcode
  483. * @param string $type message types
  484. *
  485. * @return string html code for a footnote marker
  486. *
  487. * @access public
  488. */
  489. function PMA_showHint($message, $bbcode = false, $type = 'notice')
  490. {
  491. if ($message instanceof PMA_Message) {
  492. $key = $message->getHash();
  493. $type = $message->getLevel();
  494. } else {
  495. $key = md5($message);
  496. }
  497. if (! isset($GLOBALS['footnotes'][$key])) {
  498. if (empty($GLOBALS['footnotes']) || ! is_array($GLOBALS['footnotes'])) {
  499. $GLOBALS['footnotes'] = array();
  500. }
  501. $nr = count($GLOBALS['footnotes']) + 1;
  502. $GLOBALS['footnotes'][$key] = array(
  503. 'note' => $message,
  504. 'type' => $type,
  505. 'nr' => $nr,
  506. );
  507. } else {
  508. $nr = $GLOBALS['footnotes'][$key]['nr'];
  509. }
  510. if ($bbcode) {
  511. return '[sup]' . $nr . '[/sup]';
  512. }
  513. // footnotemarker used in js/tooltip.js
  514. return '<sup class="footnotemarker">' . $nr . '</sup>' .
  515. PMA_getImage('b_help.png', '', array('class' => 'footnotemarker footnote_' . $nr));
  516. }
  517. /**
  518. * Displays a MySQL error message in the right frame.
  519. *
  520. * @param string $error_message the error message
  521. * @param string $the_query the sql query that failed
  522. * @param bool $is_modify_link whether to show a "modify" link or not
  523. * @param string $back_url the "back" link url (full path is not required)
  524. * @param bool $exit EXIT the page?
  525. *
  526. * @global string the curent table
  527. * @global string the current db
  528. *
  529. * @access public
  530. */
  531. function PMA_mysqlDie($error_message = '', $the_query = '',
  532. $is_modify_link = true, $back_url = '', $exit = true)
  533. {
  534. global $table, $db;
  535. /**
  536. * start http output, display html headers
  537. */
  538. include_once './libraries/header.inc.php';
  539. $error_msg_output = '';
  540. if (!$error_message) {
  541. $error_message = PMA_DBI_getError();
  542. }
  543. if (!$the_query && !empty($GLOBALS['sql_query'])) {
  544. $the_query = $GLOBALS['sql_query'];
  545. }
  546. // --- Added to solve bug #641765
  547. if (!function_exists('PMA_SQP_isError') || PMA_SQP_isError()) {
  548. $formatted_sql = htmlspecialchars($the_query);
  549. } elseif (empty($the_query) || trim($the_query) == '') {
  550. $formatted_sql = '';
  551. } else {
  552. if (strlen($the_query) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
  553. $formatted_sql = htmlspecialchars(substr($the_query, 0, $GLOBALS['cfg']['MaxCharactersInDisplayedSQL'])) . '[...]';
  554. } else {
  555. $formatted_sql = PMA_formatSql(PMA_SQP_parse($the_query), $the_query);
  556. }
  557. }
  558. // ---
  559. $error_msg_output .= "\n" . '<!-- PMA-SQL-ERROR -->' . "\n";
  560. $error_msg_output .= ' <div class="error"><h1>' . __('Error') . '</h1>' . "\n";
  561. // if the config password is wrong, or the MySQL server does not
  562. // respond, do not show the query that would reveal the
  563. // username/password
  564. if (!empty($the_query) && !strstr($the_query, 'connect')) {
  565. // --- Added to solve bug #641765
  566. if (function_exists('PMA_SQP_isError') && PMA_SQP_isError()) {
  567. $error_msg_output .= PMA_SQP_getErrorString() . "\n";
  568. $error_msg_output .= '<br />' . "\n";
  569. }
  570. // ---
  571. // modified to show the help on sql errors
  572. $error_msg_output .= ' <p><strong>' . __('SQL query') . ':</strong>' . "\n";
  573. if (strstr(strtolower($formatted_sql), 'select')) {
  574. // please show me help to the error on select
  575. $error_msg_output .= PMA_showMySQLDocu('SQL-Syntax', 'SELECT');
  576. }
  577. if ($is_modify_link) {
  578. $_url_params = array(
  579. 'sql_query' => $the_query,
  580. 'show_query' => 1,
  581. );
  582. if (strlen($table)) {
  583. $_url_params['db'] = $db;
  584. $_url_params['table'] = $table;
  585. $doedit_goto = '<a href="tbl_sql.php' . PMA_generate_common_url($_url_params) . '">';
  586. } elseif (strlen($db)) {
  587. $_url_params['db'] = $db;
  588. $doedit_goto = '<a href="db_sql.php' . PMA_generate_common_url($_url_params) . '">';
  589. } else {
  590. $doedit_goto = '<a href="server_sql.php' . PMA_generate_common_url($_url_params) . '">';
  591. }
  592. $error_msg_output .= $doedit_goto
  593. . PMA_getIcon('b_edit.png', __('Edit'))
  594. . '</a>';
  595. } // end if
  596. $error_msg_output .= ' </p>' . "\n"
  597. .' <p>' . "\n"
  598. .' ' . $formatted_sql . "\n"
  599. .' </p>' . "\n";
  600. } // end if
  601. if (! empty($error_message)) {
  602. $error_message = preg_replace(
  603. "@((\015\012)|(\015)|(\012)){3,}@",
  604. "\n\n",
  605. $error_message
  606. );
  607. }
  608. // modified to show the help on error-returns
  609. // (now error-messages-server)
  610. $error_msg_output .= '<p>' . "\n"
  611. . ' <strong>' . __('MySQL said: ') . '</strong>'
  612. . PMA_showMySQLDocu('Error-messages-server', 'Error-messages-server')
  613. . "\n"
  614. . '</p>' . "\n";
  615. // The error message will be displayed within a CODE segment.
  616. // To preserve original formatting, but allow wordwrapping,
  617. // we do a couple of replacements
  618. // Replace all non-single blanks with their HTML-counterpart
  619. $error_message = str_replace(' ', '&nbsp;&nbsp;', $error_message);
  620. // Replace TAB-characters with their HTML-counterpart
  621. $error_message = str_replace("\t", '&nbsp;&nbsp;&nbsp;&nbsp;', $error_message);
  622. // Replace linebreaks
  623. $error_message = nl2br($error_message);
  624. $error_msg_output .= '<code>' . "\n"
  625. . $error_message . "\n"
  626. . '</code><br />' . "\n";
  627. $error_msg_output .= '</div>';
  628. $_SESSION['Import_message']['message'] = $error_msg_output;
  629. if ($exit) {
  630. /**
  631. * If in an Ajax request
  632. * - avoid displaying a Back link
  633. * - use PMA_ajaxResponse() to transmit the message and exit
  634. */
  635. if ($GLOBALS['is_ajax_request'] == true) {
  636. PMA_ajaxResponse($error_msg_output, false);
  637. }
  638. if (! empty($back_url)) {
  639. if (strstr($back_url, '?')) {
  640. $back_url .= '&amp;no_history=true';
  641. } else {
  642. $back_url .= '?no_history=true';
  643. }
  644. $_SESSION['Import_message']['go_back_url'] = $back_url;
  645. $error_msg_output .= '<fieldset class="tblFooters">';
  646. $error_msg_output .= '[ <a href="' . $back_url . '">' . __('Back') . '</a> ]';
  647. $error_msg_output .= '</fieldset>' . "\n\n";
  648. }
  649. echo $error_msg_output;
  650. /**
  651. * display footer and exit
  652. */
  653. include './libraries/footer.inc.php';
  654. } else {
  655. echo $error_msg_output;
  656. }
  657. } // end of the 'PMA_mysqlDie()' function
  658. /**
  659. * returns array with tables of given db with extended information and grouped
  660. *
  661. * @param string $db name of db
  662. * @param string $tables name of tables
  663. * @param integer $limit_offset list offset
  664. * @param int|bool $limit_count max tables to return
  665. *
  666. * @return array (recursive) grouped table list
  667. */
  668. function PMA_getTableList($db, $tables = null, $limit_offset = 0, $limit_count = false)
  669. {
  670. $sep = $GLOBALS['cfg']['LeftFrameTableSeparator'];
  671. if (null === $tables) {
  672. $tables = PMA_DBI_get_tables_full($db, false, false, null, $limit_offset, $limit_count);
  673. if ($GLOBALS['cfg']['NaturalOrder']) {
  674. uksort($tables, 'strnatcasecmp');
  675. }
  676. }
  677. if (count($tables) < 1) {
  678. return $tables;
  679. }
  680. $default = array(
  681. 'Name' => '',
  682. 'Rows' => 0,
  683. 'Comment' => '',
  684. 'disp_name' => '',
  685. );
  686. $table_groups = array();
  687. // for blobstreaming - list of blobstreaming tables
  688. // load PMA configuration
  689. $PMA_Config = $GLOBALS['PMA_Config'];
  690. foreach ($tables as $table_name => $table) {
  691. // if BS tables exist
  692. if (PMA_BS_IsHiddenTable($table_name)) {
  693. continue;
  694. }
  695. // check for correct row count
  696. if (null === $table['Rows']) {
  697. // Do not check exact row count here,
  698. // if row count is invalid possibly the table is defect
  699. // and this would break left frame;
  700. // but we can check row count if this is a view or the
  701. // information_schema database
  702. // since PMA_Table::countRecords() returns a limited row count
  703. // in this case.
  704. // set this because PMA_Table::countRecords() can use it
  705. $tbl_is_view = $table['TABLE_TYPE'] == 'VIEW';
  706. if ($tbl_is_view || PMA_is_system_schema($db)) {
  707. $table['Rows'] = PMA_Table::countRecords($db, $table['Name'], false, true);
  708. }
  709. }
  710. // in $group we save the reference to the place in $table_groups
  711. // where to store the table info
  712. if ($GLOBALS['cfg']['LeftFrameDBTree']
  713. && $sep && strstr($table_name, $sep)
  714. ) {
  715. $parts = explode($sep, $table_name);
  716. $group =& $table_groups;
  717. $i = 0;
  718. $group_name_full = '';
  719. $parts_cnt = count($parts) - 1;
  720. while ($i < $parts_cnt
  721. && $i < $GLOBALS['cfg']['LeftFrameTableLevel']) {
  722. $group_name = $parts[$i] . $sep;
  723. $group_name_full .= $group_name;
  724. if (! isset($group[$group_name])) {
  725. $group[$group_name] = array();
  726. $group[$group_name]['is' . $sep . 'group'] = true;
  727. $group[$group_name]['tab' . $sep . 'count'] = 1;
  728. $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
  729. } elseif (! isset($group[$group_name]['is' . $sep . 'group'])) {
  730. $table = $group[$group_name];
  731. $group[$group_name] = array();
  732. $group[$group_name][$group_name] = $table;
  733. unset($table);
  734. $group[$group_name]['is' . $sep . 'group'] = true;
  735. $group[$group_name]['tab' . $sep . 'count'] = 1;
  736. $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
  737. } else {
  738. $group[$group_name]['tab' . $sep . 'count']++;
  739. }
  740. $group =& $group[$group_name];
  741. $i++;
  742. }
  743. } else {
  744. if (! isset($table_groups[$table_name])) {
  745. $table_groups[$table_name] = array();
  746. }
  747. $group =& $table_groups;
  748. }
  749. if ($GLOBALS['cfg']['ShowTooltipAliasTB']
  750. && $GLOBALS['cfg']['ShowTooltipAliasTB'] !== 'nested'
  751. && $table['Comment'] // do not switch if the comment is empty
  752. && $table['Comment'] != 'VIEW' // happens in MySQL 5.1
  753. ) {
  754. // switch tooltip and name
  755. $table['disp_name'] = $table['Comment'];
  756. $table['Comment'] = $table['Name'];
  757. } else {
  758. $table['disp_name'] = $table['Name'];
  759. }
  760. $group[$table_name] = array_merge($default, $table);
  761. }
  762. return $table_groups;
  763. }
  764. /* ----------------------- Set of misc functions ----------------------- */
  765. /**
  766. * Adds backquotes on both sides of a database, table or field name.
  767. * and escapes backquotes inside the name with another backquote
  768. *
  769. * example:
  770. * <code>
  771. * echo PMA_backquote('owner`s db'); // `owner``s db`
  772. *
  773. * </code>
  774. *
  775. * @param mixed $a_name the database, table or field name to "backquote"
  776. * or array of it
  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. function PMA_backquote($a_name, $do_it = true)
  785. {
  786. if (is_array($a_name)) {
  787. foreach ($a_name as &$data) {
  788. $data = PMA_backquote($data, $do_it);
  789. }
  790. return $a_name;
  791. }
  792. if (! $do_it) {
  793. global $PMA_SQPdata_forbidden_word;
  794. if (! in_array(strtoupper($a_name), $PMA_SQPdata_forbidden_word)) {
  795. return $a_name;
  796. }
  797. }
  798. // '0' is also empty for php :-(
  799. if (strlen($a_name) && $a_name !== '*') {
  800. return '`' . str_replace('`', '``', $a_name) . '`';
  801. } else {
  802. return $a_name;
  803. }
  804. } // end of the 'PMA_backquote()' function
  805. /**
  806. * Defines the <CR><LF> value depending on the user OS.
  807. *
  808. * @return string the <CR><LF> value to use
  809. *
  810. * @access public
  811. */
  812. function PMA_whichCrlf()
  813. {
  814. // The 'PMA_USR_OS' constant is defined in "./libraries/Config.class.php"
  815. // Win case
  816. if (PMA_USR_OS == 'Win') {
  817. $the_crlf = "\r\n";
  818. } else {
  819. // Others
  820. $the_crlf = "\n";
  821. }
  822. return $the_crlf;
  823. } // end of the 'PMA_whichCrlf()' function
  824. /**
  825. * Reloads navigation if needed.
  826. *
  827. * @param bool $jsonly prints out pure JavaScript
  828. *
  829. * @access public
  830. */
  831. function PMA_reloadNavigation($jsonly=false)
  832. {
  833. // Reloads the navigation frame via JavaScript if required
  834. if (isset($GLOBALS['reload']) && $GLOBALS['reload']) {
  835. // one of the reasons for a reload is when a table is dropped
  836. // in this case, get rid of the table limit offset, otherwise
  837. // we have a problem when dropping a table on the last page
  838. // and the offset becomes greater than the total number of tables
  839. unset($_SESSION['tmp_user_values']['table_limit_offset']);
  840. echo "\n";
  841. $reload_url = './navigation.php?' . PMA_generate_common_url($GLOBALS['db'], '', '&');
  842. if (!$jsonly) {
  843. echo '<script type="text/javascript">' . PHP_EOL;
  844. }
  845. ?>
  846. //<![CDATA[
  847. if (typeof(window.parent) != 'undefined'
  848. && typeof(window.parent.frame_navigation) != 'undefined'
  849. && window.parent.goTo) {
  850. window.parent.goTo('<?php echo $reload_url; ?>');
  851. }
  852. //]]>
  853. <?php
  854. if (!$jsonly) {
  855. echo '</script>' . PHP_EOL;
  856. }
  857. unset($GLOBALS['reload']);
  858. }
  859. }
  860. /**
  861. * displays the message and the query
  862. * usually the message is the result of the query executed
  863. *
  864. * @param string $message the message to display
  865. * @param string $sql_query the query to display
  866. * @param string $type the type (level) of the message
  867. * @param boolean $is_view is this a message after a VIEW operation?
  868. *
  869. * @return string
  870. *
  871. * @access public
  872. */
  873. function PMA_showMessage($message, $sql_query = null, $type = 'notice', $is_view = false)
  874. {
  875. /*
  876. * PMA_ajaxResponse uses this function to collect the string of HTML generated
  877. * for showing the message. Use output buffering to collect it and return it
  878. * in a string. In some special cases on sql.php, buffering has to be disabled
  879. * and hence we check with $GLOBALS['buffer_message']
  880. */
  881. if ( $GLOBALS['is_ajax_request'] == true && ! isset($GLOBALS['buffer_message']) ) {
  882. ob_start();
  883. }
  884. global $cfg;
  885. if (null === $sql_query) {
  886. if (! empty($GLOBALS['display_query'])) {
  887. $sql_query = $GLOBALS['display_query'];
  888. } elseif ($cfg['SQP']['fmtType'] == 'none' && ! empty($GLOBALS['unparsed_sql'])) {
  889. $sql_query = $GLOBALS['unparsed_sql'];
  890. } elseif (! empty($GLOBALS['sql_query'])) {
  891. $sql_query = $GLOBALS['sql_query'];
  892. } else {
  893. $sql_query = '';
  894. }
  895. }
  896. if (isset($GLOBALS['using_bookmark_message'])) {
  897. $GLOBALS['using_bookmark_message']->display();
  898. unset($GLOBALS['using_bookmark_message']);
  899. }
  900. // Corrects the tooltip text via JS if required
  901. // @todo this is REALLY the wrong place to do this - very unexpected here
  902. if (! $is_view && strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
  903. $tooltip = PMA_Table::sGetToolTip($GLOBALS['db'], $GLOBALS['table']);
  904. $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
  905. echo "\n";
  906. echo '<script type="text/javascript">' . "\n";
  907. echo '//<![CDATA[' . "\n";
  908. echo "if (window.parent.updateTableTitle) window.parent.updateTableTitle('"
  909. . $uni_tbl . "', '" . PMA_jsFormat($tooltip, false) . "');" . "\n";
  910. echo '//]]>' . "\n";
  911. echo '</script>' . "\n";
  912. } // end if ... elseif
  913. // Checks if the table needs to be repaired after a TRUNCATE query.
  914. // @todo what about $GLOBALS['display_query']???
  915. // @todo this is REALLY the wrong place to do this - very unexpected here
  916. if (strlen($GLOBALS['table'])
  917. && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])
  918. ) {
  919. if (PMA_Table::sGetStatusInfo($GLOBALS['db'], $GLOBALS['table'], 'Index_length') > 1024 && !PMA_DRIZZLE) {
  920. PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
  921. }
  922. }
  923. unset($tbl_status);
  924. // In an Ajax request, $GLOBALS['cell_align_left'] may not be defined. Hence,
  925. // check for it's presence before using it
  926. echo '<div id="result_query" align="'
  927. . ( isset($GLOBALS['cell_align_left']) ? $GLOBALS['cell_align_left'] : '' )
  928. . '">' . "\n";
  929. if ($message instanceof PMA_Message) {
  930. if (isset($GLOBALS['special_message'])) {
  931. $message->addMessage($GLOBALS['special_message']);
  932. unset($GLOBALS['special_message']);
  933. }
  934. $message->display();
  935. $type = $message->getLevel();
  936. } else {
  937. echo '<div class="' . $type . '">';
  938. echo PMA_sanitize($message);
  939. if (isset($GLOBALS['special_message'])) {
  940. echo PMA_sanitize($GLOBALS['special_message']);
  941. unset($GLOBALS['special_message']);
  942. }
  943. echo '</div>';
  944. }
  945. if ($cfg['ShowSQL'] == true && ! empty($sql_query)) {
  946. // Html format the query to be displayed
  947. // If we want to show some sql code it is easiest to create it here
  948. /* SQL-Parser-Analyzer */
  949. if (! empty($GLOBALS['show_as_php'])) {
  950. $new_line = '\\n"<br />' . "\n"
  951. . '&nbsp;&nbsp;&nbsp;&nbsp;. "';
  952. $query_base = htmlspecialchars(addslashes($sql_query));
  953. $query_base = preg_replace('/((\015\012)|(\015)|(\012))/', $new_line, $query_base);
  954. } else {
  955. $query_base = $sql_query;
  956. }
  957. $query_too_big = false;
  958. if (strlen($query_base) > $cfg['MaxCharactersInDisplayedSQL']) {
  959. // when the query is large (for example an INSERT of binary
  960. // data), the parser chokes; so avoid parsing the query
  961. $query_too_big = true;
  962. $shortened_query_base = nl2br(
  963. htmlspecialchars(
  964. substr($sql_query, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]'
  965. )
  966. );
  967. } elseif (! empty($GLOBALS['parsed_sql'])
  968. && $query_base == $GLOBALS['parsed_sql']['raw']) {
  969. // (here, use "! empty" because when deleting a bookmark,
  970. // $GLOBALS['parsed_sql'] is set but empty
  971. $parsed_sql = $GLOBALS['parsed_sql'];
  972. } else {
  973. // Parse SQL if needed
  974. $parsed_sql = PMA_SQP_parse($query_base);
  975. }
  976. // Analyze it
  977. if (isset($parsed_sql) && ! PMA_SQP_isError()) {
  978. $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
  979. // Same as below (append LIMIT), append the remembered ORDER BY
  980. if ($GLOBALS['cfg']['RememberSorting']
  981. && isset($analyzed_display_query[0]['queryflags']['select_from'])
  982. && isset($GLOBALS['sql_order_to_append'])
  983. ) {
  984. $query_base = $analyzed_display_query[0]['section_before_limit']
  985. . "\n" . $GLOBALS['sql_order_to_append']
  986. . $analyzed_display_query[0]['limit_clause'] . ' '
  987. . $analyzed_display_query[0]['section_after_limit'];
  988. // Need to reparse query
  989. $parsed_sql = PMA_SQP_parse($query_base);
  990. // update the $analyzed_display_query
  991. $analyzed_display_query[0]['section_before_limit'] .= $GLOBALS['sql_order_to_append'];
  992. $analyzed_display_query[0]['order_by_clause'] = $GLOBALS['sorted_col'];
  993. }
  994. // Here we append the LIMIT added for navigation, to
  995. // enable its display. Adding it higher in the code
  996. // to $sql_query would create a problem when
  997. // using the Refresh or Edit links.
  998. // Only append it on SELECTs.
  999. /**
  1000. * @todo what would be the best to do when someone hits Refresh:
  1001. * use the current LIMITs ?
  1002. */
  1003. if (isset($analyzed_display_query[0]['queryflags']['select_from'])
  1004. && isset($GLOBALS['sql_limit_to_append'])
  1005. ) {
  1006. $query_base = $analyzed_display_query[0]['section_before_limit']
  1007. . "\n" . $GLOBALS['sql_limit_to_append']
  1008. . $analyzed_display_query[0]['section_after_limit'];
  1009. // Need to reparse query
  1010. $parsed_sql = PMA_SQP_parse($query_base);
  1011. }
  1012. }
  1013. if (! empty($GLOBALS['show_as_php'])) {
  1014. $query_base = '$sql = "' . $query_base;
  1015. } elseif (! empty($GLOBALS['validatequery'])) {
  1016. try {
  1017. $query_base = PMA_validateSQL($query_base);
  1018. } catch (Exception $e) {
  1019. PMA_Message::error(__('Failed to connect to SQL validator!'))->display();
  1020. }
  1021. } elseif (isset($parsed_sql)) {
  1022. $query_base = PMA_formatSql($parsed_sql, $query_base);
  1023. }
  1024. // Prepares links that may be displayed to edit/explain the query
  1025. // (don't go to default pages, we must go to the page
  1026. // where the query box is available)
  1027. // Basic url query part
  1028. $url_params = array();
  1029. if (! isset($GLOBALS['db'])) {
  1030. $GLOBALS['db'] = '';
  1031. }
  1032. if (strlen($GLOBALS['db'])) {
  1033. $url_params['db'] = $GLOBALS['db'];
  1034. if (strlen($GLOBALS['table'])) {
  1035. $url_params['table'] = $GLOBALS['table'];
  1036. $edit_link = 'tbl_sql.php';
  1037. } else {
  1038. $edit_link = 'db_sql.php';
  1039. }
  1040. } else {
  1041. $edit_link = 'server_sql.php';
  1042. }
  1043. // Want to have the query explained
  1044. // but only explain a SELECT (that has not been explained)
  1045. /* SQL-Parser-Analyzer */
  1046. $explain_link = '';
  1047. $is_select = false;
  1048. if (! empty($cfg['SQLQuery']['Explain']) && ! $query_too_big) {
  1049. $explain_params = $url_params;
  1050. // Detect if we are validating as well
  1051. // To preserve the validate uRL data
  1052. if (! empty($GLOBALS['validatequery'])) {
  1053. $explain_params['validatequery'] = 1;
  1054. }
  1055. if (preg_match('@^SELECT[[:space:]]+@i', $sql_query)) {
  1056. $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
  1057. $_message = __('Explain SQL');
  1058. $is_select = true;
  1059. } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query)) {
  1060. $explain_params['sql_query'] = substr($sql_query, 8);
  1061. $_message = __('Skip Explain SQL');
  1062. }
  1063. if (isset($explain_params['sql_query'])) {
  1064. $explain_link = 'import.php' . PMA_generate_common_url($explain_params);
  1065. $explain_link = ' [' . PMA_linkOrButton($explain_link, $_message) . ']';
  1066. }
  1067. } //show explain
  1068. $url_params['sql_query'] = $sql_query;
  1069. $url_params['show_query'] = 1;
  1070. // even if the query is big and was truncated, offer the chance
  1071. // to edit it (unless it's enormous, see PMA_linkOrButton() )
  1072. if (! empty($cfg['SQLQuery']['Edit'])) {
  1073. if ($cfg['EditInWindow'] == true) {
  1074. $onclick = 'window.parent.focus_querywindow(\''
  1075. . PMA_jsFormat($sql_query, false) . '\'); return false;';
  1076. } else {
  1077. $onclick = '';
  1078. }
  1079. $edit_link .= PMA_generate_common_url($url_params) . '#querybox';
  1080. $edit_link = ' [' . PMA_linkOrButton($edit_link, __('Edit'), array('onclick' => $onclick)) . ']';
  1081. } else {
  1082. $edit_link = '';
  1083. }
  1084. $url_qpart = PMA_generate_common_url($url_params);
  1085. // Also we would like to get the SQL formed in some nice
  1086. // php-code
  1087. if (! empty($cfg['SQLQuery']['ShowAsPHP']) && ! $query_too_big) {
  1088. $php_params = $url_params;
  1089. if (! empty($GLOBALS['show_as_php'])) {
  1090. $_message = __('Without PHP Code');
  1091. } else {
  1092. $php_params['show_as_php'] = 1;
  1093. $_message = __('Create PHP Code');
  1094. }
  1095. $php_link = 'import.php' . PMA_generate_common_url($php_params);
  1096. $php_link = ' [' . PMA_linkOrButton($php_link, $_message) . ']';
  1097. if (isset($GLOBALS['show_as_php'])) {
  1098. $runquery_link = 'import.php' . PMA_generate_common_url($url_params);
  1099. $php_link .= ' [' . PMA_linkOrButton($runquery_link, __('Submit Query')) . ']';
  1100. }
  1101. } else {
  1102. $php_link = '';
  1103. } //show as php
  1104. // Refresh query
  1105. if (! empty($cfg['SQLQuery']['Refresh'])
  1106. && ! isset($GLOBALS['show_as_php']) // 'Submit query' does the same
  1107. && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)
  1108. ) {
  1109. $refresh_link = 'import.php' . PMA_generate_common_url($url_params);
  1110. $refresh_link = ' [' . PMA_linkOrButton($refresh_link, __('Refresh')) . ']';
  1111. } else {
  1112. $refresh_link = '';
  1113. } //refresh
  1114. if (! empty($cfg['SQLValidator']['use'])
  1115. && ! empty($cfg['SQLQuery']['Validate'])
  1116. ) {
  1117. $validate_params = $url_params;
  1118. if (!empty($GLOBALS['validatequery'])) {
  1119. $validate_message = __('Skip Validate SQL');
  1120. } else {
  1121. $validate_params['validatequery'] = 1;
  1122. $validate_message = __('Validate SQL');
  1123. }
  1124. $validate_link = 'import.php' . PMA_generate_common_url($validate_params);
  1125. $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
  1126. } else {
  1127. $validate_link = '';
  1128. } //validator
  1129. if (!empty($GLOBALS['validatequery'])) {
  1130. echo '<div class="sqlvalidate">';
  1131. } else {
  1132. echo '<code class="sql">';
  1133. }
  1134. if ($query_too_big) {
  1135. echo $shortened_query_base;
  1136. } else {
  1137. echo $query_base;
  1138. }
  1139. //Clean up the end of the PHP
  1140. if (! empty($GLOBALS['show_as_php'])) {
  1141. echo '";';
  1142. }
  1143. if (!empty($GLOBALS['validatequery'])) {
  1144. echo '</div>';
  1145. } else {
  1146. echo '</code>';
  1147. }
  1148. echo '<div class="tools">';
  1149. // avoid displaying a Profiling checkbox that could
  1150. // be checked, which would reexecute an INSERT, for example
  1151. if (! empty($refresh_link)) {
  1152. PMA_profilingCheckbox($sql_query);
  1153. }
  1154. // if needed, generate an invisible form that contains controls for the
  1155. // Inline link; this way, the behavior of the Inline link does not
  1156. // depend on the profiling support or on the refresh link
  1157. if (empty($refresh_link) || ! PMA_profilingSupported()) {
  1158. echo '<form action="sql.php" method="post">';
  1159. echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
  1160. echo '<input type="hidden" name="sql_query" value="'
  1161. . htmlspecialchars($sql_query) . '" />';
  1162. echo '</form>';
  1163. }
  1164. // in the tools div, only display the Inline link when not in ajax
  1165. // mode because 1) it currently does not work and 2) we would
  1166. // have two similar mechanisms on the page for the same goal
  1167. if ($is_select
  1168. || $GLOBALS['is_ajax_request'] === false
  1169. && ! $query_too_big
  1170. ) {
  1171. // see in js/functions.js the jQuery code attached to id inline_edit
  1172. // document.write conflicts with jQuery, hence used $().append()
  1173. echo "<script type=\"text/javascript\">\n" .
  1174. "//<![CDATA[\n" .
  1175. "$('.tools form').last().after('[<a href=\"#\" title=\"" .
  1176. PMA_escapeJsString(__('Inline edit of this query')) .
  1177. "\" class=\"inline_edit_sql\">" .
  1178. PMA_escapeJsString(_pgettext('Inline edit query', 'Inline')) .
  1179. "</a>]');\n" .
  1180. "//]]>\n" .
  1181. "</script>";
  1182. }
  1183. echo $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
  1184. echo '</div>';
  1185. }
  1186. echo '</div>';
  1187. if ($GLOBALS['is_ajax_request'] === false) {
  1188. echo '<br class="clearfloat" />';
  1189. }
  1190. // If we are in an Ajax request, we have most probably been called in
  1191. // PMA_ajaxResponse(). Hence, collect the buffer contents and return it
  1192. // to PMA_ajaxResponse(), which will encode it for JSON.
  1193. if ($GLOBALS['is_ajax_request'] == true
  1194. && ! isset($GLOBALS['buffer_message'])
  1195. ) {
  1196. $buffer_contents = ob_get_contents();
  1197. ob_end_clean();
  1198. return $buffer_contents;
  1199. }
  1200. return null;
  1201. } // end of the 'PMA_showMessage()' function
  1202. /**
  1203. * Verifies if current MySQL server supports profiling
  1204. *
  1205. * @access public
  1206. *
  1207. * @return boolean whether profiling is supported
  1208. */
  1209. function PMA_profilingSupported()
  1210. {
  1211. if (! PMA_cacheExists('profiling_supported', true)) {
  1212. // 5.0.37 has profiling but for example, 5.1.20 does not
  1213. // (avoid a trip to the server for MySQL before 5.0.37)
  1214. // and do not set a constant as we might be switching servers
  1215. if (defined('PMA_MYSQL_INT_VERSION')
  1216. && PMA_MYSQL_INT_VERSION >= 50037
  1217. && PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'profiling'")
  1218. ) {
  1219. PMA_cacheSet('profiling_supported', true, true);
  1220. } else {
  1221. PMA_cacheSet('profiling_supported', false, true);
  1222. }
  1223. }
  1224. return PMA_cacheGet('profiling_supported', true);
  1225. }
  1226. /**
  1227. * Displays a form with the Profiling checkbox
  1228. *
  1229. * @param string $sql_query sql query
  1230. *
  1231. * @access public
  1232. */
  1233. function PMA_profilingCheckbox($sql_query)
  1234. {
  1235. if (PMA_profilingSupported()) {
  1236. echo '<form action="sql.php" method="post">' . "\n";
  1237. echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
  1238. echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />' . "\n";
  1239. echo '<input type="hidden" name="profiling_form" value="1" />' . "\n";
  1240. PMA_display_html_checkbox('profiling', __('Profiling'), isset($_SESSION['profiling']), true);
  1241. echo '<noscript><input type="submit" value="' . __('Go') . '" /></noscript>' . "\n";
  1242. echo '</form>' . "\n";
  1243. }
  1244. }
  1245. /**
  1246. * Formats $value to byte view
  1247. *
  1248. * @param double $value the value to format
  1249. * @param int $limes the sensitiveness
  1250. * @param int $comma the number of decimals to retain
  1251. *
  1252. * @return array the formatted value and its unit
  1253. *
  1254. * @access public
  1255. */
  1256. function PMA_formatByteDown($value, $limes = 6, $comma = 0)
  1257. {
  1258. if ($value === null) {
  1259. return null;
  1260. }
  1261. $byteUnits = array(
  1262. /* l10n: shortcuts for Byte */
  1263. __('B'),
  1264. /* l10n: shortcuts for Kilobyte */
  1265. __('KiB'),
  1266. /* l10n: shortcuts for Megabyte */
  1267. __('MiB'),
  1268. /* l10n: shortcuts for Gigabyte */
  1269. __('GiB'),
  1270. /* l10n: shortcuts for Terabyte */
  1271. __('TiB'),
  1272. /* l10n: shortcuts for Petabyte */
  1273. __('PiB'),
  1274. /* l10n: shortcuts for Exabyte */
  1275. __('EiB')
  1276. );
  1277. $dh = PMA_pow(10, $comma);
  1278. $li = PMA_pow(10, $limes);
  1279. $unit = $byteUnits[0];
  1280. for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
  1281. if (isset($byteUnits[$d]) && $value >= $li * PMA_pow(10, $ex)) {
  1282. // use 1024.0 to avoid integer overflow on 64-bit machines
  1283. $value = round($value / (PMA_pow(1024, $d) / $dh)) /$dh;
  1284. $unit = $byteUnits[$d];
  1285. break 1;
  1286. } // end if
  1287. } // end for
  1288. if ($unit != $byteUnits[0]) {
  1289. // if the unit is not bytes (as represented in current language)
  1290. // reformat with max length of 5
  1291. // 4th parameter=true means do not reformat if value < 1
  1292. $return_value = PMA_formatNumber($value, 5, $comma, true);
  1293. } else {
  1294. // do not reformat, just handle the locale
  1295. $return_value = PMA_formatNumber($value, 0);
  1296. }
  1297. return array(trim($return_value), $unit);
  1298. } // end of the 'PMA_formatByteDown' function
  1299. /**
  1300. * Changes thousands and decimal separators to locale specific values.
  1301. *
  1302. * @param string $value the value
  1303. *
  1304. * @return string
  1305. */
  1306. function PMA_localizeNumber($value)
  1307. {
  1308. return str_replace(
  1309. array(',', '.'),
  1310. array(
  1311. /* l10n: Thousands separator */
  1312. __(','),
  1313. /* l10n: Decimal separator */
  1314. __('.'),
  1315. ),
  1316. $value
  1317. );
  1318. }
  1319. /**
  1320. * Formats $value to the given length and appends SI prefixes
  1321. * with a $length of 0 no truncation occurs, number is only formated
  1322. * to the current locale
  1323. *
  1324. * examples:
  1325. * <code>
  1326. * echo PMA_formatNumber(123456789, 6); // 123,457 k
  1327. * echo PMA_formatNumber(-123456789, 4, 2); // -123.46 M
  1328. * echo PMA_formatNumber(-0.003, 6); // -3 m
  1329. * echo PMA_formatNumber(0.003, 3, 3); // 0.003
  1330. * echo PMA_formatNumber(0.00003, 3, 2); // 0.03 m
  1331. * echo PMA_formatNumber(0, 6); // 0
  1332. * </code>
  1333. *
  1334. * @param double $value the value to format
  1335. * @param integer $digits_left number of digits left of the comma
  1336. * @param integer $digits_right number of digits right of the comma
  1337. * @param boolean $only_down do not reformat numbers below 1
  1338. * @param boolean $noTrailingZero removes trailing zeros right of the comma
  1339. * (default: true)
  1340. *
  1341. * @return string the formatted value and its unit
  1342. *
  1343. * @access public
  1344. */
  1345. function PMA_formatNumber($value, $digits_left = 3, $digits_right = 0,
  1346. $only_down = false, $noTrailingZero = true)
  1347. {
  1348. if ($value==0) {
  1349. return '0';
  1350. }
  1351. $originalValue = $value;
  1352. //number_format is not multibyte safe, str_replace is safe
  1353. if ($digits_left === 0) {
  1354. $value = number_format($value, $digits_right);
  1355. if ($originalValue != 0 && floatval($value) == 0) {
  1356. $value = ' <' . (1 / PMA_pow(10, $digits_right));
  1357. }
  1358. return PMA_localizeNumber($value);
  1359. }
  1360. // this units needs no translation, ISO
  1361. $units = array(
  1362. -8 => 'y',
  1363. -7 => 'z',
  1364. -6 => 'a',
  1365. -5 => 'f',
  1366. -4 => 'p',
  1367. -3 => 'n',
  1368. -2 => '&micro;',
  1369. -1 => 'm',
  1370. 0 => ' ',
  1371. 1 => 'k',
  1372. 2 => 'M',
  1373. 3 => 'G',
  1374. 4 => 'T',
  1375. 5 => 'P',
  1376. 6 => 'E',
  1377. 7 => 'Z',
  1378. 8 => 'Y'
  1379. );
  1380. // check for negative value to retain sign
  1381. if ($value < 0) {
  1382. $sign = '-';
  1383. $value = abs($value);
  1384. } else {
  1385. $sign = '';
  1386. }
  1387. $dh = PMA_pow(10, $digits_right);
  1388. /*
  1389. * This gives us the right SI prefix already,
  1390. * but $digits_left parameter not incorporated
  1391. */
  1392. $d = floor(log10($value) / 3);
  1393. /*
  1394. * Lowering the SI prefix by 1 gives us an additional 3 zeros
  1395. * So if we have 3,6,9,12.. free digits ($digits_left - $cur_digits)
  1396. * to use, then lower the SI prefix
  1397. */
  1398. $cur_digits = floor(log10($value / PMA_pow(1000, $d, 'pow'))+1);
  1399. if ($digits_left > $cur_digits) {
  1400. $d-= floor(($digits_left - $cur_digits)/3);
  1401. }
  1402. if ($d<0 && $only_down) {
  1403. $d=0;
  1404. }
  1405. $value = round($value / (PMA_pow(1000, $d, 'pow') / $dh)) /$dh;
  1406. $unit = $units[$d];
  1407. // If we dont want any zeros after the comma just add the thousand seperator
  1408. if ($noTrailingZero) {
  1409. $value = PMA_localizeNumber(
  1410. preg_replace('/(?<=\d)(?=(\d{3})+(?!\d))/', ',', $value)
  1411. );
  1412. } else {
  1413. //number_format is not multibyte safe, str_replace is safe
  1414. $value = PMA_localizeNumber(number_format($value, $digits_right));
  1415. }
  1416. if ($originalValue!=0 && floatval($value) == 0) {
  1417. return ' <' . (1 / PMA_pow(10, $digits_right)) . ' ' . $unit;
  1418. }
  1419. return $sign . $value . ' ' . $unit;
  1420. } // end of the 'PMA_formatNumber' function
  1421. /**
  1422. * Returns the number of bytes when a formatted size is given
  1423. *
  1424. * @param string $formatted_size the size expression (for example 8MB)
  1425. *
  1426. * @return integer The numerical part of the expression (for example 8)
  1427. */
  1428. function PMA_extractValueFromFormattedSize($formatted_size)
  1429. {
  1430. $return_value = -1;
  1431. if (preg_match('/^[0-9]+GB$/', $formatted_size)) {
  1432. $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 3);
  1433. } elseif (preg_match('/^[0-9]+MB$/', $formatted_size)) {
  1434. $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 2);
  1435. } elseif (preg_match('/^[0-9]+K$/', $formatted_size)) {
  1436. $return_value = substr($formatted_size, 0, -1) * PMA_pow(1024, 1);
  1437. }
  1438. return $return_value;
  1439. }// end of the 'PMA_extractValueFromFormattedSize' function
  1440. /**
  1441. * Writes localised date
  1442. *
  1443. * @param string $timestamp the current timestamp
  1444. * @param string $format format
  1445. *
  1446. * @return string the formatted date
  1447. *
  1448. * @access public
  1449. */
  1450. function PMA_localisedDate($timestamp = -1, $format = '')
  1451. {
  1452. $month = array(
  1453. /* l10n: Short month name */
  1454. __('Jan'),
  1455. /* l10n: Short month name */
  1456. __('Feb'),
  1457. /* l10n: Short month name */
  1458. __('Mar'),
  1459. /* l10n: Short month name */
  1460. __('Apr'),
  1461. /* l10n: Short month name */
  1462. _pgettext('Short month name', 'May'),
  1463. /* l10n: Short month name */
  1464. __('Jun'),
  1465. /* l10n: Short month name */
  1466. __('Jul'),
  1467. /* l10n: Short month name */
  1468. __('Aug'),
  1469. /* l10n: Short month name */
  1470. __('Sep'),
  1471. /* l10n: Short month name */
  1472. __('Oct'),
  1473. /* l10n: Short month name */
  1474. __('Nov'),
  1475. /* l10n: Short month name */
  1476. __('Dec'));
  1477. $day_of_week = array(
  1478. /* l10n: Short week day name */
  1479. _pgettext('Short week day name', 'Sun'),
  1480. /* l10n: Short week day name */
  1481. __('Mon'),
  1482. /* l10n: Short week day name */
  1483. __('Tue'),
  1484. /* l10n: Short week day name */
  1485. __('Wed'),
  1486. /* l10n: Short week day name */
  1487. __('Thu'),
  1488. /* l10n: Short week day name */
  1489. __('Fri'),
  1490. /* l10n: Short week day name */
  1491. __('Sat'));
  1492. if ($format == '') {
  1493. /* l10n: See http://www.php.net/manual/en/function.strftime.php */
  1494. $format = __('%B %d, %Y at %I:%M %p');
  1495. }
  1496. if ($timestamp == -1) {
  1497. $timestamp = time();
  1498. }
  1499. $date = preg_replace(
  1500. '@%[aA]@',
  1501. $day_of_week[(int)strftime('%w', $timestamp)],
  1502. $format
  1503. );
  1504. $date = preg_replace(
  1505. '@%[bB]@',
  1506. $month[(int)strftime('%m', $timestamp)-1],
  1507. $date
  1508. );
  1509. return strftime($date, $timestamp);
  1510. } // end of the 'PMA_localisedDate()' function
  1511. /**
  1512. * returns a tab for tabbed navigation.
  1513. * If the variables $link and $args ar left empty, an inactive tab is created
  1514. *
  1515. * @param array $tab array with all options
  1516. * @param array $url_params
  1517. *
  1518. * @return string html code for one tab, a link if valid otherwise a span
  1519. *
  1520. * @access public
  1521. */
  1522. function PMA_generate_html_tab($tab, $url_params = array(), $base_dir='')
  1523. {
  1524. // default values
  1525. $defaults = array(
  1526. 'text' => '',
  1527. 'class' => '',
  1528. 'active' => null,
  1529. 'link' => '',
  1530. 'sep' => '?',
  1531. 'attr' => '',
  1532. 'args' => '',
  1533. 'warning' => '',
  1534. 'fragment' => '',
  1535. 'id' => '',
  1536. );
  1537. $tab = array_merge($defaults, $tab);
  1538. // determine additionnal style-class
  1539. if (empty($tab['class'])) {
  1540. if (! empty($tab['active'])
  1541. || PMA_isValid($GLOBALS['active_page'], 'identical', $tab['link'])
  1542. ) {
  1543. $tab['class'] = 'active';
  1544. } elseif (is_null($tab['active']) && empty($GLOBALS['active_page'])
  1545. && basename($GLOBALS['PMA_PHP_SELF']) == $tab['link']
  1546. && empty($tab['warning'])) {
  1547. $tab['class'] = 'active';
  1548. }
  1549. }
  1550. if (!empty($tab['warning'])) {
  1551. $tab['class'] .= ' error';
  1552. $tab['attr'] .= ' title="' . htmlspecialchars($tab['warning']) . '"';
  1553. }
  1554. // If there are any tab specific URL parameters, merge those with
  1555. // the general URL parameters
  1556. if (! empty($tab['url_params']) && is_array($tab['url_params'])) {
  1557. $url_params = array_merge($url_params, $tab['url_params']);
  1558. }
  1559. // build the link
  1560. if (!empty($tab['link'])) {
  1561. $tab['link'] = htmlentities($tab['link']);
  1562. $tab['link'] = $tab['link'] . PMA_generate_common_url($url_params);
  1563. if (! empty($tab['args'])) {
  1564. foreach ($tab['args'] as $param => $value) {
  1565. $tab['link'] .= PMA_get_arg_separator('html') . urlencode($param)
  1566. . '=' . urlencode($value);
  1567. }
  1568. }
  1569. }
  1570. if (! empty($tab['fragment'])) {
  1571. $tab['link'] .= $tab['fragment'];
  1572. }
  1573. // display icon, even if iconic is disabled but the link-text is missing
  1574. if (($GLOBALS['cfg']['MainPageIconic'] || empty($tab['text']))
  1575. && isset($tab['icon'])
  1576. ) {
  1577. // avoid generating an alt tag, because it only illustrates
  1578. // the text that follows and if browser does not display
  1579. // images, the text is duplicated
  1580. $tab['text'] = PMA_getImage(htmlentities($tab['icon'])) . $tab['text'];
  1581. } elseif (empty($tab['text'])) {
  1582. // check to not display an empty link-text
  1583. $tab['text'] = '?';
  1584. trigger_error(
  1585. 'empty linktext in function ' . __FUNCTION__ . '()',
  1586. E_USER_NOTICE
  1587. );
  1588. }
  1589. //Set the id for the tab, if set in the params
  1590. $id_string = ( empty($tab['id']) ? '' : ' id="'.$tab['id'].'" ' );
  1591. $out = '<li' . ($tab['class'] == 'active' ? ' class="active"' : '') . '>';
  1592. if (!empty($tab['link'])) {
  1593. $out .= '<a class="tab' . htmlentities($tab['class']) . '"'
  1594. .$id_string
  1595. .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
  1596. . $tab['text'] . '</a>';
  1597. } else {
  1598. $out .= '<span class="tab' . htmlentities($tab['class']) . '"'.$id_string.'>'
  1599. . $tab['text'] . '</span>';
  1600. }
  1601. $out .= '</li>';
  1602. return $out;
  1603. } // end of the 'PMA_generate_html_tab()' function
  1604. /**
  1605. * returns html-code for a tab navigation
  1606. *
  1607. * @param array $tabs one element per tab
  1608. * @param string $url_params
  1609. * @param string $base_dir
  1610. * @param string $menu_id
  1611. *
  1612. * @return string html-code for tab-navigation
  1613. */
  1614. function PMA_generate_html_tabs($tabs, $url_params, $base_dir='', $menu_id='topmenu')
  1615. {
  1616. $tab_navigation = '<div id="' . htmlentities($menu_id) . 'container" class="menucontainer">'
  1617. .'<ul id="' . htmlentities($menu_id) . '">';
  1618. foreach ($tabs as $tab) {
  1619. $tab_navigation .= PMA_generate_html_tab($tab, $url_params, $base_dir);
  1620. }
  1621. $tab_navigation .=
  1622. '</ul>' . "\n"
  1623. .'<div class="clearfloat"></div>'
  1624. .'</div>' . "\n";
  1625. return $tab_navigation;
  1626. }
  1627. /**
  1628. * Displays a link, or a button if the link's URL is too large, to
  1629. * accommodate some browsers' limitations
  1630. *
  1631. * @param string $url the URL
  1632. * @param string $message the link message
  1633. * @param mixed $tag_params string: js confirmation
  1634. * array: additional tag params (f.e. style="")
  1635. * @param boolean $new_form we set this to false when we are already in
  1636. * a form, to avoid generating nested forms
  1637. * @param boolean $strip_img whether to strip the image
  1638. * @param string $target target
  1639. *
  1640. * @return string the results to be echoed or saved in an array
  1641. */
  1642. function PMA_linkOrButton($url, $message, $tag_params = array(),
  1643. $new_form = true, $strip_img = false, $target = '')
  1644. {
  1645. $url_length = strlen($url);
  1646. // with this we should be able to catch case of image upload
  1647. // into a (MEDIUM) BLOB; not worth generating even a form for these
  1648. if ($url_length > $GLOBALS['cfg']['LinkLengthLimit'] * 100) {
  1649. return '';
  1650. }
  1651. if (! is_array($tag_params)) {
  1652. $tmp = $tag_params;
  1653. $tag_params = array();
  1654. if (!empty($tmp)) {
  1655. $tag_params['onclick'] = 'return confirmLink(this, \'' . PMA_escapeJsString($tmp) . '\')';
  1656. }
  1657. unset($tmp);
  1658. }
  1659. if (! empty($target)) {
  1660. $tag_params['target'] = htmlentities($target);
  1661. }
  1662. $tag_params_strings = array();
  1663. foreach ($tag_params as $par_name => $par_value) {
  1664. // htmlspecialchars() only on non javascript
  1665. $par_value = substr($par_name, 0, 2) == 'on'
  1666. ? $par_value
  1667. : htmlspecialchars($par_value);
  1668. $tag_params_strings[] = $par_name . '="' . $par_value . '"';
  1669. }
  1670. $displayed_message = '';
  1671. // Add text if not already added
  1672. if (stristr($message, '<img')
  1673. && (!$strip_img || $GLOBALS['cfg']['PropertiesIconic'] === true)
  1674. && strip_tags($message)==$message
  1675. ) {
  1676. $displayed_message = '<span>'
  1677. . htmlspecialchars(
  1678. preg_replace('/^.*\salt="([^"]*)".*$/si', '\1', $message)
  1679. )
  1680. . '</span>';
  1681. }
  1682. // Suhosin: Check that each query parameter is not above maximum
  1683. $in_suhosin_limits = true;
  1684. if ($url_length <= $GLOBALS['cfg']['LinkLengthLimit']) {
  1685. if ($suhosin_get_MaxValueLength = ini_get('suhosin.get.max_value_length')) {
  1686. $query_parts = PMA_splitURLQuery($url);
  1687. foreach ($query_parts as $query_pair) {
  1688. list($eachvar, $eachval) = explode('=', $query_pair);
  1689. if (strlen($eachval) > $suhosin_get_MaxValueLength) {
  1690. $in_suhosin_limits = false;
  1691. break;
  1692. }
  1693. }
  1694. }
  1695. }
  1696. if ($url_length <= $GLOBALS['cfg']['LinkLengthLimit'] && $in_suhosin_limits) {
  1697. // no whitespace within an <a> else Safari will make it part of the link
  1698. $ret = "\n" . '<a href="' . $url . '" '
  1699. . implode(' ', $tag_params_strings) . '>'
  1700. . $message . $displayed_message . '</a>' . "\n";
  1701. } else {
  1702. // no spaces (linebreaks) at all
  1703. // or after the hidden fields
  1704. // IE will display them all
  1705. // add class=link to submit button
  1706. if (empty($tag_params['class'])) {
  1707. $tag_params['class'] = 'link';
  1708. }
  1709. if (! isset($query_parts)) {
  1710. $query_parts = PMA_splitURLQuery($url);
  1711. }
  1712. $url_parts = parse_url($url);
  1713. if ($new_form) {
  1714. $ret = '<form action="' . $url_parts['path'] . '" class="link"'
  1715. . ' method="post"' . $target . ' style="display: inline;">';
  1716. $subname_open = '';
  1717. $subname_close = '';
  1718. $submit_link = '#';
  1719. } else {
  1720. $query_parts[] = 'redirect=' . $url_parts['path'];
  1721. if (empty($GLOBALS['subform_counter'])) {
  1722. $GLOBALS['subform_counter'] = 0;
  1723. }
  1724. $GLOBALS['subform_counter']++;
  1725. $ret = '';
  1726. $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
  1727. $subname_close = ']';
  1728. $submit_link = '#usesubform[' . $GLOBALS['subform_counter'] . ']=1';
  1729. }
  1730. foreach ($query_parts as $query_pair) {
  1731. list($eachvar, $eachval) = explode('=', $query_pair);
  1732. $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
  1733. . $subname_close . '" value="'
  1734. . htmlspecialchars(urldecode($eachval)) . '" />';
  1735. } // end while
  1736. $ret .= "\n" . '<a href="' . $submit_link . '" class="formLinkSubmit" '
  1737. . implode(' ', $tag_params_strings) . '>'
  1738. . $message . ' ' . $displayed_message . '</a>' . "\n";
  1739. if ($new_form) {
  1740. $ret .= '</form>';
  1741. }
  1742. } // end if... else...
  1743. return $ret;
  1744. } // end of the 'PMA_linkOrButton()' function
  1745. /**
  1746. * Splits a URL string by parameter
  1747. *
  1748. * @param string $url the URL
  1749. *
  1750. * @return array the parameter/value pairs, for example [0] db=sakila
  1751. */
  1752. function PMA_splitURLQuery($url)
  1753. {
  1754. // decode encoded url separators
  1755. $separator = PMA_get_arg_separator();
  1756. // on most places separator is still hard coded ...
  1757. if ($separator !== '&') {
  1758. // ... so always replace & with $separator
  1759. $url = str_replace(htmlentities('&'), $separator, $url);
  1760. $url = str_replace('&', $separator, $url);
  1761. }
  1762. $url = str_replace(htmlentities($separator), $separator, $url);
  1763. // end decode
  1764. $url_parts = parse_url($url);
  1765. return explode($separator, $url_parts['query']);
  1766. }
  1767. /**
  1768. * Returns a given timespan value in a readable format.
  1769. *
  1770. * @param int $seconds the timespan
  1771. *
  1772. * @return string the formatted value
  1773. */
  1774. function PMA_timespanFormat($seconds)
  1775. {
  1776. $days = floor($seconds / 86400);
  1777. if ($days > 0) {
  1778. $seconds -= $days * 86400;
  1779. }
  1780. $hours = floor($seconds / 3600);
  1781. if ($days > 0 || $hours > 0) {
  1782. $seconds -= $hours * 3600;
  1783. }
  1784. $minutes = floor($seconds / 60);
  1785. if ($days > 0 || $hours > 0 || $minutes > 0) {
  1786. $seconds -= $minutes * 60;
  1787. }
  1788. return sprintf(
  1789. __('%s days, %s hours, %s minutes and %s seconds'),
  1790. (string)$days, (string)$hours, (string)$minutes, (string)$seconds
  1791. );
  1792. }
  1793. /**
  1794. * Takes a string and outputs each character on a line for itself. Used
  1795. * mainly for horizontalflipped display mode.
  1796. * Takes care of special html-characters.
  1797. * Fulfills todo-item
  1798. * http://sf.net/tracker/?func=detail&aid=544361&group_id=23067&atid=377411
  1799. *
  1800. * @param string $string The string
  1801. * @param string $Separator The Separator (defaults to "<br />\n")
  1802. *
  1803. * @access public
  1804. * @todo add a multibyte safe function PMA_STR_split()
  1805. *
  1806. * @return string The flipped string
  1807. */
  1808. function PMA_flipstring($string, $Separator = "<br />\n")
  1809. {
  1810. $format_string = '';
  1811. $charbuff = false;
  1812. for ($i = 0, $str_len = strlen($string); $i < $str_len; $i++) {
  1813. $char = $string{$i};
  1814. $append = false;
  1815. if ($char == '&') {
  1816. $format_string .= $charbuff;
  1817. $charbuff = $char;
  1818. } elseif ($char == ';' && !empty($charbuff)) {
  1819. $format_string .= $charbuff . $char;
  1820. $charbuff = false;
  1821. $append = true;
  1822. } elseif (! empty($charbuff)) {
  1823. $charbuff .= $char;
  1824. } else {
  1825. $format_string .= $char;
  1826. $append = true;
  1827. }
  1828. // do not add separator after the last character
  1829. if ($append && ($i != $str_len - 1)) {
  1830. $format_string .= $Separator;
  1831. }
  1832. }
  1833. return $format_string;
  1834. }
  1835. /**
  1836. * Function added to avoid path disclosures.
  1837. * Called by each script that needs parameters, it displays
  1838. * an error message and, by default, stops the execution.
  1839. *
  1840. * Not sure we could use a strMissingParameter message here,
  1841. * would have to check if the error message file is always available
  1842. *
  1843. * @param array $params The names of the parameters needed by the calling script.
  1844. * @param bool $die Stop the execution?
  1845. * (Set this manually to false in the calling script
  1846. * until you know all needed parameters to check).
  1847. * @param bool $request Whether to include this list in checking for special params.
  1848. *
  1849. * @global string path to current script
  1850. * @global boolean flag whether any special variable was required
  1851. *
  1852. * @access public
  1853. * @todo use PMA_fatalError() if $die === true?
  1854. */
  1855. function PMA_checkParameters($params, $die = true, $request = true)
  1856. {
  1857. global $checked_special;
  1858. if (! isset($checked_special)) {
  1859. $checked_special = false;
  1860. }
  1861. $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
  1862. $found_error = false;
  1863. $error_message = '';
  1864. foreach ($params as $param) {
  1865. if ($request && $param != 'db' && $param != 'table') {
  1866. $checked_special = true;
  1867. }
  1868. if (! isset($GLOBALS[$param])) {
  1869. $error_message .= $reported_script_name
  1870. . ': ' . __('Missing parameter:') . ' '
  1871. . $param
  1872. . PMA_showDocu('faqmissingparameters')
  1873. . '<br />';
  1874. $found_error = true;
  1875. }
  1876. }
  1877. if ($found_error) {
  1878. /**
  1879. * display html meta tags
  1880. */
  1881. include_once './libraries/header_meta_style.inc.php';
  1882. echo '</head><body><p>' . $error_message . '</p></body></html>';
  1883. if ($die) {
  1884. exit();
  1885. }
  1886. }
  1887. } // end function
  1888. /**
  1889. * Function to generate unique condition for specified row.
  1890. *
  1891. * @param resource $handle current query result
  1892. * @param integer $fields_cnt number of fields
  1893. * @param array $fields_meta meta information about fields
  1894. * @param array $row current row
  1895. * @param boolean $force_unique generate condition only on pk or unique
  1896. *
  1897. * @access public
  1898. *
  1899. * @return array the calculated condition and whether condition is unique
  1900. */
  1901. function PMA_getUniqueCondition($handle, $fields_cnt, $fields_meta, $row, $force_unique = false)
  1902. {
  1903. $primary_key = '';
  1904. $unique_key = '';
  1905. $nonprimary_condition = '';
  1906. $preferred_condition = '';
  1907. $primary_key_array = array();
  1908. $unique_key_array = array();
  1909. $nonprimary_condition_array = array();
  1910. $condition_array = array();
  1911. for ($i = 0; $i < $fields_cnt; ++$i) {
  1912. $condition = '';
  1913. $con_key = '';
  1914. $con_val = '';
  1915. $field_flags = PMA_DBI_field_flags($handle, $i);
  1916. $meta = $fields_meta[$i];
  1917. // do not use a column alias in a condition
  1918. if (! isset($meta->orgname) || ! strlen($meta->orgname)) {
  1919. $meta->orgname = $meta->name;
  1920. if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
  1921. && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])
  1922. ) {
  1923. foreach ($GLOBALS['analyzed_sql'][0]['select_expr'] as $select_expr) {
  1924. // need (string) === (string)
  1925. // '' !== 0 but '' == 0
  1926. if ((string) $select_expr['alias'] === (string) $meta->name) {
  1927. $meta->orgname = $select_expr['column'];
  1928. break;
  1929. } // end if
  1930. } // end foreach
  1931. }
  1932. }
  1933. // Do not use a table alias in a condition.
  1934. // Test case is:
  1935. // select * from galerie x WHERE
  1936. //(select count(*) from galerie y where y.datum=x.datum)>1
  1937. //
  1938. // But orgtable is present only with mysqli extension so the
  1939. // fix is only for mysqli.
  1940. // Also, do not use the original table name if we are dealing with
  1941. // a view because this view might be updatable.
  1942. // (The isView() verification should not be costly in most cases
  1943. // because there is some caching in the function).
  1944. if (isset($meta->orgtable)
  1945. && $meta->table != $meta->orgtable
  1946. && ! PMA_Table::isView($GLOBALS['db'], $meta->table)
  1947. ) {
  1948. $meta->table = $meta->orgtable;
  1949. }
  1950. // to fix the bug where float fields (primary or not)
  1951. // can't be matched because of the imprecision of
  1952. // floating comparison, use CONCAT
  1953. // (also, the syntax "CONCAT(field) IS NULL"
  1954. // that we need on the next "if" will work)
  1955. if ($meta->type == 'real') {
  1956. $con_key = 'CONCAT(' . PMA_backquote($meta->table) . '.'
  1957. . PMA_backquote($meta->orgname) . ')';
  1958. } else {
  1959. $con_key = PMA_backquote($meta->table) . '.'
  1960. . PMA_backquote($meta->orgname);
  1961. } // end if... else...
  1962. $condition = ' ' . $con_key . ' ';
  1963. if (! isset($row[$i]) || is_null($row[$i])) {
  1964. $con_val = 'IS NULL';
  1965. } else {
  1966. // timestamp is numeric on some MySQL 4.1
  1967. // for real we use CONCAT above and it should compare to string
  1968. if ($meta->numeric
  1969. && $meta->type != 'timestamp'
  1970. && $meta->type != 'real'
  1971. ) {
  1972. $con_val = '= ' . $row[$i];
  1973. } elseif (($meta->type == 'blob' || $meta->type == 'string')
  1974. // hexify only if this is a true not empty BLOB or a BINARY
  1975. && stristr($field_flags, 'BINARY')
  1976. && !empty($row[$i])) {
  1977. // do not waste memory building a too big condition
  1978. if (strlen($row[$i]) < 1000) {
  1979. // use a CAST if possible, to avoid problems
  1980. // if the field contains wildcard characters % or _
  1981. $con_val = '= CAST(0x' . bin2hex($row[$i]) . ' AS BINARY)';
  1982. } else {
  1983. // this blob won't be part of the final condition
  1984. $con_val = null;
  1985. }
  1986. } elseif (in_array($meta->type, PMA_getGISDatatypes())
  1987. && ! empty($row[$i])
  1988. ) {
  1989. // do not build a too big condition
  1990. if (strlen($row[$i]) < 5000) {
  1991. $condition .= '=0x' . bin2hex($row[$i]) . ' AND';
  1992. } else {
  1993. $condition = '';
  1994. }
  1995. } elseif ($meta->type == 'bit') {
  1996. $con_val = "= b'" . PMA_printable_bit_value($row[$i], $meta->length) . "'";
  1997. } else {
  1998. $con_val = '= \'' . PMA_sqlAddSlashes($row[$i], false, true) . '\'';
  1999. }
  2000. }
  2001. if ($con_val != null) {
  2002. $condition .= $con_val . ' AND';
  2003. if ($meta->primary_key > 0) {
  2004. $primary_key .= $condition;
  2005. $primary_key_array[$con_key] = $con_val;
  2006. } elseif ($meta->unique_key > 0) {
  2007. $unique_key .= $condition;
  2008. $unique_key_array[$con_key] = $con_val;
  2009. }
  2010. $nonprimary_condition .= $condition;
  2011. $nonprimary_condition_array[$con_key] = $con_val;
  2012. }
  2013. } // end for
  2014. // Correction University of Virginia 19991216:
  2015. // prefer primary or unique keys for condition,
  2016. // but use conjunction of all values if no primary key
  2017. $clause_is_unique = true;
  2018. if ($primary_key) {
  2019. $preferred_condition = $primary_key;
  2020. $condition_array = $primary_key_array;
  2021. } elseif ($unique_key) {
  2022. $preferred_condition = $unique_key;
  2023. $condition_array = $unique_key_array;
  2024. } elseif (! $force_unique) {
  2025. $preferred_condition = $nonprimary_condition;
  2026. $condition_array = $nonprimary_condition_array;
  2027. $clause_is_unique = false;
  2028. }
  2029. $where_clause = trim(preg_replace('|\s?AND$|', '', $preferred_condition));
  2030. return(array($where_clause, $clause_is_unique, $condition_array));
  2031. } // end function
  2032. /**
  2033. * Generate a button or image tag
  2034. *
  2035. * @param string $button_name name of button element
  2036. * @param string $button_class class of button element
  2037. * @param string $image_name name of image element
  2038. * @param string $text text to display
  2039. * @param string $image image to display
  2040. * @param string $value value
  2041. *
  2042. * @access public
  2043. */
  2044. function PMA_buttonOrImage($button_name, $button_class, $image_name, $text,
  2045. $image, $value = '')
  2046. {
  2047. if ($value == '') {
  2048. $value = $text;
  2049. }
  2050. if (false === $GLOBALS['cfg']['PropertiesIconic']) {
  2051. echo ' <input type="submit" name="' . $button_name . '"'
  2052. .' value="' . htmlspecialchars($value) . '"'
  2053. .' title="' . htmlspecialchars($text) . '" />' . "\n";
  2054. return;
  2055. }
  2056. /* Opera has trouble with <input type="image"> */
  2057. /* IE has trouble with <button> */
  2058. if (PMA_USR_BROWSER_AGENT != 'IE') {
  2059. echo '<button class="' . $button_class . '" type="submit"'
  2060. .' name="' . $button_name . '" value="' . htmlspecialchars($value) . '"'
  2061. .' title="' . htmlspecialchars($text) . '">' . "\n"
  2062. . PMA_getIcon($image, $text)
  2063. .'</button>' . "\n";
  2064. } else {
  2065. echo '<input type="image" name="' . $image_name
  2066. . '" value="' . htmlspecialchars($value)
  2067. . '" title="' . htmlspecialchars($text)
  2068. . '" src="' . $GLOBALS['pmaThemeImage']. $image . '" />'
  2069. . ($GLOBALS['cfg']['PropertiesIconic'] === 'both'
  2070. ? '&nbsp;' . htmlspecialchars($text)
  2071. : '') . "\n";
  2072. }
  2073. } // end function
  2074. /**
  2075. * Generate a pagination selector for browsing resultsets
  2076. *
  2077. * @param int $rows Number of rows in the pagination set
  2078. * @param int $pageNow current page number
  2079. * @param int $nbTotalPage number of total pages
  2080. * @param int $showAll If the number of pages is lower than this
  2081. * variable, no pages will be omitted in pagination
  2082. * @param int $sliceStart How many rows at the beginning should always be shown?
  2083. * @param int $sliceEnd How many rows at the end should always be shown?
  2084. * @param int $percent Percentage of calculation page offsets to hop to a
  2085. * next page
  2086. * @param int $range Near the current page, how many pages should
  2087. * be considered "nearby" and displayed as well?
  2088. * @param string $prompt The prompt to display (sometimes empty)
  2089. *
  2090. * @return string
  2091. *
  2092. * @access public
  2093. */
  2094. function PMA_pageselector($rows, $pageNow = 1, $nbTotalPage = 1,
  2095. $showAll = 200, $sliceStart = 5, $sliceEnd = 5, $percent = 20,
  2096. $range = 10, $prompt = '')
  2097. {
  2098. $increment = floor($nbTotalPage / $percent);
  2099. $pageNowMinusRange = ($pageNow - $range);
  2100. $pageNowPlusRange = ($pageNow + $range);
  2101. $gotopage = $prompt . ' <select id="pageselector" ';
  2102. if ($GLOBALS['cfg']['AjaxEnable']) {
  2103. $gotopage .= ' class="ajax"';
  2104. }
  2105. $gotopage .= ' name="pos" >' . "\n";
  2106. if ($nbTotalPage < $showAll) {
  2107. $pages = range(1, $nbTotalPage);
  2108. } else {
  2109. $pages = array();
  2110. // Always show first X pages
  2111. for ($i = 1; $i <= $sliceStart; $i++) {
  2112. $pages[] = $i;
  2113. }
  2114. // Always show last X pages
  2115. for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++) {
  2116. $pages[] = $i;
  2117. }
  2118. // Based on the number of results we add the specified
  2119. // $percent percentage to each page number,
  2120. // so that we have a representing page number every now and then to
  2121. // immediately jump to specific pages.
  2122. // As soon as we get near our currently chosen page ($pageNow -
  2123. // $range), every page number will be shown.
  2124. $i = $sliceStart;
  2125. $x = $nbTotalPage - $sliceEnd;
  2126. $met_boundary = false;
  2127. while ($i <= $x) {
  2128. if ($i >= $pageNowMinusRange && $i <= $pageNowPlusRange) {
  2129. // If our pageselector comes near the current page, we use 1
  2130. // counter increments
  2131. $i++;
  2132. $met_boundary = true;
  2133. } else {
  2134. // We add the percentage increment to our current page to
  2135. // hop to the next one in range
  2136. $i += $increment;
  2137. // Make sure that we do not cross our boundaries.
  2138. if ($i > $pageNowMinusRange && ! $met_boundary) {
  2139. $i = $pageNowMinusRange;
  2140. }
  2141. }
  2142. if ($i > 0 && $i <= $x) {
  2143. $pages[] = $i;
  2144. }
  2145. }
  2146. /*
  2147. Add page numbers with "geometrically increasing" distances.
  2148. This helps me a lot when navigating through giant tables.
  2149. Test case: table with 2.28 million sets, 76190 pages. Page of interest is
  2150. between 72376 and 76190.
  2151. Selecting page 72376.
  2152. Now, old version enumerated only +/- 10 pages around 72376 and the
  2153. percentage increment produced steps of about 3000.
  2154. The following code adds page numbers +/- 2,4,8,16,32,64,128,256 etc.
  2155. around the current page.
  2156. */
  2157. $i = $pageNow;
  2158. $dist = 1;
  2159. while ($i < $x) {
  2160. $dist = 2 * $dist;
  2161. $i = $pageNow + $dist;
  2162. if ($i > 0 && $i <= $x) {
  2163. $pages[] = $i;
  2164. }
  2165. }
  2166. $i = $pageNow;
  2167. $dist = 1;
  2168. while ($i >0) {
  2169. $dist = 2 * $dist;
  2170. $i = $pageNow - $dist;
  2171. if ($i > 0 && $i <= $x) {
  2172. $pages[] = $i;
  2173. }
  2174. }
  2175. // Since because of ellipsing of the current page some numbers may be double,
  2176. // we unify our array:
  2177. sort($pages);
  2178. $pages = array_unique($pages);
  2179. }
  2180. foreach ($pages as $i) {
  2181. if ($i == $pageNow) {
  2182. $selected = 'selected="selected" style="font-weight: bold"';
  2183. } else {
  2184. $selected = '';
  2185. }
  2186. $gotopage .= ' <option ' . $selected
  2187. . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
  2188. }
  2189. $gotopage .= ' </select><noscript><input type="submit" value="'
  2190. . __('Go') . '" /></noscript>';
  2191. return $gotopage;
  2192. } // end function
  2193. /**
  2194. * Generate navigation for a list
  2195. *
  2196. * @param int $count number of elements in the list
  2197. * @param int $pos current position in the list
  2198. * @param array $_url_params url parameters
  2199. * @param string $script script name for form target
  2200. * @param string $frame target frame
  2201. * @param int $max_count maximum number of elements to display from the list
  2202. *
  2203. * @access public
  2204. *
  2205. * @todo use $pos from $_url_params
  2206. */
  2207. function PMA_listNavigator($count, $pos, $_url_params, $script, $frame, $max_count)
  2208. {
  2209. if ($max_count < $count) {
  2210. echo 'frame_navigation' == $frame
  2211. ? '<div id="navidbpageselector">' . "\n"
  2212. : '';
  2213. echo __('Page number:');
  2214. echo 'frame_navigation' == $frame ? '<br />' : ' ';
  2215. // Move to the beginning or to the previous page
  2216. if ($pos > 0) {
  2217. // patch #474210 - part 1
  2218. if ($GLOBALS['cfg']['NavigationBarIconic']) {
  2219. $caption1 = '&lt;&lt;';
  2220. $caption2 = ' &lt; ';
  2221. $title1 = ' title="' . _pgettext('First page', 'Begin') . '"';
  2222. $title2 = ' title="' . _pgettext('Previous page', 'Previous') . '"';
  2223. } else {
  2224. $caption1 = _pgettext('First page', 'Begin') . ' &lt;&lt;';
  2225. $caption2 = _pgettext('Previous page', 'Previous') . ' &lt;';
  2226. $title1 = '';
  2227. $title2 = '';
  2228. } // end if... else...
  2229. $_url_params['pos'] = 0;
  2230. echo '<a' . $title1 . ' href="' . $script
  2231. . PMA_generate_common_url($_url_params) . '" target="'
  2232. . $frame . '">' . $caption1 . '</a>';
  2233. $_url_params['pos'] = $pos - $max_count;
  2234. echo '<a' . $title2 . ' href="' . $script
  2235. . PMA_generate_common_url($_url_params) . '" target="'
  2236. . $frame . '">' . $caption2 . '</a>';
  2237. }
  2238. echo "\n", '<form action="./', basename($script), '" method="post" target="', $frame, '">', "\n";
  2239. echo PMA_generate_common_hidden_inputs($_url_params);
  2240. echo PMA_pageselector(
  2241. $max_count,
  2242. floor(($pos + 1) / $max_count) + 1,
  2243. ceil($count / $max_count)
  2244. );
  2245. echo '</form>';
  2246. if ($pos + $max_count < $count) {
  2247. if ($GLOBALS['cfg']['NavigationBarIconic']) {
  2248. $caption3 = ' &gt; ';
  2249. $caption4 = '&gt;&gt;';
  2250. $title3 = ' title="' . _pgettext('Next page', 'Next') . '"';
  2251. $title4 = ' title="' . _pgettext('Last page', 'End') . '"';
  2252. } else {
  2253. $caption3 = '&gt; ' . _pgettext('Next page', 'Next');
  2254. $caption4 = '&gt;&gt; ' . _pgettext('Last page', 'End');
  2255. $title3 = '';
  2256. $title4 = '';
  2257. } // end if... else...
  2258. $_url_params['pos'] = $pos + $max_count;
  2259. echo '<a' . $title3 . ' href="' . $script
  2260. . PMA_generate_common_url($_url_params) . '" target="'
  2261. . $frame . '">' . $caption3 . '</a>';
  2262. $_url_params['pos'] = floor($count / $max_count) * $max_count;
  2263. if ($_url_params['pos'] == $count) {
  2264. $_url_params['pos'] = $count - $max_count;
  2265. }
  2266. echo '<a' . $title4 . ' href="' . $script
  2267. . PMA_generate_common_url($_url_params) . '" target="'
  2268. . $frame . '">' . $caption4 . '</a>';
  2269. }
  2270. echo "\n";
  2271. if ('frame_navigation' == $frame) {
  2272. echo '</div>' . "\n";
  2273. }
  2274. }
  2275. }
  2276. /**
  2277. * replaces %u in given path with current user name
  2278. *
  2279. * example:
  2280. * <code>
  2281. * $user_dir = PMA_userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
  2282. *
  2283. * </code>
  2284. *
  2285. * @param string $dir with wildcard for user
  2286. *
  2287. * @return string per user directory
  2288. */
  2289. function PMA_userDir($dir)
  2290. {
  2291. // add trailing slash
  2292. if (substr($dir, -1) != '/') {
  2293. $dir .= '/';
  2294. }
  2295. return str_replace('%u', $GLOBALS['cfg']['Server']['user'], $dir);
  2296. }
  2297. /**
  2298. * returns html code for db link to default db page
  2299. *
  2300. * @param string $database database
  2301. *
  2302. * @return string html link to default db page
  2303. */
  2304. function PMA_getDbLink($database = null)
  2305. {
  2306. if (! strlen($database)) {
  2307. if (! strlen($GLOBALS['db'])) {
  2308. return '';
  2309. }
  2310. $database = $GLOBALS['db'];
  2311. } else {
  2312. $database = PMA_unescape_mysql_wildcards($database);
  2313. }
  2314. return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?'
  2315. . PMA_generate_common_url($database) . '" title="'
  2316. . sprintf(
  2317. __('Jump to database &quot;%s&quot;.'),
  2318. htmlspecialchars($database)
  2319. )
  2320. . '">' . htmlspecialchars($database) . '</a>';
  2321. }
  2322. /**
  2323. * Displays a lightbulb hint explaining a known external bug
  2324. * that affects a functionality
  2325. *
  2326. * @param string $functionality localized message explaining the func.
  2327. * @param string $component 'mysql' (eventually, 'php')
  2328. * @param string $minimum_version of this component
  2329. * @param string $bugref bug reference for this component
  2330. */
  2331. function PMA_externalBug($functionality, $component, $minimum_version, $bugref)
  2332. {
  2333. if ($component == 'mysql' && PMA_MYSQL_INT_VERSION < $minimum_version) {
  2334. echo PMA_showHint(
  2335. sprintf(
  2336. __('The %s functionality is affected by a known bug, see %s'),
  2337. $functionality,
  2338. PMA_linkURL('http://bugs.mysql.com/') . $bugref
  2339. )
  2340. );
  2341. }
  2342. }
  2343. /**
  2344. * Generates and echoes an HTML checkbox
  2345. *
  2346. * @param string $html_field_name the checkbox HTML field
  2347. * @param string $label label for checkbox
  2348. * @param boolean $checked is it initially checked?
  2349. * @param boolean $onclick should it submit the form on click?
  2350. *
  2351. * @return the HTML for the checkbox
  2352. */
  2353. function PMA_display_html_checkbox($html_field_name, $label, $checked, $onclick)
  2354. {
  2355. echo '<input type="checkbox" name="' . $html_field_name . '" id="'
  2356. . $html_field_name . '"' . ($checked ? ' checked="checked"' : '')
  2357. . ($onclick ? ' class="autosubmit"' : '') . ' /><label for="'
  2358. . $html_field_name . '">' . $label . '</label>';
  2359. }
  2360. /**
  2361. * Generates and echoes a set of radio HTML fields
  2362. *
  2363. * @param string $html_field_name the radio HTML field
  2364. * @param array $choices the choices values and labels
  2365. * @param string $checked_choice the choice to check by default
  2366. * @param boolean $line_break whether to add an HTML line break after a choice
  2367. * @param boolean $escape_label whether to use htmlspecialchars() on label
  2368. * @param string $class enclose each choice with a div of this class
  2369. *
  2370. * @return the HTML for the tadio buttons
  2371. */
  2372. function PMA_display_html_radio($html_field_name, $choices, $checked_choice = '',
  2373. $line_break = true, $escape_label = true, $class='')
  2374. {
  2375. foreach ($choices as $choice_value => $choice_label) {
  2376. if (! empty($class)) {
  2377. echo '<div class="' . $class . '">';
  2378. }
  2379. $html_field_id = $html_field_name . '_' . $choice_value;
  2380. echo '<input type="radio" name="' . $html_field_name . '" id="'
  2381. . $html_field_id . '" value="' . htmlspecialchars($choice_value) . '"';
  2382. if ($choice_value == $checked_choice) {
  2383. echo ' checked="checked"';
  2384. }
  2385. echo ' />' . "\n";
  2386. echo '<label for="' . $html_field_id . '">'
  2387. . ($escape_label ? htmlspecialchars($choice_label) : $choice_label)
  2388. . '</label>';
  2389. if ($line_break) {
  2390. echo '<br />';
  2391. }
  2392. if (! empty($class)) {
  2393. echo '</div>';
  2394. }
  2395. echo "\n";
  2396. }
  2397. }
  2398. /**
  2399. * Generates and returns an HTML dropdown
  2400. *
  2401. * @param string $select_name name for the select element
  2402. * @param array $choices choices values
  2403. * @param string $active_choice the choice to select by default
  2404. * @param string $id id of the select element; can be different in case
  2405. * the dropdown is present more than once on the page
  2406. *
  2407. * @return string
  2408. *
  2409. * @todo support titles
  2410. */
  2411. function PMA_generate_html_dropdown($select_name, $choices, $active_choice, $id)
  2412. {
  2413. $result = '<select name="' . htmlspecialchars($select_name) . '" id="'
  2414. . htmlspecialchars($id) . '">';
  2415. foreach ($choices as $one_choice_value => $one_choice_label) {
  2416. $result .= '<option value="' . htmlspecialchars($one_choice_value) . '"';
  2417. if ($one_choice_value == $active_choice) {
  2418. $result .= ' selected="selected"';
  2419. }
  2420. $result .= '>' . htmlspecialchars($one_choice_label) . '</option>';
  2421. }
  2422. $result .= '</select>';
  2423. return $result;
  2424. }
  2425. /**
  2426. * Generates a slider effect (jQjuery)
  2427. * Takes care of generating the initial <div> and the link
  2428. * controlling the slider; you have to generate the </div> yourself
  2429. * after the sliding section.
  2430. *
  2431. * @param string $id the id of the <div> on which to apply the effect
  2432. * @param string $message the message to show as a link
  2433. */
  2434. function PMA_generate_slider_effect($id, $message)
  2435. {
  2436. if ($GLOBALS['cfg']['InitialSlidersState'] == 'disabled') {
  2437. echo '<div id="' . $id . '">';
  2438. return;
  2439. }
  2440. /**
  2441. * Bad hack on the next line. document.write() conflicts with jQuery, hence,
  2442. * opening the <div> with PHP itself instead of JavaScript.
  2443. *
  2444. * @todo find a better solution that uses $.append(), the recommended method
  2445. * maybe by using an additional param, the id of the div to append to
  2446. */
  2447. ?>
  2448. <div id="<?php echo $id; ?>" <?php echo $GLOBALS['cfg']['InitialSlidersState'] == 'closed' ? ' style="display: none; overflow:auto;"' : ''; ?> class="pma_auto_slider" title="<?php echo htmlspecialchars($message); ?>">
  2449. <?php
  2450. }
  2451. /**
  2452. * Creates an AJAX sliding toggle button
  2453. * (or and equivalent form when AJAX is disabled)
  2454. *
  2455. * @param string $action The URL for the request to be executed
  2456. * @param string $select_name The name for the dropdown box
  2457. * @param array $options An array of options (see rte_footer.lib.php)
  2458. * @param string $callback A JS snippet to execute when the request is
  2459. * successfully processed
  2460. *
  2461. * @return string HTML code for the toggle button
  2462. */
  2463. function PMA_toggleButton($action, $select_name, $options, $callback)
  2464. {
  2465. // Do the logic first
  2466. $link_on = "$action&amp;$select_name=" . urlencode($options[1]['value']);
  2467. $link_off = "$action&amp;$select_name=" . urlencode($options[0]['value']);
  2468. if ($options[1]['selected'] == true) {
  2469. $state = 'on';
  2470. } else if ($options[0]['selected'] == true) {
  2471. $state = 'off';
  2472. } else {
  2473. $state = 'on';
  2474. }
  2475. $selected1 = '';
  2476. $selected0 = '';
  2477. if ($options[1]['selected'] == true) {
  2478. $selected1 = " selected='selected'";
  2479. } else if ($options[0]['selected'] == true) {
  2480. $selected0 = " selected='selected'";
  2481. }
  2482. // Generate output
  2483. $retval = "<!-- TOGGLE START -->\n";
  2484. if ($GLOBALS['cfg']['AjaxEnable'] && is_readable($_SESSION['PMA_Theme']->getImgPath() . 'toggle-ltr.png')) {
  2485. $retval .= "<noscript>\n";
  2486. }
  2487. $retval .= "<div class='wrapper'>\n";
  2488. $retval .= " <form action='$action' method='post'>\n";
  2489. $retval .= " <select name='$select_name'>\n";
  2490. $retval .= " <option value='{$options[1]['value']}'$selected1>";
  2491. $retval .= " {$options[1]['label']}\n";
  2492. $retval .= " </option>\n";
  2493. $retval .= " <option value='{$options[0]['value']}'$selected0>";
  2494. $retval .= " {$options[0]['label']}\n";
  2495. $retval .= " </option>\n";
  2496. $retval .= " </select>\n";
  2497. $retval .= " <input type='submit' value='" . __('Change') . "'/>\n";
  2498. $retval .= " </form>\n";
  2499. $retval .= "</div>\n";
  2500. if ($GLOBALS['cfg']['AjaxEnable'] && is_readable($_SESSION['PMA_Theme']->getImgPath() . 'toggle-ltr.png')) {
  2501. $retval .= "</noscript>\n";
  2502. $retval .= "<div class='wrapper toggleAjax hide'>\n";
  2503. $retval .= " <div class='toggleButton'>\n";
  2504. $retval .= " <div title='" . __('Click to toggle') . "' class='container $state'>\n";
  2505. $retval .= " <img src='{$GLOBALS['pmaThemeImage']}toggle-{$GLOBALS['text_dir']}.png'\n";
  2506. $retval .= " alt='' />\n";
  2507. $retval .= " <table cellspacing='0' cellpadding='0'><tr>\n";
  2508. $retval .= " <tbody>\n";
  2509. $retval .= " <td class='toggleOn'>\n";
  2510. $retval .= " <span class='hide'>$link_on</span>\n";
  2511. $retval .= " <div>";
  2512. $retval .= str_replace(' ', '&nbsp;', $options[1]['label']) . "</div>\n";
  2513. $retval .= " </td>\n";
  2514. $retval .= " <td><div>&nbsp;</div></td>\n";
  2515. $retval .= " <td class='toggleOff'>\n";
  2516. $retval .= " <span class='hide'>$link_off</span>\n";
  2517. $retval .= " <div>";
  2518. $retval .= str_replace(' ', '&nbsp;', $options[0]['label']) . "</div>\n";
  2519. $retval .= " </div>\n";
  2520. $retval .= " </tbody>\n";
  2521. $retval .= " </tr></table>\n";
  2522. $retval .= " <span class='hide callback'>$callback</span>\n";
  2523. $retval .= " <span class='hide text_direction'>{$GLOBALS['text_dir']}</span>\n";
  2524. $retval .= " </div>\n";
  2525. $retval .= " </div>\n";
  2526. $retval .= "</div>\n";
  2527. }
  2528. $retval .= "<!-- TOGGLE END -->";
  2529. return $retval;
  2530. } // end PMA_toggleButton()
  2531. /**
  2532. * Clears cache content which needs to be refreshed on user change.
  2533. *
  2534. * @return nothing
  2535. */
  2536. function PMA_clearUserCache()
  2537. {
  2538. PMA_cacheUnset('is_superuser', true);
  2539. }
  2540. /**
  2541. * Verifies if something is cached in the session
  2542. *
  2543. * @param string $var variable name
  2544. * @param int|true $server server
  2545. *
  2546. * @return boolean
  2547. */
  2548. function PMA_cacheExists($var, $server = 0)
  2549. {
  2550. if (true === $server) {
  2551. $server = $GLOBALS['server'];
  2552. }
  2553. return isset($_SESSION['cache']['server_' . $server][$var]);
  2554. }
  2555. /**
  2556. * Gets cached information from the session
  2557. *
  2558. * @param string $var varibale name
  2559. * @param int|true $server server
  2560. *
  2561. * @return mixed
  2562. */
  2563. function PMA_cacheGet($var, $server = 0)
  2564. {
  2565. if (true === $server) {
  2566. $server = $GLOBALS['server'];
  2567. }
  2568. if (isset($_SESSION['cache']['server_' . $server][$var])) {
  2569. return $_SESSION['cache']['server_' . $server][$var];
  2570. } else {
  2571. return null;
  2572. }
  2573. }
  2574. /**
  2575. * Caches information in the session
  2576. *
  2577. * @param string $var variable name
  2578. * @param mixed $val value
  2579. * @param int|true $server server
  2580. *
  2581. * @return mixed
  2582. */
  2583. function PMA_cacheSet($var, $val = null, $server = 0)
  2584. {
  2585. if (true === $server) {
  2586. $server = $GLOBALS['server'];
  2587. }
  2588. $_SESSION['cache']['server_' . $server][$var] = $val;
  2589. }
  2590. /**
  2591. * Removes cached information from the session
  2592. *
  2593. * @param string $var variable name
  2594. * @param int|true $server server
  2595. *
  2596. * @return nothing
  2597. */
  2598. function PMA_cacheUnset($var, $server = 0)
  2599. {
  2600. if (true === $server) {
  2601. $server = $GLOBALS['server'];
  2602. }
  2603. unset($_SESSION['cache']['server_' . $server][$var]);
  2604. }
  2605. /**
  2606. * Converts a bit value to printable format;
  2607. * in MySQL a BIT field can be from 1 to 64 bits so we need this
  2608. * function because in PHP, decbin() supports only 32 bits
  2609. *
  2610. * @param numeric $value coming from a BIT field
  2611. * @param integer $length length
  2612. *
  2613. * @return string the printable value
  2614. */
  2615. function PMA_printable_bit_value($value, $length)
  2616. {
  2617. $printable = '';
  2618. for ($i = 0, $len_ceiled = ceil($length / 8); $i < $len_ceiled; $i++) {
  2619. $printable .= sprintf('%08d', decbin(ord(substr($value, $i, 1))));
  2620. }
  2621. $printable = substr($printable, -$length);
  2622. return $printable;
  2623. }
  2624. /**
  2625. * Verifies whether the value contains a non-printable character
  2626. *
  2627. * @param string $value value
  2628. *
  2629. * @return boolean
  2630. */
  2631. function PMA_contains_nonprintable_ascii($value)
  2632. {
  2633. return preg_match('@[^[:print:]]@', $value);
  2634. }
  2635. /**
  2636. * Converts a BIT type default value
  2637. * for example, b'010' becomes 010
  2638. *
  2639. * @param string $bit_default_value value
  2640. *
  2641. * @return string the converted value
  2642. */
  2643. function PMA_convert_bit_default_value($bit_default_value)
  2644. {
  2645. return strtr($bit_default_value, array("b" => "", "'" => ""));
  2646. }
  2647. /**
  2648. * Extracts the various parts from a field type spec
  2649. *
  2650. * @param string $fieldspec Field specification
  2651. *
  2652. * @return array associative array containing type, spec_in_brackets
  2653. * and possibly enum_set_values (another array)
  2654. */
  2655. function PMA_extractFieldSpec($fieldspec)
  2656. {
  2657. $first_bracket_pos = strpos($fieldspec, '(');
  2658. if ($first_bracket_pos) {
  2659. $spec_in_brackets = chop(
  2660. substr(
  2661. $fieldspec,
  2662. $first_bracket_pos + 1,
  2663. (strrpos($fieldspec, ')') - $first_bracket_pos - 1)
  2664. )
  2665. );
  2666. // convert to lowercase just to be sure
  2667. $type = strtolower(chop(substr($fieldspec, 0, $first_bracket_pos)));
  2668. } else {
  2669. $type = strtolower($fieldspec);
  2670. $spec_in_brackets = '';
  2671. }
  2672. if ('enum' == $type || 'set' == $type) {
  2673. // Define our working vars
  2674. $enum_set_values = array();
  2675. $working = "";
  2676. $in_string = false;
  2677. $index = 0;
  2678. // While there is another character to process
  2679. while (isset($fieldspec[$index])) {
  2680. // Grab the char to look at
  2681. $char = $fieldspec[$index];
  2682. // If it is a single quote, needs to be handled specially
  2683. if ($char == "'") {
  2684. // If we are not currently in a string, begin one
  2685. if (! $in_string) {
  2686. $in_string = true;
  2687. $working = "";
  2688. } else {
  2689. // Otherwise, it may be either an end of a string,
  2690. // or a 'double quote' which can be handled as-is
  2691. // Check out the next character (if possible)
  2692. $has_next = isset($fieldspec[$index + 1]);
  2693. $next = $has_next ? $fieldspec[$index + 1] : null;
  2694. //If we have reached the end of our 'working' string (because
  2695. //there are no more chars,or the next char is not another quote)
  2696. if (! $has_next || $next != "'") {
  2697. $enum_set_values[] = $working;
  2698. $in_string = false;
  2699. } elseif ($next == "'") {
  2700. // Otherwise, this is a 'double quote',
  2701. // and can be added to the working string
  2702. $working .= "'";
  2703. // Skip the next char; we already know what it is
  2704. $index++;
  2705. }
  2706. }
  2707. } elseif ('\\' == $char
  2708. && isset($fieldspec[$index + 1])
  2709. && "'" == $fieldspec[$index + 1]
  2710. ) {
  2711. // escaping of a quote?
  2712. $working .= "'";
  2713. $index++;
  2714. } else {
  2715. // Otherwise, add it to our working string like normal
  2716. $working .= $char;
  2717. }
  2718. // Increment character index
  2719. $index++;
  2720. } // end while
  2721. $printtype = $type . '(' . str_replace("','", "', '", $spec_in_brackets) . ')';
  2722. $binary = false;
  2723. $unsigned = false;
  2724. $zerofill = false;
  2725. } else {
  2726. $enum_set_values = array();
  2727. /* Create printable type name */
  2728. $printtype = strtolower($fieldspec);
  2729. // Strip the "BINARY" attribute, except if we find "BINARY(" because
  2730. // this would be a BINARY or VARBINARY field type;
  2731. // by the way, a BLOB should not show the BINARY attribute
  2732. // because this is not accepted in MySQL syntax.
  2733. if (preg_match('@binary@', $printtype) && ! preg_match('@binary[\(]@', $printtype)) {
  2734. $printtype = preg_replace('@binary@', '', $printtype);
  2735. $binary = true;
  2736. } else {
  2737. $binary = false;
  2738. }
  2739. $printtype = preg_replace('@zerofill@', '', $printtype, -1, $zerofill_cnt);
  2740. $zerofill = ($zerofill_cnt > 0);
  2741. $printtype = preg_replace('@unsigned@', '', $printtype, -1, $unsigned_cnt);
  2742. $unsigned = ($unsigned_cnt > 0);
  2743. $printtype = trim($printtype);
  2744. }
  2745. $attribute = ' ';
  2746. if ($binary) {
  2747. $attribute = 'BINARY';
  2748. }
  2749. if ($unsigned) {
  2750. $attribute = 'UNSIGNED';
  2751. }
  2752. if ($zerofill) {
  2753. $attribute = 'UNSIGNED ZEROFILL';
  2754. }
  2755. return array(
  2756. 'type' => $type,
  2757. 'spec_in_brackets' => $spec_in_brackets,
  2758. 'enum_set_values' => $enum_set_values,
  2759. 'print_type' => $printtype,
  2760. 'binary' => $binary,
  2761. 'unsigned' => $unsigned,
  2762. 'zerofill' => $zerofill,
  2763. 'attribute' => $attribute,
  2764. );
  2765. }
  2766. /**
  2767. * Verifies if this table's engine supports foreign keys
  2768. *
  2769. * @param string $engine engine
  2770. *
  2771. * @return boolean
  2772. */
  2773. function PMA_foreignkey_supported($engine)
  2774. {
  2775. $engine = strtoupper($engine);
  2776. if ('INNODB' == $engine || 'PBXT' == $engine) {
  2777. return true;
  2778. } else {
  2779. return false;
  2780. }
  2781. }
  2782. /**
  2783. * Replaces some characters by a displayable equivalent
  2784. *
  2785. * @param string $content content
  2786. *
  2787. * @return string the content with characters replaced
  2788. */
  2789. function PMA_replace_binary_contents($content)
  2790. {
  2791. $result = str_replace("\x00", '\0', $content);
  2792. $result = str_replace("\x08", '\b', $result);
  2793. $result = str_replace("\x0a", '\n', $result);
  2794. $result = str_replace("\x0d", '\r', $result);
  2795. $result = str_replace("\x1a", '\Z', $result);
  2796. return $result;
  2797. }
  2798. /**
  2799. * Converts GIS data to Well Known Text format
  2800. *
  2801. * @param binary $data GIS data
  2802. * @param bool $includeSRID Add SRID to the WKT
  2803. *
  2804. * @return GIS data in Well Know Text format
  2805. */
  2806. function PMA_asWKT($data, $includeSRID = false)
  2807. {
  2808. // Convert to WKT format
  2809. $hex = bin2hex($data);
  2810. $wktsql = "SELECT ASTEXT(x'" . $hex . "')";
  2811. if ($includeSRID) {
  2812. $wktsql .= ", SRID(x'" . $hex . "')";
  2813. }
  2814. $wktresult = PMA_DBI_try_query($wktsql, null, PMA_DBI_QUERY_STORE);
  2815. $wktarr = PMA_DBI_fetch_row($wktresult, 0);
  2816. $wktval = $wktarr[0];
  2817. if ($includeSRID) {
  2818. $srid = $wktarr[1];
  2819. $wktval = "'" . $wktval . "'," . $srid;
  2820. }
  2821. @PMA_DBI_free_result($wktresult);
  2822. return $wktval;
  2823. }
  2824. /**
  2825. * If the string starts with a \r\n pair (0x0d0a) add an extra \n
  2826. *
  2827. * @param string $string string
  2828. *
  2829. * @return string with the chars replaced
  2830. */
  2831. function PMA_duplicateFirstNewline($string)
  2832. {
  2833. $first_occurence = strpos($string, "\r\n");
  2834. if ($first_occurence === 0) {
  2835. $string = "\n".$string;
  2836. }
  2837. return $string;
  2838. }
  2839. /**
  2840. * Get the action word corresponding to a script name
  2841. * in order to display it as a title in navigation panel
  2842. *
  2843. * @param string $target a valid value for $cfg['LeftDefaultTabTable'],
  2844. * $cfg['DefaultTabTable'] or $cfg['DefaultTabDatabase']
  2845. *
  2846. * @return array
  2847. */
  2848. function PMA_getTitleForTarget($target)
  2849. {
  2850. $mapping = array(
  2851. // Values for $cfg['DefaultTabTable']
  2852. 'tbl_structure.php' => __('Structure'),
  2853. 'tbl_sql.php' => __('SQL'),
  2854. 'tbl_select.php' =>__('Search'),
  2855. 'tbl_change.php' =>__('Insert'),
  2856. 'sql.php' => __('Browse'),
  2857. // Values for $cfg['DefaultTabDatabase']
  2858. 'db_structure.php' => __('Structure'),
  2859. 'db_sql.php' => __('SQL'),
  2860. 'db_search.php' => __('Search'),
  2861. 'db_operations.php' => __('Operations'),
  2862. );
  2863. return $mapping[$target];
  2864. }
  2865. /**
  2866. * Formats user string, expanding @VARIABLES@, accepting strftime format string.
  2867. *
  2868. * @param string $string Text where to do expansion.
  2869. * @param function $escape Function to call for escaping variable values.
  2870. * @param array $updates Array with overrides for default parameters
  2871. * (obtained from GLOBALS).
  2872. *
  2873. * @return string
  2874. */
  2875. function PMA_expandUserString($string, $escape = null, $updates = array())
  2876. {
  2877. /* Content */
  2878. $vars['http_host'] = PMA_getenv('HTTP_HOST') ? PMA_getenv('HTTP_HOST') : '';
  2879. $vars['server_name'] = $GLOBALS['cfg']['Server']['host'];
  2880. $vars['server_verbose'] = $GLOBALS['cfg']['Server']['verbose'];
  2881. $vars['server_verbose_or_name'] = ! empty($GLOBALS['cfg']['Server']['verbose'])
  2882. ? $GLOBALS['cfg']['Server']['verbose']
  2883. : $GLOBALS['cfg']['Server']['host'];
  2884. $vars['database'] = $GLOBALS['db'];
  2885. $vars['table'] = $GLOBALS['table'];
  2886. $vars['phpmyadmin_version'] = 'phpMyAdmin ' . PMA_VERSION;
  2887. /* Update forced variables */
  2888. foreach ($updates as $key => $val) {
  2889. $vars[$key] = $val;
  2890. }
  2891. /* Replacement mapping */
  2892. /*
  2893. * The __VAR__ ones are for backward compatibility, because user
  2894. * might still have it in cookies.
  2895. */
  2896. $replace = array(
  2897. '@HTTP_HOST@' => $vars['http_host'],
  2898. '@SERVER@' => $vars['server_name'],
  2899. '__SERVER__' => $vars['server_name'],
  2900. '@VERBOSE@' => $vars['server_verbose'],
  2901. '@VSERVER@' => $vars['server_verbose_or_name'],
  2902. '@DATABASE@' => $vars['database'],
  2903. '__DB__' => $vars['database'],
  2904. '@TABLE@' => $vars['table'],
  2905. '__TABLE__' => $vars['table'],
  2906. '@PHPMYADMIN@' => $vars['phpmyadmin_version'],
  2907. );
  2908. /* Optional escaping */
  2909. if (!is_null($escape)) {
  2910. foreach ($replace as $key => $val) {
  2911. $replace[$key] = $escape($val);
  2912. }
  2913. }
  2914. /* Backward compatibility in 3.5.x */
  2915. if (strpos($string, '@FIELDS@') !== false) {
  2916. $string = strtr($string, array('@FIELDS@' => '@COLUMNS@'));
  2917. }
  2918. /* Fetch columns list if required */
  2919. if (strpos($string, '@COLUMNS@') !== false) {
  2920. $columns_list = PMA_DBI_get_columns($GLOBALS['db'], $GLOBALS['table']);
  2921. $column_names = array();
  2922. foreach ($columns_list as $column) {
  2923. if (! is_null($escape)) {
  2924. $column_names[] = $escape($column['Field']);
  2925. } else {
  2926. $column_names[] = $field['Field'];
  2927. }
  2928. }
  2929. $replace['@COLUMNS@'] = implode(',', $column_names);
  2930. }
  2931. /* Do the replacement */
  2932. return strtr(strftime($string), $replace);
  2933. }
  2934. /**
  2935. * function that generates a json output for an ajax request and ends script
  2936. * execution
  2937. *
  2938. * @param PMA_Message|string $message message string containing the
  2939. * html of the message
  2940. * @param bool $success success whether the ajax request
  2941. * was successfull
  2942. * @param array $extra_data extra data optional -
  2943. * any other data as part of the json request
  2944. *
  2945. * @return nothing
  2946. */
  2947. function PMA_ajaxResponse($message, $success = true, $extra_data = array())
  2948. {
  2949. $response = array();
  2950. if ( $success == true ) {
  2951. $response['success'] = true;
  2952. if ($message instanceof PMA_Message) {
  2953. $response['message'] = $message->getDisplay();
  2954. } else {
  2955. $response['message'] = $message;
  2956. }
  2957. } else {
  2958. $response['success'] = false;
  2959. if ($message instanceof PMA_Message) {
  2960. $response['error'] = $message->getDisplay();
  2961. } else {
  2962. $response['error'] = $message;
  2963. }
  2964. }
  2965. // If extra_data has been provided, append it to the response array
  2966. if ( ! empty($extra_data) && count($extra_data) > 0 ) {
  2967. $response = array_merge($response, $extra_data);
  2968. }
  2969. // Set the Content-Type header to JSON so that jQuery parses the
  2970. // response correctly.
  2971. //
  2972. // At this point, other headers might have been sent;
  2973. // even if $GLOBALS['is_header_sent'] is true,
  2974. // we have to send these additional headers.
  2975. header('Cache-Control: no-cache');
  2976. header("Content-Type: application/json");
  2977. echo json_encode($response);
  2978. if (!defined('TESTSUITE'))
  2979. exit;
  2980. }
  2981. /**
  2982. * Display the form used to browse anywhere on the local server for a file to import
  2983. *
  2984. * @param string $max_upload_size maximum upload size
  2985. *
  2986. * @return nothing
  2987. */
  2988. function PMA_browseUploadFile($max_upload_size)
  2989. {
  2990. echo '<label for="radio_import_file">' . __("Browse your computer:") . '</label>';
  2991. echo '<div id="upload_form_status" style="display: none;"></div>';
  2992. echo '<div id="upload_form_status_info" style="display: none;"></div>';
  2993. echo '<input type="file" name="import_file" id="input_import_file" />';
  2994. echo PMA_displayMaximumUploadSize($max_upload_size) . "\n";
  2995. // some browsers should respect this :)
  2996. echo PMA_generateHiddenMaxFileSize($max_upload_size) . "\n";
  2997. }
  2998. /**
  2999. * Display the form used to select a file to import from the server upload directory
  3000. *
  3001. * @param array $import_list array of import types
  3002. * @param string $uploaddir upload directory
  3003. *
  3004. * @return nothing
  3005. */
  3006. function PMA_selectUploadFile($import_list, $uploaddir)
  3007. {
  3008. echo '<label for="radio_local_import_file">' . sprintf(__("Select from the web server upload directory <b>%s</b>:"), htmlspecialchars(PMA_userDir($uploaddir))) . '</label>';
  3009. $extensions = '';
  3010. foreach ($import_list as $key => $val) {
  3011. if (!empty($extensions)) {
  3012. $extensions .= '|';
  3013. }
  3014. $extensions .= $val['extension'];
  3015. }
  3016. $matcher = '@\.(' . $extensions . ')(\.('
  3017. . PMA_supportedDecompressions() . '))?$@';
  3018. $active = (isset($timeout_passed) && $timeout_passed && isset($local_import_file))
  3019. ? $local_import_file
  3020. : '';
  3021. $files = PMA_getFileSelectOptions(
  3022. PMA_userDir($uploaddir),
  3023. $matcher,
  3024. $active
  3025. );
  3026. if ($files === false) {
  3027. PMA_Message::error(
  3028. __('The directory you set for upload work cannot be reached')
  3029. )->display();
  3030. } elseif (!empty($files)) {
  3031. echo "\n";
  3032. echo ' <select style="margin: 5px" size="1" name="local_import_file" id="select_local_import_file">' . "\n";
  3033. echo ' <option value="">&nbsp;</option>' . "\n";
  3034. echo $files;
  3035. echo ' </select>' . "\n";
  3036. } elseif (empty ($files)) {
  3037. echo '<i>' . __('There are no files to upload') . '</i>';
  3038. }
  3039. }
  3040. /**
  3041. * Build titles and icons for action links
  3042. *
  3043. * @return array the action titles
  3044. */
  3045. function PMA_buildActionTitles()
  3046. {
  3047. $titles = array();
  3048. $titles['Browse'] = PMA_getIcon('b_browse.png', __('Browse'));
  3049. $titles['NoBrowse'] = PMA_getIcon('bd_browse.png', __('Browse'));
  3050. $titles['Search'] = PMA_getIcon('b_select.png', __('Search'));
  3051. $titles['NoSearch'] = PMA_getIcon('bd_select.png', __('Search'));
  3052. $titles['Insert'] = PMA_getIcon('b_insrow.png', __('Insert'));
  3053. $titles['NoInsert'] = PMA_getIcon('bd_insrow.png', __('Insert'));
  3054. $titles['Structure'] = PMA_getIcon('b_props.png', __('Structure'));
  3055. $titles['Drop'] = PMA_getIcon('b_drop.png', __('Drop'));
  3056. $titles['NoDrop'] = PMA_getIcon('bd_drop.png', __('Drop'));
  3057. $titles['Empty'] = PMA_getIcon('b_empty.png', __('Empty'));
  3058. $titles['NoEmpty'] = PMA_getIcon('bd_empty.png', __('Empty'));
  3059. $titles['Edit'] = PMA_getIcon('b_edit.png', __('Edit'));
  3060. $titles['NoEdit'] = PMA_getIcon('bd_edit.png', __('Edit'));
  3061. $titles['Export'] = PMA_getIcon('b_export.png', __('Export'));
  3062. $titles['NoExport'] = PMA_getIcon('bd_export.png', __('Export'));
  3063. $titles['Execute'] = PMA_getIcon('b_nextpage.png', __('Execute'));
  3064. $titles['NoExecute'] = PMA_getIcon('bd_nextpage.png', __('Execute'));
  3065. return $titles;
  3066. }
  3067. /**
  3068. * This function processes the datatypes supported by the DB, as specified in
  3069. * $cfg['ColumnTypes'] and either returns an array (useful for quickly checking
  3070. * if a datatype is supported) or an HTML snippet that creates a drop-down list.
  3071. *
  3072. * @param bool $html Whether to generate an html snippet or an array
  3073. * @param string $selected The value to mark as selected in HTML mode
  3074. *
  3075. * @return mixed An HTML snippet or an array of datatypes.
  3076. *
  3077. */
  3078. function PMA_getSupportedDatatypes($html = false, $selected = '')
  3079. {
  3080. global $cfg;
  3081. if ($html) {
  3082. // NOTE: the SELECT tag in not included in this snippet.
  3083. $retval = '';
  3084. foreach ($cfg['ColumnTypes'] as $key => $value) {
  3085. if (is_array($value)) {
  3086. $retval .= "<optgroup label='" . htmlspecialchars($key) . "'>";
  3087. foreach ($value as $subvalue) {
  3088. if ($subvalue == $selected) {
  3089. $retval .= "<option selected='selected'>";
  3090. $retval .= $subvalue;
  3091. $retval .= "</option>";
  3092. } else if ($subvalue === '-') {
  3093. $retval .= "<option disabled='disabled'>";
  3094. $retval .= $subvalue;
  3095. $retval .= "</option>";
  3096. } else {
  3097. $retval .= "<option>$subvalue</option>";
  3098. }
  3099. }
  3100. $retval .= '</optgroup>';
  3101. } else {
  3102. if ($selected == $value) {
  3103. $retval .= "<option selected='selected'>$value</option>";
  3104. } else {
  3105. $retval .= "<option>$value</option>";
  3106. }
  3107. }
  3108. }
  3109. } else {
  3110. $retval = array();
  3111. foreach ($cfg['ColumnTypes'] as $value) {
  3112. if (is_array($value)) {
  3113. foreach ($value as $subvalue) {
  3114. if ($subvalue !== '-') {
  3115. $retval[] = $subvalue;
  3116. }
  3117. }
  3118. } else {
  3119. if ($value !== '-') {
  3120. $retval[] = $value;
  3121. }
  3122. }
  3123. }
  3124. }
  3125. return $retval;
  3126. } // end PMA_getSupportedDatatypes()
  3127. /**
  3128. * Returns a list of datatypes that are not (yet) handled by PMA.
  3129. * Used by: tbl_change.php and libraries/db_routines.inc.php
  3130. *
  3131. * @return array list of datatypes
  3132. */
  3133. function PMA_unsupportedDatatypes()
  3134. {
  3135. $no_support_types = array();
  3136. return $no_support_types;
  3137. }
  3138. /**
  3139. * Return GIS data types
  3140. *
  3141. * @param bool $upper_case whether to return values in upper case
  3142. *
  3143. * @return array GIS data types
  3144. */
  3145. function PMA_getGISDatatypes($upper_case = false)
  3146. {
  3147. $gis_data_types = array(
  3148. 'geometry',
  3149. 'point',
  3150. 'linestring',
  3151. 'polygon',
  3152. 'multipoint',
  3153. 'multilinestring',
  3154. 'multipolygon',
  3155. 'geometrycollection'
  3156. );
  3157. if ($upper_case) {
  3158. for ($i = 0; $i < count($gis_data_types); $i++) {
  3159. $gis_data_types[$i] = strtoupper($gis_data_types[$i]);
  3160. }
  3161. }
  3162. return $gis_data_types;
  3163. }
  3164. /**
  3165. * Generates GIS data based on the string passed.
  3166. *
  3167. * @param string $gis_string GIS string
  3168. *
  3169. * @return GIS data enclosed in 'GeomFromText' function
  3170. */
  3171. function PMA_createGISData($gis_string)
  3172. {
  3173. $gis_string = trim($gis_string);
  3174. $geom_types = '(POINT|MULTIPOINT|LINESTRING|MULTILINESTRING|'
  3175. . 'POLYGON|MULTIPOLYGON|GEOMETRYCOLLECTION)';
  3176. if (preg_match("/^'" . $geom_types . "\(.*\)',[0-9]*$/i", $gis_string)) {
  3177. return 'GeomFromText(' . $gis_string . ')';
  3178. } elseif (preg_match("/^" . $geom_types . "\(.*\)$/i", $gis_string)) {
  3179. return "GeomFromText('" . $gis_string . "')";
  3180. } else {
  3181. return $gis_string;
  3182. }
  3183. }
  3184. /**
  3185. * Returns the names and details of the functions
  3186. * that can be applied on geometry data typess.
  3187. *
  3188. * @param string $geom_type if provided the output is limited to the functions
  3189. * that are applicable to the provided geometry type.
  3190. * @param bool $binary if set to false functions that take two geometries
  3191. * as arguments will not be included.
  3192. * @param bool $display if set to true seperators will be added to the
  3193. * output array.
  3194. *
  3195. * @return array names and details of the functions that can be applied on
  3196. * geometry data typess.
  3197. */
  3198. function PMA_getGISFunctions($geom_type = null, $binary = true, $display = false)
  3199. {
  3200. $funcs = array();
  3201. if ($display) {
  3202. $funcs[] = array('display' => ' ');
  3203. }
  3204. // Unary functions common to all geomety types
  3205. $funcs['Dimension'] = array('params' => 1, 'type' => 'int');
  3206. $funcs['Envelope'] = array('params' => 1, 'type' => 'Polygon');
  3207. $funcs['GeometryType'] = array('params' => 1, 'type' => 'text');
  3208. $funcs['SRID'] = array('params' => 1, 'type' => 'int');
  3209. $funcs['IsEmpty'] = array('params' => 1, 'type' => 'int');
  3210. $funcs['IsSimple'] = array('params' => 1, 'type' => 'int');
  3211. $geom_type = trim(strtolower($geom_type));
  3212. if ($display && $geom_type != 'geometry' && $geom_type != 'multipoint') {
  3213. $funcs[] = array('display' => '--------');
  3214. }
  3215. // Unary functions that are specific to each geomety type
  3216. if ($geom_type == 'point') {
  3217. $funcs['X'] = array('params' => 1, 'type' => 'float');
  3218. $funcs['Y'] = array('params' => 1, 'type' => 'float');
  3219. } elseif ($geom_type == 'multipoint') {
  3220. // no fucntions here
  3221. } elseif ($geom_type == 'linestring') {
  3222. $funcs['EndPoint'] = array('params' => 1, 'type' => 'point');
  3223. $funcs['GLength'] = array('params' => 1, 'type' => 'float');
  3224. $funcs['NumPoints'] = array('params' => 1, 'type' => 'int');
  3225. $funcs['StartPoint'] = array('params' => 1, 'type' => 'point');
  3226. $funcs['IsRing'] = array('params' => 1, 'type' => 'int');
  3227. } elseif ($geom_type == 'multilinestring') {
  3228. $funcs['GLength'] = array('params' => 1, 'type' => 'float');
  3229. $funcs['IsClosed'] = array('params' => 1, 'type' => 'int');
  3230. } elseif ($geom_type == 'polygon') {
  3231. $funcs['Area'] = array('params' => 1, 'type' => 'float');
  3232. $funcs['ExteriorRing'] = array('params' => 1, 'type' => 'linestring');
  3233. $funcs['NumInteriorRings'] = array('params' => 1, 'type' => 'int');
  3234. } elseif ($geom_type == 'multipolygon') {
  3235. $funcs['Area'] = array('params' => 1, 'type' => 'float');
  3236. $funcs['Centroid'] = array('params' => 1, 'type' => 'point');
  3237. // Not yet implemented in MySQL
  3238. //$funcs['PointOnSurface'] = array('params' => 1, 'type' => 'point');
  3239. } elseif ($geom_type == 'geometrycollection') {
  3240. $funcs['NumGeometries'] = array('params' => 1, 'type' => 'int');
  3241. }
  3242. // If we are asked for binary functions as well
  3243. if ($binary) {
  3244. // section seperator
  3245. if ($display) {
  3246. $funcs[] = array('display' => '--------');
  3247. }
  3248. if (PMA_MYSQL_INT_VERSION < 50601) {
  3249. $funcs['Crosses'] = array('params' => 2, 'type' => 'int');
  3250. $funcs['Contains'] = array('params' => 2, 'type' => 'int');
  3251. $funcs['Disjoint'] = array('params' => 2, 'type' => 'int');
  3252. $funcs['Equals'] = array('params' => 2, 'type' => 'int');
  3253. $funcs['Intersects'] = array('params' => 2, 'type' => 'int');
  3254. $funcs['Overlaps'] = array('params' => 2, 'type' => 'int');
  3255. $funcs['Touches'] = array('params' => 2, 'type' => 'int');
  3256. $funcs['Within'] = array('params' => 2, 'type' => 'int');
  3257. } else {
  3258. // If MySQl version is greaeter than or equal 5.6.1, use the ST_ prefix.
  3259. $funcs['ST_Crosses'] = array('params' => 2, 'type' => 'int');
  3260. $funcs['ST_Contains'] = array('params' => 2, 'type' => 'int');
  3261. $funcs['ST_Disjoint'] = array('params' => 2, 'type' => 'int');
  3262. $funcs['ST_Equals'] = array('params' => 2, 'type' => 'int');
  3263. $funcs['ST_Intersects'] = array('params' => 2, 'type' => 'int');
  3264. $funcs['ST_Overlaps'] = array('params' => 2, 'type' => 'int');
  3265. $funcs['ST_Touches'] = array('params' => 2, 'type' => 'int');
  3266. $funcs['ST_Within'] = array('params' => 2, 'type' => 'int');
  3267. }
  3268. if ($display) {
  3269. $funcs[] = array('display' => '--------');
  3270. }
  3271. // Minimum bounding rectangle functions
  3272. $funcs['MBRContains'] = array('params' => 2, 'type' => 'int');
  3273. $funcs['MBRDisjoint'] = array('params' => 2, 'type' => 'int');
  3274. $funcs['MBREquals'] = array('params' => 2, 'type' => 'int');
  3275. $funcs['MBRIntersects'] = array('params' => 2, 'type' => 'int');
  3276. $funcs['MBROverlaps'] = array('params' => 2, 'type' => 'int');
  3277. $funcs['MBRTouches'] = array('params' => 2, 'type' => 'int');
  3278. $funcs['MBRWithin'] = array('params' => 2, 'type' => 'int');
  3279. }
  3280. return $funcs;
  3281. }
  3282. /**
  3283. * Creates a dropdown box with MySQL functions for a particular column.
  3284. *
  3285. * @param array $field Data about the column for which
  3286. * to generate the dropdown
  3287. * @param bool $insert_mode Whether the operation is 'insert'
  3288. *
  3289. * @global array $cfg PMA configuration
  3290. * @global array $analyzed_sql Analyzed SQL query
  3291. * @global mixed $data (null/string) FIXME: what is this for?
  3292. *
  3293. * @return string An HTML snippet of a dropdown list with function
  3294. * names appropriate for the requested column.
  3295. */
  3296. function PMA_getFunctionsForField($field, $insert_mode)
  3297. {
  3298. global $cfg, $analyzed_sql, $data;
  3299. $selected = '';
  3300. // Find the current type in the RestrictColumnTypes. Will result in 'FUNC_CHAR'
  3301. // or something similar. Then directly look up the entry in the
  3302. // RestrictFunctions array, which'll then reveal the available dropdown options
  3303. if (isset($cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])])
  3304. && isset($cfg['RestrictFunctions'][$cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])]])
  3305. ) {
  3306. $current_func_type = $cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])];
  3307. $dropdown = $cfg['RestrictFunctions'][$current_func_type];
  3308. $default_function = $cfg['DefaultFunctions'][$current_func_type];
  3309. } else {
  3310. $dropdown = array();
  3311. $default_function = '';
  3312. }
  3313. $dropdown_built = array();
  3314. $op_spacing_needed = false;
  3315. // what function defined as default?
  3316. // for the first timestamp we don't set the default function
  3317. // if there is a default value for the timestamp
  3318. // (not including CURRENT_TIMESTAMP)
  3319. // and the column does not have the
  3320. // ON UPDATE DEFAULT TIMESTAMP attribute.
  3321. if ($field['True_Type'] == 'timestamp'
  3322. && empty($field['Default'])
  3323. && empty($data)
  3324. && ! isset($analyzed_sql[0]['create_table_fields'][$field['Field']]['on_update_current_timestamp'])
  3325. && $analyzed_sql[0]['create_table_fields'][$field['Field']]['default_value'] != 'NULL'
  3326. ) {
  3327. $default_function = $cfg['DefaultFunctions']['first_timestamp'];
  3328. }
  3329. // For primary keys of type char(36) or varchar(36) UUID if the default function
  3330. // Only applies to insert mode, as it would silently trash data on updates.
  3331. if ($insert_mode
  3332. && $field['Key'] == 'PRI'
  3333. && ($field['Type'] == 'char(36)' || $field['Type'] == 'varchar(36)')
  3334. ) {
  3335. $default_function = $cfg['DefaultFunctions']['FUNC_UUID'];
  3336. }
  3337. // this is set only when appropriate and is always true
  3338. if (isset($field['display_binary_as_hex'])) {
  3339. $default_function = 'UNHEX';
  3340. }
  3341. // Create the output
  3342. $retval = ' <option></option>' . "\n";
  3343. // loop on the dropdown array and print all available options for that field.
  3344. foreach ($dropdown as $each_dropdown) {
  3345. $retval .= ' ';
  3346. $retval .= '<option';
  3347. if ($default_function === $each_dropdown) {
  3348. $retval .= ' selected="selected"';
  3349. }
  3350. $retval .= '>' . $each_dropdown . '</option>' . "\n";
  3351. $dropdown_built[$each_dropdown] = 'true';
  3352. $op_spacing_needed = true;
  3353. }
  3354. // For compatibility's sake, do not let out all other functions. Instead
  3355. // print a separator (blank) and then show ALL functions which weren't shown
  3356. // yet.
  3357. $cnt_functions = count($cfg['Functions']);
  3358. for ($j = 0; $j < $cnt_functions; $j++) {
  3359. if (! isset($dropdown_built[$cfg['Functions'][$j]])
  3360. || $dropdown_built[$cfg['Functions'][$j]] != 'true'
  3361. ) {
  3362. // Is current function defined as default?
  3363. $selected = ($field['first_timestamp'] && $cfg['Functions'][$j] == $cfg['DefaultFunctions']['first_timestamp'])
  3364. || (! $field['first_timestamp'] && $cfg['Functions'][$j] == $default_function)
  3365. ? ' selected="selected"'
  3366. : '';
  3367. if ($op_spacing_needed == true) {
  3368. $retval .= ' ';
  3369. $retval .= '<option value="">--------</option>' . "\n";
  3370. $op_spacing_needed = false;
  3371. }
  3372. $retval .= ' ';
  3373. $retval .= '<option' . $selected . '>' . $cfg['Functions'][$j]
  3374. . '</option>' . "\n";
  3375. }
  3376. } // end for
  3377. return $retval;
  3378. } // end PMA_getFunctionsForField()
  3379. /**
  3380. * Checks if the current user has a specific privilege and returns true if the
  3381. * user indeed has that privilege or false if (s)he doesn't. This function must
  3382. * only be used for features that are available since MySQL 5, because it
  3383. * relies on the INFORMATION_SCHEMA database to be present.
  3384. *
  3385. * Example: PMA_currentUserHasPrivilege('CREATE ROUTINE', 'mydb');
  3386. * // Checks if the currently logged in user has the global
  3387. * // 'CREATE ROUTINE' privilege or, if not, checks if the
  3388. * // user has this privilege on database 'mydb'.
  3389. *
  3390. * @param string $priv The privilege to check
  3391. * @param mixed $db null, to only check global privileges
  3392. * string, db name where to also check for privileges
  3393. * @param mixed $tbl null, to only check global/db privileges
  3394. * string, table name where to also check for privileges
  3395. *
  3396. * @return bool
  3397. */
  3398. function PMA_currentUserHasPrivilege($priv, $db = null, $tbl = null)
  3399. {
  3400. // Get the username for the current user in the format
  3401. // required to use in the information schema database.
  3402. $user = PMA_DBI_fetch_value("SELECT CURRENT_USER();");
  3403. if ($user === false) {
  3404. return false;
  3405. }
  3406. $user = explode('@', $user);
  3407. $username = "''";
  3408. $username .= str_replace("'", "''", $user[0]);
  3409. $username .= "''@''";
  3410. $username .= str_replace("'", "''", $user[1]);
  3411. $username .= "''";
  3412. // Prepage the query
  3413. $query = "SELECT `PRIVILEGE_TYPE` FROM `INFORMATION_SCHEMA`.`%s` "
  3414. . "WHERE GRANTEE='%s' AND PRIVILEGE_TYPE='%s'";
  3415. // Check global privileges first.
  3416. if (PMA_DBI_fetch_value(
  3417. sprintf(
  3418. $query,
  3419. 'USER_PRIVILEGES',
  3420. $username,
  3421. $priv
  3422. )
  3423. )
  3424. ) {
  3425. return true;
  3426. }
  3427. // If a database name was provided and user does not have the
  3428. // required global privilege, try database-wise permissions.
  3429. if ($db !== null) {
  3430. // need to escape wildcards in db and table names, see bug #3518484
  3431. $db = str_replace(array('%', '_'), array('\%', '\_'), $db);
  3432. $query .= " AND TABLE_SCHEMA='%s'";
  3433. if (PMA_DBI_fetch_value(
  3434. sprintf(
  3435. $query,
  3436. 'SCHEMA_PRIVILEGES',
  3437. $username,
  3438. $priv,
  3439. PMA_sqlAddSlashes($db)
  3440. )
  3441. )
  3442. ) {
  3443. return true;
  3444. }
  3445. } else {
  3446. // There was no database name provided and the user
  3447. // does not have the correct global privilege.
  3448. return false;
  3449. }
  3450. // If a table name was also provided and we still didn't
  3451. // find any valid privileges, try table-wise privileges.
  3452. if ($tbl !== null) {
  3453. // need to escape wildcards in db and table names, see bug #3518484
  3454. $tbl = str_replace(array('%', '_'), array('\%', '\_'), $tbl);
  3455. $query .= " AND TABLE_NAME='%s'";
  3456. if ($retval = PMA_DBI_fetch_value(
  3457. sprintf(
  3458. $query,
  3459. 'TABLE_PRIVILEGES',
  3460. $username,
  3461. $priv,
  3462. PMA_sqlAddSlashes($db),
  3463. PMA_sqlAddSlashes($tbl)
  3464. )
  3465. )
  3466. ) {
  3467. return true;
  3468. }
  3469. }
  3470. // If we reached this point, the user does not
  3471. // have even valid table-wise privileges.
  3472. return false;
  3473. }
  3474. /**
  3475. * Returns server type for current connection
  3476. *
  3477. * Known types are: Drizzle, MariaDB and MySQL (default)
  3478. *
  3479. * @return string
  3480. */
  3481. function PMA_getServerType()
  3482. {
  3483. $server_type = 'MySQL';
  3484. if (PMA_DRIZZLE) {
  3485. $server_type = 'Drizzle';
  3486. } else if (strpos(PMA_MYSQL_STR_VERSION, 'mariadb') !== false) {
  3487. $server_type = 'MariaDB';
  3488. } else if (stripos(PMA_MYSQL_VERSION_COMMENT, 'percona') !== false) {
  3489. $server_type = 'Percona Server';
  3490. }
  3491. return $server_type;
  3492. }
  3493. /**
  3494. * Analyzes the limit clause and return the start and length attributes of it.
  3495. *
  3496. * @param string $limit_clause limit clause
  3497. *
  3498. * @return array Start and length attributes of the limit clause
  3499. */
  3500. function PMA_analyzeLimitClause($limit_clause)
  3501. {
  3502. $start_and_length = explode(',', str_ireplace('LIMIT', '', $limit_clause));
  3503. return array(
  3504. 'start' => trim($start_and_length[0]),
  3505. 'length' => trim($start_and_length[1])
  3506. );
  3507. }
  3508. /**
  3509. * Outputs HTML code for print button.
  3510. *
  3511. * @return nothing
  3512. */
  3513. function PMA_printButton()
  3514. {
  3515. echo '<p class="print_ignore">';
  3516. echo '<input type="button" id="print" value="' . __('Print') . '" />';
  3517. echo '</p>';
  3518. }
  3519. /**
  3520. * Parses ENUM/SET values
  3521. *
  3522. * @param string $definition The definition of the column
  3523. * for which to parse the values
  3524. *
  3525. * @return array
  3526. */
  3527. function PMA_parseEnumSetValues($definition)
  3528. {
  3529. $values_string = htmlentities($definition);
  3530. // There is a JS port of the below parser in functions.js
  3531. // If you are fixing something here,
  3532. // you need to also update the JS port.
  3533. $values = array();
  3534. $in_string = false;
  3535. $buffer = '';
  3536. for ($i=0; $i<strlen($values_string); $i++) {
  3537. $curr = $values_string[$i];
  3538. $next = $i == strlen($values_string)-1 ? '' : $values_string[$i+1];
  3539. if (! $in_string && $curr == "'") {
  3540. $in_string = true;
  3541. } else if ($in_string && $curr == "\\" && $next == "\\") {
  3542. $buffer .= "&#92;";
  3543. $i++;
  3544. } else if ($in_string && $next == "'" && ($curr == "'" || $curr == "\\")) {
  3545. $buffer .= "&#39;";
  3546. $i++;
  3547. } else if ($in_string && $curr == "'") {
  3548. $in_string = false;
  3549. $values[] = $buffer;
  3550. $buffer = '';
  3551. } else if ($in_string) {
  3552. $buffer .= $curr;
  3553. }
  3554. }
  3555. if (strlen($buffer) > 0) {
  3556. // The leftovers in the buffer are the last value (if any)
  3557. $values[] = $buffer;
  3558. }
  3559. return $values;
  3560. }
  3561. ?>