PageRenderTime 39ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 1ms

/libraries/Util.class.php

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