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

/moodle1917/configuracionCated/phpmyadmin/libraries/Util.class.php

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