Translated using Weblate (Slovenian)
[phpmyadmin.git] / libraries / Util.php
blobb24a5c083b1ca5ed487a0f96a0255ecb54e67d5e
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * Hold the PMA\libraries\Util class
6 * @package PhpMyAdmin
7 */
8 namespace PMA\libraries;
10 use PMA\libraries\plugins\ImportPlugin;
11 use PhpMyAdmin\SqlParser\Context;
12 use PhpMyAdmin\SqlParser\Lexer;
13 use PhpMyAdmin\SqlParser\Parser;
14 use PhpMyAdmin\SqlParser\Token;
15 use stdClass;
16 use PMA\libraries\URL;
17 use PMA\libraries\Sanitize;
18 use PMA\libraries\Template;
19 use PhpMyAdmin\SqlParser\Utils\Error as ParserError;
21 if (! defined('PHPMYADMIN')) {
22 exit;
25 /**
26 * Misc functions used all over the scripts.
28 * @package PhpMyAdmin
30 class Util
32 /**
33 * Checks whether configuration value tells to show icons.
35 * @param string $value Configuration option name
37 * @return boolean Whether to show icons.
39 public static function showIcons($value)
41 return in_array($GLOBALS['cfg'][$value], array('icons', 'both'));
44 /**
45 * Checks whether configuration value tells to show text.
47 * @param string $value Configuration option name
49 * @return boolean Whether to show text.
51 public static function showText($value)
53 return in_array($GLOBALS['cfg'][$value], array('text', 'both'));
56 /**
57 * Returns an HTML IMG tag for a particular icon from a theme,
58 * which may be an actual file or an icon from a sprite.
59 * This function takes into account the ActionLinksMode
60 * configuration setting and wraps the image tag in a span tag.
62 * @param string $icon name of icon file
63 * @param string $alternate alternate text
64 * @param boolean $force_text whether to force alternate text to be displayed
65 * @param boolean $menu_icon whether this icon is for the menu bar or not
66 * @param string $control_param which directive controls the display
68 * @return string an html snippet
70 public static function getIcon(
71 $icon,
72 $alternate = '',
73 $force_text = false,
74 $menu_icon = false,
75 $control_param = 'ActionLinksMode'
76 ) {
77 $include_icon = $include_text = false;
78 if (self::showIcons($control_param)) {
79 $include_icon = true;
81 if ($force_text
82 || self::showText($control_param)
83 ) {
84 $include_text = true;
86 // Sometimes use a span (we rely on this in js/sql.js). But for menu bar
87 // we don't need a span
88 $button = $menu_icon ? '' : '<span class="nowrap">';
89 if ($include_icon) {
90 $button .= self::getImage($icon, $alternate);
92 if ($include_icon && $include_text) {
93 $button .= '&nbsp;';
95 if ($include_text) {
96 $button .= $alternate;
98 $button .= $menu_icon ? '' : '</span>';
100 return $button;
104 * Returns an HTML IMG tag for a particular image from a theme,
105 * which may be an actual file or an icon from a sprite
107 * @param string $image The name of the file to get
108 * @param string $alternate Used to set 'alt' and 'title' attributes
109 * of the image
110 * @param array $attributes An associative array of other attributes
112 * @return string an html IMG tag
114 public static function getImage($image, $alternate = '', $attributes = array())
116 static $sprites; // cached list of available sprites (if any)
117 if (defined('TESTSUITE')) {
118 // prevent caching in testsuite
119 unset($sprites);
122 $is_sprite = false;
123 $alternate = htmlspecialchars($alternate);
125 // If it's the first time this function is called
126 if (! isset($sprites)) {
127 $sprites = array();
128 // Try to load the list of sprites
129 if (isset($_SESSION['PMA_Theme'])) {
130 $sprites = $_SESSION['PMA_Theme']->getSpriteData();
134 // Check if we have the requested image as a sprite
135 // and set $url accordingly
136 $class = str_replace(array('.gif','.png'), '', $image);
137 if (array_key_exists($class, $sprites)) {
138 $is_sprite = true;
139 $url = (defined('PMA_TEST_THEME') ? '../' : '') . 'themes/dot.gif';
140 } elseif (isset($GLOBALS['pmaThemeImage'])) {
141 $url = $GLOBALS['pmaThemeImage'] . $image;
142 } else {
143 $url = './themes/pmahomme/' . $image;
146 // set class attribute
147 if ($is_sprite) {
148 if (isset($attributes['class'])) {
149 $attributes['class'] = "icon ic_$class " . $attributes['class'];
150 } else {
151 $attributes['class'] = "icon ic_$class";
155 // set all other attributes
156 $attr_str = '';
157 foreach ($attributes as $key => $value) {
158 if (! in_array($key, array('alt', 'title'))) {
159 $attr_str .= " $key=\"$value\"";
163 // override the alt attribute
164 if (isset($attributes['alt'])) {
165 $alt = $attributes['alt'];
166 } else {
167 $alt = $alternate;
170 // override the title attribute
171 if (isset($attributes['title'])) {
172 $title = $attributes['title'];
173 } else {
174 $title = $alternate;
177 // generate the IMG tag
178 $template = '<img src="%s" title="%s" alt="%s"%s />';
179 $retval = sprintf($template, $url, $title, $alt, $attr_str);
181 return $retval;
185 * Returns the formatted maximum size for an upload
187 * @param integer $max_upload_size the size
189 * @return string the message
191 * @access public
193 public static function getFormattedMaximumUploadSize($max_upload_size)
195 // I have to reduce the second parameter (sensitiveness) from 6 to 4
196 // to avoid weird results like 512 kKib
197 list($max_size, $max_unit) = self::formatByteDown($max_upload_size, 4);
198 return '(' . sprintf(__('Max: %s%s'), $max_size, $max_unit) . ')';
202 * Generates a hidden field which should indicate to the browser
203 * the maximum size for upload
205 * @param integer $max_size the size
207 * @return string the INPUT field
209 * @access public
211 public static function generateHiddenMaxFileSize($max_size)
213 return '<input type="hidden" name="MAX_FILE_SIZE" value="'
214 . $max_size . '" />';
218 * Add slashes before "_" and "%" characters for using them in MySQL
219 * database, table and field names.
220 * Note: This function does not escape backslashes!
222 * @param string $name the string to escape
224 * @return string the escaped string
226 * @access public
228 public static function escapeMysqlWildcards($name)
230 return strtr($name, array('_' => '\\_', '%' => '\\%'));
231 } // end of the 'escapeMysqlWildcards()' function
234 * removes slashes before "_" and "%" characters
235 * Note: This function does not unescape backslashes!
237 * @param string $name the string to escape
239 * @return string the escaped string
241 * @access public
243 public static function unescapeMysqlWildcards($name)
245 return strtr($name, array('\\_' => '_', '\\%' => '%'));
246 } // end of the 'unescapeMysqlWildcards()' function
249 * removes quotes (',",`) from a quoted string
251 * checks if the string is quoted and removes this quotes
253 * @param string $quoted_string string to remove quotes from
254 * @param string $quote type of quote to remove
256 * @return string unqoted string
258 public static function unQuote($quoted_string, $quote = null)
260 $quotes = array();
262 if ($quote === null) {
263 $quotes[] = '`';
264 $quotes[] = '"';
265 $quotes[] = "'";
266 } else {
267 $quotes[] = $quote;
270 foreach ($quotes as $quote) {
271 if (mb_substr($quoted_string, 0, 1) === $quote
272 && mb_substr($quoted_string, -1, 1) === $quote
274 $unquoted_string = mb_substr($quoted_string, 1, -1);
275 // replace escaped quotes
276 $unquoted_string = str_replace(
277 $quote . $quote,
278 $quote,
279 $unquoted_string
281 return $unquoted_string;
285 return $quoted_string;
289 * format sql strings
291 * @param string $sqlQuery raw SQL string
292 * @param boolean $truncate truncate the query if it is too long
294 * @return string the formatted sql
296 * @global array $cfg the configuration array
298 * @access public
299 * @todo move into PMA_Sql
301 public static function formatSql($sqlQuery, $truncate = false)
303 global $cfg;
305 if ($truncate
306 && mb_strlen($sqlQuery) > $cfg['MaxCharactersInDisplayedSQL']
308 $sqlQuery = mb_substr(
309 $sqlQuery,
311 $cfg['MaxCharactersInDisplayedSQL']
312 ) . '[...]';
314 return '<code class="sql"><pre>' . "\n"
315 . htmlspecialchars($sqlQuery) . "\n"
316 . '</pre></code>';
317 } // end of the "formatSql()" function
320 * Displays a link to the documentation as an icon
322 * @param string $link documentation link
323 * @param string $target optional link target
324 * @param boolean $bbcode optional flag indicating whether to output bbcode
326 * @return string the html link
328 * @access public
330 public static function showDocLink($link, $target = 'documentation', $bbcode = false)
332 if($bbcode){
333 return "[a@$link@$target][dochelpicon][/a]";
334 }else{
335 return '<a href="' . $link . '" target="' . $target . '">'
336 . self::getImage('b_help.png', __('Documentation'))
337 . '</a>';
339 } // end of the 'showDocLink()' function
342 * Get a URL link to the official MySQL documentation
344 * @param string $link contains name of page/anchor that is being linked
345 * @param string $anchor anchor to page part
347 * @return string the URL link
349 * @access public
351 public static function getMySQLDocuURL($link, $anchor = '')
353 // Fixup for newly used names:
354 $link = str_replace('_', '-', mb_strtolower($link));
356 if (empty($link)) {
357 $link = 'index';
359 $mysql = '5.5';
360 $lang = 'en';
361 if (defined('PMA_MYSQL_INT_VERSION')) {
362 if (PMA_MYSQL_INT_VERSION >= 50700) {
363 $mysql = '5.7';
364 } elseif (PMA_MYSQL_INT_VERSION >= 50600) {
365 $mysql = '5.6';
366 } elseif (PMA_MYSQL_INT_VERSION >= 50500) {
367 $mysql = '5.5';
370 $url = 'https://dev.mysql.com/doc/refman/'
371 . $mysql . '/' . $lang . '/' . $link . '.html';
372 if (! empty($anchor)) {
373 $url .= '#' . $anchor;
376 return PMA_linkURL($url);
380 * Displays a link to the official MySQL documentation
382 * @param string $link contains name of page/anchor that is being linked
383 * @param bool $big_icon whether to use big icon (like in left frame)
384 * @param string $anchor anchor to page part
385 * @param bool $just_open whether only the opening <a> tag should be returned
387 * @return string the html link
389 * @access public
391 public static function showMySQLDocu(
392 $link,
393 $big_icon = false,
394 $anchor = '',
395 $just_open = false
397 $url = self::getMySQLDocuURL($link, $anchor);
398 $open_link = '<a href="' . $url . '" target="mysql_doc">';
399 if ($just_open) {
400 return $open_link;
401 } elseif ($big_icon) {
402 return $open_link
403 . self::getImage('b_sqlhelp.png', __('Documentation')) . '</a>';
404 } else {
405 return self::showDocLink($url, 'mysql_doc');
407 } // end of the 'showMySQLDocu()' function
410 * Returns link to documentation.
412 * @param string $page Page in documentation
413 * @param string $anchor Optional anchor in page
415 * @return string URL
417 public static function getDocuLink($page, $anchor = '')
419 /* Construct base URL */
420 $url = $page . '.html';
421 if (!empty($anchor)) {
422 $url .= '#' . $anchor;
425 /* Check if we have built local documentation */
426 if (defined('TESTSUITE')) {
427 /* Provide consistent URL for testsuite */
428 return PMA_linkURL('https://docs.phpmyadmin.net/en/latest/' . $url);
429 } elseif (@file_exists('doc/html/index.html')) {
430 if (defined('PMA_SETUP')) {
431 return '../doc/html/' . $url;
432 } else {
433 return './doc/html/' . $url;
435 } else {
436 /* TODO: Should link to correct branch for released versions */
437 return PMA_linkURL('https://docs.phpmyadmin.net/en/latest/' . $url);
442 * Displays a link to the phpMyAdmin documentation
444 * @param string $page Page in documentation
445 * @param string $anchor Optional anchor in page
446 * @param boolean $bbcode Optional flag indicating whether to output bbcode
448 * @return string the html link
450 * @access public
452 public static function showDocu($page, $anchor = '', $bbcode = false)
454 return self::showDocLink(self::getDocuLink($page, $anchor), 'documentation', $bbcode);
455 } // end of the 'showDocu()' function
458 * Displays a link to the PHP documentation
460 * @param string $target anchor in documentation
462 * @return string the html link
464 * @access public
466 public static function showPHPDocu($target)
468 $url = PMA_getPHPDocLink($target);
470 return self::showDocLink($url);
471 } // end of the 'showPHPDocu()' function
474 * Returns HTML code for a tooltip
476 * @param string $message the message for the tooltip
478 * @return string
480 * @access public
482 public static function showHint($message)
484 if ($GLOBALS['cfg']['ShowHint']) {
485 $classClause = ' class="pma_hint"';
486 } else {
487 $classClause = '';
489 return '<span' . $classClause . '>'
490 . self::getImage('b_help.png')
491 . '<span class="hide">' . $message . '</span>'
492 . '</span>';
496 * Displays a MySQL error message in the main panel when $exit is true.
497 * Returns the error message otherwise.
499 * @param string|bool $server_msg Server's error message.
500 * @param string $sql_query The SQL query that failed.
501 * @param bool $is_modify_link Whether to show a "modify" link or not.
502 * @param string $back_url URL for the "back" link (full path is
503 * not required).
504 * @param bool $exit Whether execution should be stopped or
505 * the error message should be returned.
507 * @return string
509 * @global string $table The current table.
510 * @global string $db The current database.
512 * @access public
514 public static function mysqlDie(
515 $server_msg = '',
516 $sql_query = '',
517 $is_modify_link = true,
518 $back_url = '',
519 $exit = true
521 global $table, $db;
524 * Error message to be built.
525 * @var string $error_msg
527 $error_msg = '';
529 // Checking for any server errors.
530 if (empty($server_msg)) {
531 $server_msg = $GLOBALS['dbi']->getError();
534 // Finding the query that failed, if not specified.
535 if ((empty($sql_query) && (!empty($GLOBALS['sql_query'])))) {
536 $sql_query = $GLOBALS['sql_query'];
538 $sql_query = trim($sql_query);
541 * The lexer used for analysis.
542 * @var Lexer $lexer
544 $lexer = new Lexer($sql_query);
547 * The parser used for analysis.
548 * @var Parser $parser
550 $parser = new Parser($lexer->list);
553 * The errors found by the lexer and the parser.
554 * @var array $errors
556 $errors = ParserError::get(array($lexer, $parser));
558 if (empty($sql_query)) {
559 $formatted_sql = '';
560 } elseif (count($errors)) {
561 $formatted_sql = htmlspecialchars($sql_query);
562 } else {
563 $formatted_sql = self::formatSql($sql_query, true);
566 $error_msg .= '<div class="error"><h1>' . __('Error') . '</h1>';
568 // For security reasons, if the MySQL refuses the connection, the query
569 // is hidden so no details are revealed.
570 if ((!empty($sql_query)) && (!(mb_strstr($sql_query, 'connect')))) {
571 // Static analysis errors.
572 if (!empty($errors)) {
573 $error_msg .= '<p><strong>' . __('Static analysis:')
574 . '</strong></p>';
575 $error_msg .= '<p>' . sprintf(
576 __('%d errors were found during analysis.'),
577 count($errors)
578 ) . '</p>';
579 $error_msg .= '<p><ol>';
580 $error_msg .= implode(
581 ParserError::format(
582 $errors,
583 '<li>%2$s (near "%4$s" at position %5$d)</li>'
586 $error_msg .= '</ol></p>';
589 // Display the SQL query and link to MySQL documentation.
590 $error_msg .= '<p><strong>' . __('SQL query:') . '</strong>' . "\n";
591 $formattedSqlToLower = mb_strtolower($formatted_sql);
593 // TODO: Show documentation for all statement types.
594 if (mb_strstr($formattedSqlToLower, 'select')) {
595 // please show me help to the error on select
596 $error_msg .= self::showMySQLDocu('SELECT');
599 if ($is_modify_link) {
600 $_url_params = array(
601 'sql_query' => $sql_query,
602 'show_query' => 1,
604 if (strlen($table) > 0) {
605 $_url_params['db'] = $db;
606 $_url_params['table'] = $table;
607 $doedit_goto = '<a href="tbl_sql.php'
608 . URL::getCommon($_url_params) . '">';
609 } elseif (strlen($db) > 0) {
610 $_url_params['db'] = $db;
611 $doedit_goto = '<a href="db_sql.php'
612 . URL::getCommon($_url_params) . '">';
613 } else {
614 $doedit_goto = '<a href="server_sql.php'
615 . URL::getCommon($_url_params) . '">';
618 $error_msg .= $doedit_goto
619 . self::getIcon('b_edit.png', __('Edit'))
620 . '</a>';
623 $error_msg .= ' </p>' . "\n"
624 . '<p>' . "\n"
625 . $formatted_sql . "\n"
626 . '</p>' . "\n";
629 // Display server's error.
630 if (!empty($server_msg)) {
631 $server_msg = preg_replace(
632 "@((\015\012)|(\015)|(\012)){3,}@",
633 "\n\n",
634 $server_msg
637 // Adds a link to MySQL documentation.
638 $error_msg .= '<p>' . "\n"
639 . ' <strong>' . __('MySQL said: ') . '</strong>'
640 . self::showMySQLDocu('Error-messages-server')
641 . "\n"
642 . '</p>' . "\n";
644 // The error message will be displayed within a CODE segment.
645 // To preserve original formatting, but allow word-wrapping,
646 // a couple of replacements are done.
647 // All non-single blanks and TAB-characters are replaced with their
648 // HTML-counterpart
649 $server_msg = str_replace(
650 array(' ', "\t"),
651 array('&nbsp;&nbsp;', '&nbsp;&nbsp;&nbsp;&nbsp;'),
652 $server_msg
655 // Replace line breaks
656 $server_msg = nl2br($server_msg);
658 $error_msg .= '<code>' . $server_msg . '</code><br/>';
661 $error_msg .= '</div>';
662 $_SESSION['Import_message']['message'] = $error_msg;
664 if (!$exit) {
665 return $error_msg;
669 * If this is an AJAX request, there is no "Back" link and
670 * `Response()` is used to send the response.
672 $response = Response::getInstance();
673 if ($response->isAjax()) {
674 $response->setRequestStatus(false);
675 $response->addJSON('message', $error_msg);
676 exit;
679 if (!empty($back_url)) {
680 if (mb_strstr($back_url, '?')) {
681 $back_url .= '&amp;no_history=true';
682 } else {
683 $back_url .= '?no_history=true';
686 $_SESSION['Import_message']['go_back_url'] = $back_url;
688 $error_msg .= '<fieldset class="tblFooters">'
689 . '[ <a href="' . $back_url . '">' . __('Back') . '</a> ]'
690 . '</fieldset>' . "\n\n";
693 exit($error_msg);
697 * Check the correct row count
699 * @param string $db the db name
700 * @param array $table the table infos
702 * @return int $rowCount the possibly modified row count
705 private static function _checkRowCount($db, $table)
707 $rowCount = 0;
709 if ($table['Rows'] === null) {
710 // Do not check exact row count here,
711 // if row count is invalid possibly the table is defect
712 // and this would break the navigation panel;
713 // but we can check row count if this is a view or the
714 // information_schema database
715 // since Table::countRecords() returns a limited row count
716 // in this case.
718 // set this because Table::countRecords() can use it
719 $tbl_is_view = $table['TABLE_TYPE'] == 'VIEW';
721 if ($tbl_is_view || $GLOBALS['dbi']->isSystemSchema($db)) {
722 $rowCount = $GLOBALS['dbi']
723 ->getTable($db, $table['Name'])
724 ->countRecords();
727 return $rowCount;
731 * returns array with tables of given db with extended information and grouped
733 * @param string $db name of db
734 * @param string $tables name of tables
735 * @param integer $limit_offset list offset
736 * @param int|bool $limit_count max tables to return
738 * @return array (recursive) grouped table list
740 public static function getTableList(
741 $db,
742 $tables = null,
743 $limit_offset = 0,
744 $limit_count = false
746 $sep = $GLOBALS['cfg']['NavigationTreeTableSeparator'];
748 if ($tables === null) {
749 $tables = $GLOBALS['dbi']->getTablesFull(
750 $db,
752 false,
753 null,
754 $limit_offset,
755 $limit_count
757 if ($GLOBALS['cfg']['NaturalOrder']) {
758 uksort($tables, 'strnatcasecmp');
762 if (count($tables) < 1) {
763 return $tables;
766 $default = array(
767 'Name' => '',
768 'Rows' => 0,
769 'Comment' => '',
770 'disp_name' => '',
773 $table_groups = array();
775 foreach ($tables as $table_name => $table) {
776 $table['Rows'] = self::_checkRowCount($db, $table);
778 // in $group we save the reference to the place in $table_groups
779 // where to store the table info
780 if ($GLOBALS['cfg']['NavigationTreeEnableGrouping']
781 && $sep && mb_strstr($table_name, $sep)
783 $parts = explode($sep, $table_name);
785 $group =& $table_groups;
786 $i = 0;
787 $group_name_full = '';
788 $parts_cnt = count($parts) - 1;
790 while (($i < $parts_cnt)
791 && ($i < $GLOBALS['cfg']['NavigationTreeTableLevel'])
793 $group_name = $parts[$i] . $sep;
794 $group_name_full .= $group_name;
796 if (! isset($group[$group_name])) {
797 $group[$group_name] = array();
798 $group[$group_name]['is' . $sep . 'group'] = true;
799 $group[$group_name]['tab' . $sep . 'count'] = 1;
800 $group[$group_name]['tab' . $sep . 'group']
801 = $group_name_full;
803 } elseif (! isset($group[$group_name]['is' . $sep . 'group'])) {
804 $table = $group[$group_name];
805 $group[$group_name] = array();
806 $group[$group_name][$group_name] = $table;
807 $group[$group_name]['is' . $sep . 'group'] = true;
808 $group[$group_name]['tab' . $sep . 'count'] = 1;
809 $group[$group_name]['tab' . $sep . 'group']
810 = $group_name_full;
812 } else {
813 $group[$group_name]['tab' . $sep . 'count']++;
816 $group =& $group[$group_name];
817 $i++;
820 } else {
821 if (! isset($table_groups[$table_name])) {
822 $table_groups[$table_name] = array();
824 $group =& $table_groups;
827 $table['disp_name'] = $table['Name'];
828 $group[$table_name] = array_merge($default, $table);
831 return $table_groups;
834 /* ----------------------- Set of misc functions ----------------------- */
837 * Adds backquotes on both sides of a database, table or field name.
838 * and escapes backquotes inside the name with another backquote
840 * example:
841 * <code>
842 * echo backquote('owner`s db'); // `owner``s db`
844 * </code>
846 * @param mixed $a_name the database, table or field name to "backquote"
847 * or array of it
848 * @param boolean $do_it a flag to bypass this function (used by dump
849 * functions)
851 * @return mixed the "backquoted" database, table or field name
853 * @access public
855 public static function backquote($a_name, $do_it = true)
857 if (is_array($a_name)) {
858 foreach ($a_name as &$data) {
859 $data = self::backquote($data, $do_it);
861 return $a_name;
864 if (! $do_it) {
865 if (!(Context::isKeyword($a_name) & Token::FLAG_KEYWORD_RESERVED)
867 return $a_name;
871 // '0' is also empty for php :-(
872 if (strlen($a_name) > 0 && $a_name !== '*') {
873 return '`' . str_replace('`', '``', $a_name) . '`';
874 } else {
875 return $a_name;
877 } // end of the 'backquote()' function
880 * Adds backquotes on both sides of a database, table or field name.
881 * in compatibility mode
883 * example:
884 * <code>
885 * echo backquoteCompat('owner`s db'); // `owner``s db`
887 * </code>
889 * @param mixed $a_name the database, table or field name to
890 * "backquote" or array of it
891 * @param string $compatibility string compatibility mode (used by dump
892 * functions)
893 * @param boolean $do_it a flag to bypass this function (used by dump
894 * functions)
896 * @return mixed the "backquoted" database, table or field name
898 * @access public
900 public static function backquoteCompat(
901 $a_name,
902 $compatibility = 'MSSQL',
903 $do_it = true
905 if (is_array($a_name)) {
906 foreach ($a_name as &$data) {
907 $data = self::backquoteCompat($data, $compatibility, $do_it);
909 return $a_name;
912 if (! $do_it) {
913 if (!Context::isKeyword($a_name)) {
914 return $a_name;
918 // @todo add more compatibility cases (ORACLE for example)
919 switch ($compatibility) {
920 case 'MSSQL':
921 $quote = '"';
922 break;
923 default:
924 $quote = "`";
925 break;
928 // '0' is also empty for php :-(
929 if (strlen($a_name) > 0 && $a_name !== '*') {
930 return $quote . $a_name . $quote;
931 } else {
932 return $a_name;
934 } // end of the 'backquoteCompat()' function
937 * Prepare the message and the query
938 * usually the message is the result of the query executed
940 * @param Message|string $message the message to display
941 * @param string $sql_query the query to display
942 * @param string $type the type (level) of the message
944 * @return string
946 * @access public
948 public static function getMessage(
949 $message,
950 $sql_query = null,
951 $type = 'notice'
953 global $cfg;
954 $retval = '';
956 if (null === $sql_query) {
957 if (! empty($GLOBALS['display_query'])) {
958 $sql_query = $GLOBALS['display_query'];
959 } elseif (! empty($GLOBALS['unparsed_sql'])) {
960 $sql_query = $GLOBALS['unparsed_sql'];
961 } elseif (! empty($GLOBALS['sql_query'])) {
962 $sql_query = $GLOBALS['sql_query'];
963 } else {
964 $sql_query = '';
968 $render_sql = $cfg['ShowSQL'] == true && ! empty($sql_query) && $sql_query !== ';';
970 if (isset($GLOBALS['using_bookmark_message'])) {
971 $retval .= $GLOBALS['using_bookmark_message']->getDisplay();
972 unset($GLOBALS['using_bookmark_message']);
975 if ($render_sql) {
976 $retval .= '<div class="result_query"'
977 . ' style="text-align: ' . $GLOBALS['cell_align_left'] . '"'
978 . '>' . "\n";
981 if ($message instanceof Message) {
982 if (isset($GLOBALS['special_message'])) {
983 $message->addText($GLOBALS['special_message']);
984 unset($GLOBALS['special_message']);
986 $retval .= $message->getDisplay();
987 } else {
988 $retval .= '<div class="' . $type . '">';
989 $retval .= Sanitize::sanitize($message);
990 if (isset($GLOBALS['special_message'])) {
991 $retval .= Sanitize::sanitize($GLOBALS['special_message']);
992 unset($GLOBALS['special_message']);
994 $retval .= '</div>';
997 if ($render_sql) {
998 $query_too_big = false;
1000 $queryLength = mb_strlen($sql_query);
1001 if ($queryLength > $cfg['MaxCharactersInDisplayedSQL']) {
1002 // when the query is large (for example an INSERT of binary
1003 // data), the parser chokes; so avoid parsing the query
1004 $query_too_big = true;
1005 $query_base = mb_substr(
1006 $sql_query,
1008 $cfg['MaxCharactersInDisplayedSQL']
1009 ) . '[...]';
1010 } else {
1011 $query_base = $sql_query;
1014 // Html format the query to be displayed
1015 // If we want to show some sql code it is easiest to create it here
1016 /* SQL-Parser-Analyzer */
1018 if (! empty($GLOBALS['show_as_php'])) {
1019 $new_line = '\\n"<br />' . "\n" . '&nbsp;&nbsp;&nbsp;&nbsp;. "';
1020 $query_base = '$sql = \'' . $query_base;
1021 $query_base = '<code class="php"><pre>' . "\n"
1022 . htmlspecialchars(addslashes($query_base));
1023 $query_base = preg_replace(
1024 '/((\015\012)|(\015)|(\012))/',
1025 $new_line,
1026 $query_base
1028 $query_base = '$sql = \'' . $query_base . '"';
1029 } elseif ($query_too_big) {
1030 $query_base = htmlspecialchars($query_base);
1031 } else {
1032 $query_base = self::formatSql($query_base);
1035 // Prepares links that may be displayed to edit/explain the query
1036 // (don't go to default pages, we must go to the page
1037 // where the query box is available)
1039 // Basic url query part
1040 $url_params = array();
1041 if (! isset($GLOBALS['db'])) {
1042 $GLOBALS['db'] = '';
1044 if (strlen($GLOBALS['db']) > 0) {
1045 $url_params['db'] = $GLOBALS['db'];
1046 if (strlen($GLOBALS['table']) > 0) {
1047 $url_params['table'] = $GLOBALS['table'];
1048 $edit_link = 'tbl_sql.php';
1049 } else {
1050 $edit_link = 'db_sql.php';
1052 } else {
1053 $edit_link = 'server_sql.php';
1056 // Want to have the query explained
1057 // but only explain a SELECT (that has not been explained)
1058 /* SQL-Parser-Analyzer */
1059 $explain_link = '';
1060 $is_select = preg_match('@^SELECT[[:space:]]+@i', $sql_query);
1061 if (! empty($cfg['SQLQuery']['Explain']) && ! $query_too_big) {
1062 $explain_params = $url_params;
1063 if ($is_select) {
1064 $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
1065 $explain_link = ' ['
1066 . self::linkOrButton(
1067 'import.php' . URL::getCommon($explain_params),
1068 __('Explain SQL')
1069 ) . ']';
1070 } elseif (preg_match(
1071 '@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i',
1072 $sql_query
1073 )) {
1074 $explain_params['sql_query']
1075 = mb_substr($sql_query, 8);
1076 $explain_link = ' ['
1077 . self::linkOrButton(
1078 'import.php' . URL::getCommon($explain_params),
1079 __('Skip Explain SQL')
1080 ) . ']';
1081 $url = 'https://mariadb.org/explain_analyzer/analyze/'
1082 . '?client=phpMyAdmin&raw_explain='
1083 . urlencode(self::_generateRowQueryOutput($sql_query));
1084 $explain_link .= ' ['
1085 . self::linkOrButton(
1086 htmlspecialchars('url.php?url=' . urlencode($url)),
1087 sprintf(__('Analyze Explain at %s'), 'mariadb.org'),
1088 array(),
1089 true,
1090 false,
1091 '_blank'
1092 ) . ']';
1094 } //show explain
1096 $url_params['sql_query'] = $sql_query;
1097 $url_params['show_query'] = 1;
1099 // even if the query is big and was truncated, offer the chance
1100 // to edit it (unless it's enormous, see linkOrButton() )
1101 if (! empty($cfg['SQLQuery']['Edit'])
1102 && empty($GLOBALS['show_as_php'])
1104 $edit_link .= URL::getCommon($url_params) . '#querybox';
1105 $edit_link = ' ['
1106 . self::linkOrButton($edit_link, __('Edit'))
1107 . ']';
1108 } else {
1109 $edit_link = '';
1112 // Also we would like to get the SQL formed in some nice
1113 // php-code
1114 if (! empty($cfg['SQLQuery']['ShowAsPHP']) && ! $query_too_big) {
1116 if (! empty($GLOBALS['show_as_php'])) {
1117 $php_link = ' ['
1118 . self::linkOrButton(
1119 'import.php' . URL::getCommon($url_params),
1120 __('Without PHP code'),
1121 array(),
1122 true,
1123 false,
1125 true
1127 . ']';
1129 $php_link .= ' ['
1130 . self::linkOrButton(
1131 'import.php' . URL::getCommon($url_params),
1132 __('Submit query'),
1133 array(),
1134 true,
1135 false,
1137 true
1139 . ']';
1140 } else {
1141 $php_params = $url_params;
1142 $php_params['show_as_php'] = 1;
1143 $_message = __('Create PHP code');
1144 $php_link = ' ['
1145 . self::linkOrButton(
1146 'import.php' . URL::getCommon($php_params),
1147 $_message
1149 . ']';
1151 } else {
1152 $php_link = '';
1153 } //show as php
1155 // Refresh query
1156 if (! empty($cfg['SQLQuery']['Refresh'])
1157 && ! isset($GLOBALS['show_as_php']) // 'Submit query' does the same
1158 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)
1160 $refresh_link = 'import.php' . URL::getCommon($url_params);
1161 $refresh_link = ' ['
1162 . self::linkOrButton($refresh_link, __('Refresh')) . ']';
1163 } else {
1164 $refresh_link = '';
1165 } //refresh
1167 $retval .= '<div class="sqlOuter">';
1168 $retval .= $query_base;
1170 //Clean up the end of the PHP
1171 if (! empty($GLOBALS['show_as_php'])) {
1172 $retval .= '\';' . "\n"
1173 . '</pre></code>';
1175 $retval .= '</div>';
1177 $retval .= '<div class="tools print_ignore">';
1178 $retval .= '<form action="sql.php" method="post">';
1179 $retval .= URL::getHiddenInputs($GLOBALS['db'], $GLOBALS['table']);
1180 $retval .= '<input type="hidden" name="sql_query" value="'
1181 . htmlspecialchars($sql_query) . '" />';
1183 // avoid displaying a Profiling checkbox that could
1184 // be checked, which would reexecute an INSERT, for example
1185 if (! empty($refresh_link) && self::profilingSupported()) {
1186 $retval .= '<input type="hidden" name="profiling_form" value="1" />';
1187 $retval .= Template::get('checkbox')
1188 ->render(
1189 array(
1190 'html_field_name' => 'profiling',
1191 'label' => __('Profiling'),
1192 'checked' => isset($_SESSION['profiling']),
1193 'onclick' => true,
1194 'html_field_id' => '',
1198 $retval .= '</form>';
1201 * TODO: Should we have $cfg['SQLQuery']['InlineEdit']?
1203 if (! empty($cfg['SQLQuery']['Edit'])
1204 && ! $query_too_big
1205 && empty($GLOBALS['show_as_php'])
1207 $inline_edit_link = ' ['
1208 . self::linkOrButton(
1209 '#',
1210 _pgettext('Inline edit query', 'Edit inline'),
1211 array('class' => 'inline_edit_sql')
1213 . ']';
1214 } else {
1215 $inline_edit_link = '';
1217 $retval .= $inline_edit_link . $edit_link . $explain_link . $php_link
1218 . $refresh_link;
1219 $retval .= '</div>';
1221 $retval .= '</div>';
1224 return $retval;
1225 } // end of the 'getMessage()' function
1228 * Execute an EXPLAIN query and formats results similar to MySQL command line
1229 * utility.
1231 * @param string $sqlQuery EXPLAIN query
1233 * @return string query resuls
1235 private static function _generateRowQueryOutput($sqlQuery)
1237 $ret = '';
1238 $result = $GLOBALS['dbi']->query($sqlQuery);
1239 if ($result) {
1240 $devider = '+';
1241 $columnNames = '|';
1242 $fieldsMeta = $GLOBALS['dbi']->getFieldsMeta($result);
1243 foreach ($fieldsMeta as $meta) {
1244 $devider .= '---+';
1245 $columnNames .= ' ' . $meta->name . ' |';
1247 $devider .= "\n";
1249 $ret .= $devider . $columnNames . "\n" . $devider;
1250 while ($row = $GLOBALS['dbi']->fetchRow($result)) {
1251 $values = '|';
1252 foreach ($row as $value) {
1253 if (is_null($value)) {
1254 $value = 'NULL';
1256 $values .= ' ' . $value . ' |';
1258 $ret .= $values . "\n";
1260 $ret .= $devider;
1262 return $ret;
1266 * Verifies if current MySQL server supports profiling
1268 * @access public
1270 * @return boolean whether profiling is supported
1272 public static function profilingSupported()
1274 if (!self::cacheExists('profiling_supported')) {
1275 // 5.0.37 has profiling but for example, 5.1.20 does not
1276 // (avoid a trip to the server for MySQL before 5.0.37)
1277 // and do not set a constant as we might be switching servers
1278 if (defined('PMA_MYSQL_INT_VERSION')
1279 && $GLOBALS['dbi']->fetchValue("SELECT @@have_profiling")
1281 self::cacheSet('profiling_supported', true);
1282 } else {
1283 self::cacheSet('profiling_supported', false);
1287 return self::cacheGet('profiling_supported');
1291 * Formats $value to byte view
1293 * @param double|int $value the value to format
1294 * @param int $limes the sensitiveness
1295 * @param int $comma the number of decimals to retain
1297 * @return array the formatted value and its unit
1299 * @access public
1301 public static function formatByteDown($value, $limes = 6, $comma = 0)
1303 if ($value === null) {
1304 return null;
1307 $byteUnits = array(
1308 /* l10n: shortcuts for Byte */
1309 __('B'),
1310 /* l10n: shortcuts for Kilobyte */
1311 __('KiB'),
1312 /* l10n: shortcuts for Megabyte */
1313 __('MiB'),
1314 /* l10n: shortcuts for Gigabyte */
1315 __('GiB'),
1316 /* l10n: shortcuts for Terabyte */
1317 __('TiB'),
1318 /* l10n: shortcuts for Petabyte */
1319 __('PiB'),
1320 /* l10n: shortcuts for Exabyte */
1321 __('EiB')
1324 $dh = pow(10, $comma);
1325 $li = pow(10, $limes);
1326 $unit = $byteUnits[0];
1328 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1329 $unitSize = $li * pow(10, $ex);
1330 if (isset($byteUnits[$d]) && $value >= $unitSize) {
1331 // use 1024.0 to avoid integer overflow on 64-bit machines
1332 $value = round($value / (pow(1024, $d) / $dh)) /$dh;
1333 $unit = $byteUnits[$d];
1334 break 1;
1335 } // end if
1336 } // end for
1338 if ($unit != $byteUnits[0]) {
1339 // if the unit is not bytes (as represented in current language)
1340 // reformat with max length of 5
1341 // 4th parameter=true means do not reformat if value < 1
1342 $return_value = self::formatNumber($value, 5, $comma, true);
1343 } else {
1344 // do not reformat, just handle the locale
1345 $return_value = self::formatNumber($value, 0);
1348 return array(trim($return_value), $unit);
1349 } // end of the 'formatByteDown' function
1353 * Formats $value to the given length and appends SI prefixes
1354 * with a $length of 0 no truncation occurs, number is only formatted
1355 * to the current locale
1357 * examples:
1358 * <code>
1359 * echo formatNumber(123456789, 6); // 123,457 k
1360 * echo formatNumber(-123456789, 4, 2); // -123.46 M
1361 * echo formatNumber(-0.003, 6); // -3 m
1362 * echo formatNumber(0.003, 3, 3); // 0.003
1363 * echo formatNumber(0.00003, 3, 2); // 0.03 m
1364 * echo formatNumber(0, 6); // 0
1365 * </code>
1367 * @param double $value the value to format
1368 * @param integer $digits_left number of digits left of the comma
1369 * @param integer $digits_right number of digits right of the comma
1370 * @param boolean $only_down do not reformat numbers below 1
1371 * @param boolean $noTrailingZero removes trailing zeros right of the comma
1372 * (default: true)
1374 * @return string the formatted value and its unit
1376 * @access public
1378 public static function formatNumber(
1379 $value,
1380 $digits_left = 3,
1381 $digits_right = 0,
1382 $only_down = false,
1383 $noTrailingZero = true
1385 if ($value == 0) {
1386 return '0';
1389 $originalValue = $value;
1390 //number_format is not multibyte safe, str_replace is safe
1391 if ($digits_left === 0) {
1392 $value = number_format(
1393 $value,
1394 $digits_right,
1395 /* l10n: Decimal separator */
1396 __('.'),
1397 /* l10n: Thousands separator */
1398 __(',')
1400 if (($originalValue != 0) && (floatval($value) == 0)) {
1401 $value = ' <' . (1 / pow(10, $digits_right));
1403 return $value;
1406 // this units needs no translation, ISO
1407 $units = array(
1408 -8 => 'y',
1409 -7 => 'z',
1410 -6 => 'a',
1411 -5 => 'f',
1412 -4 => 'p',
1413 -3 => 'n',
1414 -2 => '&micro;',
1415 -1 => 'm',
1416 0 => ' ',
1417 1 => 'k',
1418 2 => 'M',
1419 3 => 'G',
1420 4 => 'T',
1421 5 => 'P',
1422 6 => 'E',
1423 7 => 'Z',
1424 8 => 'Y'
1427 // check for negative value to retain sign
1428 if ($value < 0) {
1429 $sign = '-';
1430 $value = abs($value);
1431 } else {
1432 $sign = '';
1435 $dh = pow(10, $digits_right);
1438 * This gives us the right SI prefix already,
1439 * but $digits_left parameter not incorporated
1441 $d = floor(log10($value) / 3);
1443 * Lowering the SI prefix by 1 gives us an additional 3 zeros
1444 * So if we have 3,6,9,12.. free digits ($digits_left - $cur_digits)
1445 * to use, then lower the SI prefix
1447 $cur_digits = floor(log10($value / pow(1000, $d))+1);
1448 if ($digits_left > $cur_digits) {
1449 $d -= floor(($digits_left - $cur_digits)/3);
1452 if ($d < 0 && $only_down) {
1453 $d = 0;
1456 $value = round($value / (pow(1000, $d) / $dh)) /$dh;
1457 $unit = $units[$d];
1459 // number_format is not multibyte safe, str_replace is safe
1460 $formattedValue = number_format(
1461 $value,
1462 $digits_right,
1463 /* l10n: Decimal separator */
1464 __('.'),
1465 /* l10n: Thousands separator */
1466 __(',')
1468 // If we don't want any zeros, remove them now
1469 if ($noTrailingZero && strpos($formattedValue, '.') !== false) {
1470 $formattedValue = preg_replace('/\.?0+$/', '', $formattedValue);
1473 if ($originalValue != 0 && floatval($value) == 0) {
1474 return ' <' . number_format(
1475 (1 / pow(10, $digits_right)),
1476 $digits_right,
1477 /* l10n: Decimal separator */
1478 __('.'),
1479 /* l10n: Thousands separator */
1480 __(',')
1482 . ' ' . $unit;
1485 return $sign . $formattedValue . ' ' . $unit;
1486 } // end of the 'formatNumber' function
1489 * Returns the number of bytes when a formatted size is given
1491 * @param string $formatted_size the size expression (for example 8MB)
1493 * @return integer The numerical part of the expression (for example 8)
1495 public static function extractValueFromFormattedSize($formatted_size)
1497 $return_value = -1;
1499 if (preg_match('/^[0-9]+GB$/', $formatted_size)) {
1500 $return_value = mb_substr($formatted_size, 0, -2)
1501 * pow(1024, 3);
1502 } elseif (preg_match('/^[0-9]+MB$/', $formatted_size)) {
1503 $return_value = mb_substr($formatted_size, 0, -2)
1504 * pow(1024, 2);
1505 } elseif (preg_match('/^[0-9]+K$/', $formatted_size)) {
1506 $return_value = mb_substr($formatted_size, 0, -1)
1507 * pow(1024, 1);
1509 return $return_value;
1510 }// end of the 'extractValueFromFormattedSize' function
1513 * Writes localised date
1515 * @param integer $timestamp the current timestamp
1516 * @param string $format format
1518 * @return string the formatted date
1520 * @access public
1522 public static function localisedDate($timestamp = -1, $format = '')
1524 $month = array(
1525 /* l10n: Short month name */
1526 __('Jan'),
1527 /* l10n: Short month name */
1528 __('Feb'),
1529 /* l10n: Short month name */
1530 __('Mar'),
1531 /* l10n: Short month name */
1532 __('Apr'),
1533 /* l10n: Short month name */
1534 _pgettext('Short month name', 'May'),
1535 /* l10n: Short month name */
1536 __('Jun'),
1537 /* l10n: Short month name */
1538 __('Jul'),
1539 /* l10n: Short month name */
1540 __('Aug'),
1541 /* l10n: Short month name */
1542 __('Sep'),
1543 /* l10n: Short month name */
1544 __('Oct'),
1545 /* l10n: Short month name */
1546 __('Nov'),
1547 /* l10n: Short month name */
1548 __('Dec'));
1549 $day_of_week = array(
1550 /* l10n: Short week day name */
1551 _pgettext('Short week day name', 'Sun'),
1552 /* l10n: Short week day name */
1553 __('Mon'),
1554 /* l10n: Short week day name */
1555 __('Tue'),
1556 /* l10n: Short week day name */
1557 __('Wed'),
1558 /* l10n: Short week day name */
1559 __('Thu'),
1560 /* l10n: Short week day name */
1561 __('Fri'),
1562 /* l10n: Short week day name */
1563 __('Sat'));
1565 if ($format == '') {
1566 /* l10n: See https://secure.php.net/manual/en/function.strftime.php */
1567 $format = __('%B %d, %Y at %I:%M %p');
1570 if ($timestamp == -1) {
1571 $timestamp = time();
1574 $date = preg_replace(
1575 '@%[aA]@',
1576 $day_of_week[(int)strftime('%w', $timestamp)],
1577 $format
1579 $date = preg_replace(
1580 '@%[bB]@',
1581 $month[(int)strftime('%m', $timestamp)-1],
1582 $date
1585 /* Fill in AM/PM */
1586 $hours = (int)date('H', $timestamp);
1587 if ($hours >= 12) {
1588 $am_pm = _pgettext('AM/PM indication in time', 'PM');
1589 } else {
1590 $am_pm = _pgettext('AM/PM indication in time', 'AM');
1592 $date = preg_replace('@%[pP]@', $am_pm, $date);
1594 $ret = strftime($date, $timestamp);
1595 // Some OSes such as Win8.1 Traditional Chinese version did not produce UTF-8
1596 // output here. See https://sourceforge.net/p/phpmyadmin/bugs/4207/
1597 if (mb_detect_encoding($ret, 'UTF-8', true) != 'UTF-8') {
1598 $ret = date('Y-m-d H:i:s', $timestamp);
1601 return $ret;
1602 } // end of the 'localisedDate()' function
1605 * returns a tab for tabbed navigation.
1606 * If the variables $link and $args ar left empty, an inactive tab is created
1608 * @param array $tab array with all options
1609 * @param array $url_params tab specific URL parameters
1611 * @return string html code for one tab, a link if valid otherwise a span
1613 * @access public
1615 public static function getHtmlTab($tab, $url_params = array())
1617 // default values
1618 $defaults = array(
1619 'text' => '',
1620 'class' => '',
1621 'active' => null,
1622 'link' => '',
1623 'sep' => '?',
1624 'attr' => '',
1625 'args' => '',
1626 'warning' => '',
1627 'fragment' => '',
1628 'id' => '',
1631 $tab = array_merge($defaults, $tab);
1633 // determine additional style-class
1634 if (empty($tab['class'])) {
1635 if (! empty($tab['active'])
1636 || PMA_isValid($GLOBALS['active_page'], 'identical', $tab['link'])
1638 $tab['class'] = 'active';
1639 } elseif (is_null($tab['active']) && empty($GLOBALS['active_page'])
1640 && (basename($GLOBALS['PMA_PHP_SELF']) == $tab['link'])
1642 $tab['class'] = 'active';
1646 // If there are any tab specific URL parameters, merge those with
1647 // the general URL parameters
1648 if (! empty($tab['url_params']) && is_array($tab['url_params'])) {
1649 $url_params = array_merge($url_params, $tab['url_params']);
1652 // build the link
1653 if (! empty($tab['link'])) {
1654 $tab['link'] = htmlentities($tab['link']);
1655 $tab['link'] = $tab['link'] . URL::getCommon($url_params);
1656 if (! empty($tab['args'])) {
1657 foreach ($tab['args'] as $param => $value) {
1658 $tab['link'] .= URL::getArgSeparator('html')
1659 . urlencode($param) . '=' . urlencode($value);
1664 if (! empty($tab['fragment'])) {
1665 $tab['link'] .= $tab['fragment'];
1668 // display icon
1669 if (isset($tab['icon'])) {
1670 // avoid generating an alt tag, because it only illustrates
1671 // the text that follows and if browser does not display
1672 // images, the text is duplicated
1673 $tab['text'] = self::getIcon(
1674 $tab['icon'],
1675 $tab['text'],
1676 false,
1677 true,
1678 'TabsMode'
1681 } elseif (empty($tab['text'])) {
1682 // check to not display an empty link-text
1683 $tab['text'] = '?';
1684 trigger_error(
1685 'empty linktext in function ' . __FUNCTION__ . '()',
1686 E_USER_NOTICE
1690 //Set the id for the tab, if set in the params
1691 $tabId = (empty($tab['id']) ? null : $tab['id']);
1693 $item = array();
1694 if (!empty($tab['link'])) {
1695 $item = array(
1696 'content' => $tab['text'],
1697 'url' => array(
1698 'href' => empty($tab['link']) ? null : $tab['link'],
1699 'id' => $tabId,
1700 'class' => 'tab' . htmlentities($tab['class']),
1703 } else {
1704 $item['content'] = '<span class="tab' . htmlentities($tab['class']) . '"'
1705 . $tabId . '>' . $tab['text'] . '</span>';
1708 $item['class'] = $tab['class'] == 'active' ? 'active' : '';
1710 return Template::get('list/item')
1711 ->render($item);
1712 } // end of the 'getHtmlTab()' function
1715 * returns html-code for a tab navigation
1717 * @param array $tabs one element per tab
1718 * @param array $url_params additional URL parameters
1719 * @param string $menu_id HTML id attribute for the menu container
1720 * @param bool $resizable whether to add a "resizable" class
1722 * @return string html-code for tab-navigation
1724 public static function getHtmlTabs(
1725 $tabs,
1726 $url_params,
1727 $menu_id,
1728 $resizable = false
1730 $class = '';
1731 if ($resizable) {
1732 $class = ' class="resizable-menu"';
1735 $tab_navigation = '<div id="' . htmlentities($menu_id)
1736 . 'container" class="menucontainer">'
1737 . '<ul id="' . htmlentities($menu_id) . '" ' . $class . '>';
1739 foreach ($tabs as $tab) {
1740 $tab_navigation .= self::getHtmlTab($tab, $url_params);
1743 $tab_navigation .=
1744 '<div class="clearfloat"></div>'
1745 . '</ul>' . "\n"
1746 . '</div>' . "\n";
1748 return $tab_navigation;
1752 * Displays a link, or a button if the link's URL is too large, to
1753 * accommodate some browsers' limitations
1755 * @param string $url the URL
1756 * @param string $message the link message
1757 * @param mixed $tag_params string: js confirmation
1758 * array: additional tag params (f.e. style="")
1759 * @param boolean $new_form we set this to false when we are already in
1760 * a form, to avoid generating nested forms
1761 * @param boolean $strip_img whether to strip the image
1762 * @param string $target target
1763 * @param boolean $force_button use a button even when the URL is not too long
1765 * @return string the results to be echoed or saved in an array
1767 public static function linkOrButton(
1768 $url, $message, $tag_params = array(),
1769 $new_form = true, $strip_img = false, $target = '', $force_button = false
1771 $url_length = mb_strlen($url);
1772 // with this we should be able to catch case of image upload
1773 // into a (MEDIUM) BLOB; not worth generating even a form for these
1774 if ($url_length > $GLOBALS['cfg']['LinkLengthLimit'] * 100) {
1775 return '';
1778 if (! is_array($tag_params)) {
1779 $tmp = $tag_params;
1780 $tag_params = array();
1781 if (! empty($tmp)) {
1782 $tag_params['onclick'] = 'return confirmLink(this, \''
1783 . Sanitize::escapeJsString($tmp) . '\')';
1785 unset($tmp);
1787 if (! empty($target)) {
1788 $tag_params['target'] = htmlentities($target);
1789 if ($target === '_blank' && strncmp($url, 'url.php?', 8) == 0) {
1790 $tag_params['rel'] = 'noopener noreferrer';
1794 $displayed_message = '';
1795 // Add text if not already added
1796 if (stristr($message, '<img')
1797 && (! $strip_img || ($GLOBALS['cfg']['ActionLinksMode'] == 'icons'))
1798 && (strip_tags($message) == $message)
1800 $displayed_message = '<span>'
1801 . htmlspecialchars(
1802 preg_replace('/^.*\salt="([^"]*)".*$/si', '\1', $message)
1804 . '</span>';
1807 // Suhosin: Check that each query parameter is not above maximum
1808 $in_suhosin_limits = true;
1809 if ($url_length <= $GLOBALS['cfg']['LinkLengthLimit']) {
1810 $suhosin_get_MaxValueLength = ini_get('suhosin.get.max_value_length');
1811 if ($suhosin_get_MaxValueLength) {
1812 $query_parts = self::splitURLQuery($url);
1813 foreach ($query_parts as $query_pair) {
1814 if (strpos($query_pair, '=') === false) {
1815 continue;
1818 list(, $eachval) = explode('=', $query_pair);
1819 if (mb_strlen($eachval) > $suhosin_get_MaxValueLength
1821 $in_suhosin_limits = false;
1822 break;
1828 if (($url_length <= $GLOBALS['cfg']['LinkLengthLimit'])
1829 && $in_suhosin_limits
1830 && ! $force_button
1832 $tag_params_strings = array();
1833 foreach ($tag_params as $par_name => $par_value) {
1834 // htmlspecialchars() only on non javascript
1835 $par_value = mb_substr($par_name, 0, 2) == 'on'
1836 ? $par_value
1837 : htmlspecialchars($par_value);
1838 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1841 // no whitespace within an <a> else Safari will make it part of the link
1842 $ret = "\n" . '<a href="' . $url . '" '
1843 . implode(' ', $tag_params_strings) . '>'
1844 . $message . $displayed_message . '</a>' . "\n";
1845 } else {
1846 // no spaces (line breaks) at all
1847 // or after the hidden fields
1848 // IE will display them all
1850 if (! isset($query_parts)) {
1851 $query_parts = self::splitURLQuery($url);
1853 $url_parts = parse_url($url);
1855 if ($new_form) {
1856 if ($target) {
1857 $target = ' target="' . $target . '"';
1859 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1860 . ' method="post"' . $target . ' style="display: inline;">';
1861 $subname_open = '';
1862 $subname_close = '';
1863 $submit_link = '#';
1864 } else {
1865 $query_parts[] = 'redirect=' . $url_parts['path'];
1866 if (empty($GLOBALS['subform_counter'])) {
1867 $GLOBALS['subform_counter'] = 0;
1869 $GLOBALS['subform_counter']++;
1870 $ret = '';
1871 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1872 $subname_close = ']';
1873 $submit_link = '#usesubform[' . $GLOBALS['subform_counter']
1874 . ']=1';
1877 foreach ($query_parts as $query_pair) {
1878 list($eachvar, $eachval) = explode('=', $query_pair);
1879 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1880 . $subname_close . '" value="'
1881 . htmlspecialchars(urldecode($eachval)) . '" />';
1882 } // end while
1884 if (empty($tag_params['class'])) {
1885 $tag_params['class'] = 'formLinkSubmit';
1886 } else {
1887 $tag_params['class'] .= ' formLinkSubmit';
1890 $tag_params_strings = array();
1891 foreach ($tag_params as $par_name => $par_value) {
1892 // htmlspecialchars() only on non javascript
1893 $par_value = mb_substr($par_name, 0, 2) == 'on'
1894 ? $par_value
1895 : htmlspecialchars($par_value);
1896 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1899 $ret .= "\n" . '<a href="' . $submit_link . '" '
1900 . implode(' ', $tag_params_strings) . '>'
1901 . $message . ' ' . $displayed_message . '</a>' . "\n";
1903 if ($new_form) {
1904 $ret .= '</form>';
1906 } // end if... else...
1908 return $ret;
1909 } // end of the 'linkOrButton()' function
1912 * Splits a URL string by parameter
1914 * @param string $url the URL
1916 * @return array the parameter/value pairs, for example [0] db=sakila
1918 public static function splitURLQuery($url)
1920 // decode encoded url separators
1921 $separator = URL::getArgSeparator();
1922 // on most places separator is still hard coded ...
1923 if ($separator !== '&') {
1924 // ... so always replace & with $separator
1925 $url = str_replace(htmlentities('&'), $separator, $url);
1926 $url = str_replace('&', $separator, $url);
1929 $url = str_replace(htmlentities($separator), $separator, $url);
1930 // end decode
1932 $url_parts = parse_url($url);
1934 if (! empty($url_parts['query'])) {
1935 return explode($separator, $url_parts['query']);
1936 } else {
1937 return array();
1942 * Returns a given timespan value in a readable format.
1944 * @param int $seconds the timespan
1946 * @return string the formatted value
1948 public static function timespanFormat($seconds)
1950 $days = floor($seconds / 86400);
1951 if ($days > 0) {
1952 $seconds -= $days * 86400;
1955 $hours = floor($seconds / 3600);
1956 if ($days > 0 || $hours > 0) {
1957 $seconds -= $hours * 3600;
1960 $minutes = floor($seconds / 60);
1961 if ($days > 0 || $hours > 0 || $minutes > 0) {
1962 $seconds -= $minutes * 60;
1965 return sprintf(
1966 __('%s days, %s hours, %s minutes and %s seconds'),
1967 (string)$days,
1968 (string)$hours,
1969 (string)$minutes,
1970 (string)$seconds
1975 * Function added to avoid path disclosures.
1976 * Called by each script that needs parameters, it displays
1977 * an error message and, by default, stops the execution.
1979 * Not sure we could use a strMissingParameter message here,
1980 * would have to check if the error message file is always available
1982 * @param string[] $params The names of the parameters needed by the calling
1983 * script
1984 * @param bool $request Whether to include this list in checking for
1985 * special params
1987 * @return void
1989 * @global boolean $checked_special flag whether any special variable
1990 * was required
1992 * @access public
1994 public static function checkParameters($params, $request = true)
1996 global $checked_special;
1998 if (! isset($checked_special)) {
1999 $checked_special = false;
2002 $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
2003 $found_error = false;
2004 $error_message = '';
2006 foreach ($params as $param) {
2007 if ($request && ($param != 'db') && ($param != 'table')) {
2008 $checked_special = true;
2011 if (! isset($GLOBALS[$param])) {
2012 $error_message .= $reported_script_name
2013 . ': ' . __('Missing parameter:') . ' '
2014 . $param
2015 . self::showDocu('faq', 'faqmissingparameters',true)
2016 . '[br]';
2017 $found_error = true;
2020 if ($found_error) {
2021 PMA_fatalError($error_message);
2023 } // end function
2026 * Function to generate unique condition for specified row.
2028 * @param resource $handle current query result
2029 * @param integer $fields_cnt number of fields
2030 * @param array $fields_meta meta information about fields
2031 * @param array $row current row
2032 * @param boolean $force_unique generate condition only on pk
2033 * or unique
2034 * @param string|boolean $restrict_to_table restrict the unique condition
2035 * to this table or false if
2036 * none
2037 * @param array $analyzed_sql_results the analyzed query
2039 * @access public
2041 * @return array the calculated condition and whether condition is unique
2043 public static function getUniqueCondition(
2044 $handle, $fields_cnt, $fields_meta, $row, $force_unique = false,
2045 $restrict_to_table = false, $analyzed_sql_results = null
2047 $primary_key = '';
2048 $unique_key = '';
2049 $nonprimary_condition = '';
2050 $preferred_condition = '';
2051 $primary_key_array = array();
2052 $unique_key_array = array();
2053 $nonprimary_condition_array = array();
2054 $condition_array = array();
2056 for ($i = 0; $i < $fields_cnt; ++$i) {
2058 $con_val = '';
2059 $field_flags = $GLOBALS['dbi']->fieldFlags($handle, $i);
2060 $meta = $fields_meta[$i];
2062 // do not use a column alias in a condition
2063 if (! isset($meta->orgname) || strlen($meta->orgname) === 0) {
2064 $meta->orgname = $meta->name;
2066 if (!empty($analyzed_sql_results['statement']->expr)) {
2067 foreach ($analyzed_sql_results['statement']->expr as $expr) {
2068 if ((empty($expr->alias)) || (empty($expr->column))) {
2069 continue;
2071 if (strcasecmp($meta->name, $expr->alias) == 0) {
2072 $meta->orgname = $expr->column;
2073 break;
2079 // Do not use a table alias in a condition.
2080 // Test case is:
2081 // select * from galerie x WHERE
2082 //(select count(*) from galerie y where y.datum=x.datum)>1
2084 // But orgtable is present only with mysqli extension so the
2085 // fix is only for mysqli.
2086 // Also, do not use the original table name if we are dealing with
2087 // a view because this view might be updatable.
2088 // (The isView() verification should not be costly in most cases
2089 // because there is some caching in the function).
2090 if (isset($meta->orgtable)
2091 && ($meta->table != $meta->orgtable)
2092 && ! $GLOBALS['dbi']->getTable($GLOBALS['db'], $meta->table)->isView()
2094 $meta->table = $meta->orgtable;
2097 // If this field is not from the table which the unique clause needs
2098 // to be restricted to.
2099 if ($restrict_to_table && $restrict_to_table != $meta->table) {
2100 continue;
2103 // to fix the bug where float fields (primary or not)
2104 // can't be matched because of the imprecision of
2105 // floating comparison, use CONCAT
2106 // (also, the syntax "CONCAT(field) IS NULL"
2107 // that we need on the next "if" will work)
2108 if ($meta->type == 'real') {
2109 $con_key = 'CONCAT(' . self::backquote($meta->table) . '.'
2110 . self::backquote($meta->orgname) . ')';
2111 } else {
2112 $con_key = self::backquote($meta->table) . '.'
2113 . self::backquote($meta->orgname);
2114 } // end if... else...
2115 $condition = ' ' . $con_key . ' ';
2117 if (! isset($row[$i]) || is_null($row[$i])) {
2118 $con_val = 'IS NULL';
2119 } else {
2120 // timestamp is numeric on some MySQL 4.1
2121 // for real we use CONCAT above and it should compare to string
2122 if ($meta->numeric
2123 && ($meta->type != 'timestamp')
2124 && ($meta->type != 'real')
2126 $con_val = '= ' . $row[$i];
2127 } elseif ((($meta->type == 'blob') || ($meta->type == 'string'))
2128 && stristr($field_flags, 'BINARY')
2129 && ! empty($row[$i])
2131 // hexify only if this is a true not empty BLOB or a BINARY
2133 // do not waste memory building a too big condition
2134 if (mb_strlen($row[$i]) < 1000) {
2135 // use a CAST if possible, to avoid problems
2136 // if the field contains wildcard characters % or _
2137 $con_val = '= CAST(0x' . bin2hex($row[$i]) . ' AS BINARY)';
2138 } elseif ($fields_cnt == 1) {
2139 // when this blob is the only field present
2140 // try settling with length comparison
2141 $condition = ' CHAR_LENGTH(' . $con_key . ') ';
2142 $con_val = ' = ' . mb_strlen($row[$i]);
2143 } else {
2144 // this blob won't be part of the final condition
2145 $con_val = null;
2147 } elseif (in_array($meta->type, self::getGISDatatypes())
2148 && ! empty($row[$i])
2150 // do not build a too big condition
2151 if (mb_strlen($row[$i]) < 5000) {
2152 $condition .= '=0x' . bin2hex($row[$i]) . ' AND';
2153 } else {
2154 $condition = '';
2156 } elseif ($meta->type == 'bit') {
2157 $con_val = "= b'"
2158 . self::printableBitValue($row[$i], $meta->length) . "'";
2159 } else {
2160 $con_val = '= \''
2161 . $GLOBALS['dbi']->escapeString($row[$i]) . '\'';
2165 if ($con_val != null) {
2167 $condition .= $con_val . ' AND';
2169 if ($meta->primary_key > 0) {
2170 $primary_key .= $condition;
2171 $primary_key_array[$con_key] = $con_val;
2172 } elseif ($meta->unique_key > 0) {
2173 $unique_key .= $condition;
2174 $unique_key_array[$con_key] = $con_val;
2177 $nonprimary_condition .= $condition;
2178 $nonprimary_condition_array[$con_key] = $con_val;
2180 } // end for
2182 // Correction University of Virginia 19991216:
2183 // prefer primary or unique keys for condition,
2184 // but use conjunction of all values if no primary key
2185 $clause_is_unique = true;
2187 if ($primary_key) {
2188 $preferred_condition = $primary_key;
2189 $condition_array = $primary_key_array;
2191 } elseif ($unique_key) {
2192 $preferred_condition = $unique_key;
2193 $condition_array = $unique_key_array;
2195 } elseif (! $force_unique) {
2196 $preferred_condition = $nonprimary_condition;
2197 $condition_array = $nonprimary_condition_array;
2198 $clause_is_unique = false;
2201 $where_clause = trim(preg_replace('|\s?AND$|', '', $preferred_condition));
2202 return(array($where_clause, $clause_is_unique, $condition_array));
2203 } // end function
2206 * Generate the charset query part
2208 * @param string $collation Collation
2209 * @param boolean optional $override force 'CHARACTER SET' keyword
2211 * @return string
2213 static function getCharsetQueryPart($collation, $override = false)
2215 list($charset) = explode('_', $collation);
2216 $keyword = ' CHARSET=';
2218 if ($override) {
2219 $keyword = ' CHARACTER SET ';
2221 return $keyword . $charset
2222 . ($charset == $collation ? '' : ' COLLATE ' . $collation);
2226 * Generate a button or image tag
2228 * @param string $button_name name of button element
2229 * @param string $button_class class of button or image element
2230 * @param string $text text to display
2231 * @param string $image image to display
2232 * @param string $value value
2234 * @return string html content
2236 * @access public
2238 public static function getButtonOrImage(
2239 $button_name, $button_class, $text, $image, $value = ''
2241 if ($value == '') {
2242 $value = $text;
2244 if ($GLOBALS['cfg']['ActionLinksMode'] == 'text') {
2245 return ' <input type="submit" name="' . $button_name . '"'
2246 . ' value="' . htmlspecialchars($value) . '"'
2247 . ' title="' . htmlspecialchars($text) . '" />' . "\n";
2249 return '<button class="' . $button_class . '" type="submit"'
2250 . ' name="' . $button_name . '" value="' . htmlspecialchars($value)
2251 . '" title="' . htmlspecialchars($text) . '">' . "\n"
2252 . self::getIcon($image, $text)
2253 . '</button>' . "\n";
2254 } // end function
2257 * Generate a pagination selector for browsing resultsets
2259 * @param string $name The name for the request parameter
2260 * @param int $rows Number of rows in the pagination set
2261 * @param int $pageNow current page number
2262 * @param int $nbTotalPage number of total pages
2263 * @param int $showAll If the number of pages is lower than this
2264 * variable, no pages will be omitted in pagination
2265 * @param int $sliceStart How many rows at the beginning should always
2266 * be shown?
2267 * @param int $sliceEnd How many rows at the end should always be shown?
2268 * @param int $percent Percentage of calculation page offsets to hop to a
2269 * next page
2270 * @param int $range Near the current page, how many pages should
2271 * be considered "nearby" and displayed as well?
2272 * @param string $prompt The prompt to display (sometimes empty)
2274 * @return string
2276 * @access public
2278 public static function pageselector(
2279 $name, $rows, $pageNow = 1, $nbTotalPage = 1, $showAll = 200,
2280 $sliceStart = 5,
2281 $sliceEnd = 5, $percent = 20, $range = 10, $prompt = ''
2283 $increment = floor($nbTotalPage / $percent);
2284 $pageNowMinusRange = ($pageNow - $range);
2285 $pageNowPlusRange = ($pageNow + $range);
2287 $gotopage = $prompt . ' <select class="pageselector ajax"';
2289 $gotopage .= ' name="' . $name . '" >';
2290 if ($nbTotalPage < $showAll) {
2291 $pages = range(1, $nbTotalPage);
2292 } else {
2293 $pages = array();
2295 // Always show first X pages
2296 for ($i = 1; $i <= $sliceStart; $i++) {
2297 $pages[] = $i;
2300 // Always show last X pages
2301 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++) {
2302 $pages[] = $i;
2305 // Based on the number of results we add the specified
2306 // $percent percentage to each page number,
2307 // so that we have a representing page number every now and then to
2308 // immediately jump to specific pages.
2309 // As soon as we get near our currently chosen page ($pageNow -
2310 // $range), every page number will be shown.
2311 $i = $sliceStart;
2312 $x = $nbTotalPage - $sliceEnd;
2313 $met_boundary = false;
2315 while ($i <= $x) {
2316 if ($i >= $pageNowMinusRange && $i <= $pageNowPlusRange) {
2317 // If our pageselector comes near the current page, we use 1
2318 // counter increments
2319 $i++;
2320 $met_boundary = true;
2321 } else {
2322 // We add the percentage increment to our current page to
2323 // hop to the next one in range
2324 $i += $increment;
2326 // Make sure that we do not cross our boundaries.
2327 if ($i > $pageNowMinusRange && ! $met_boundary) {
2328 $i = $pageNowMinusRange;
2332 if ($i > 0 && $i <= $x) {
2333 $pages[] = $i;
2338 Add page numbers with "geometrically increasing" distances.
2340 This helps me a lot when navigating through giant tables.
2342 Test case: table with 2.28 million sets, 76190 pages. Page of interest
2343 is between 72376 and 76190.
2344 Selecting page 72376.
2345 Now, old version enumerated only +/- 10 pages around 72376 and the
2346 percentage increment produced steps of about 3000.
2348 The following code adds page numbers +/- 2,4,8,16,32,64,128,256 etc.
2349 around the current page.
2351 $i = $pageNow;
2352 $dist = 1;
2353 while ($i < $x) {
2354 $dist = 2 * $dist;
2355 $i = $pageNow + $dist;
2356 if ($i > 0 && $i <= $x) {
2357 $pages[] = $i;
2361 $i = $pageNow;
2362 $dist = 1;
2363 while ($i > 0) {
2364 $dist = 2 * $dist;
2365 $i = $pageNow - $dist;
2366 if ($i > 0 && $i <= $x) {
2367 $pages[] = $i;
2371 // Since because of ellipsing of the current page some numbers may be
2372 // double, we unify our array:
2373 sort($pages);
2374 $pages = array_unique($pages);
2377 foreach ($pages as $i) {
2378 if ($i == $pageNow) {
2379 $selected = 'selected="selected" style="font-weight: bold"';
2380 } else {
2381 $selected = '';
2383 $gotopage .= ' <option ' . $selected
2384 . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2387 $gotopage .= ' </select>';
2389 return $gotopage;
2390 } // end function
2393 * Prepare navigation for a list
2395 * @param int $count number of elements in the list
2396 * @param int $pos current position in the list
2397 * @param array $_url_params url parameters
2398 * @param string $script script name for form target
2399 * @param string $frame target frame
2400 * @param int $max_count maximum number of elements to display from
2401 * the list
2402 * @param string $name the name for the request parameter
2403 * @param string[] $classes additional classes for the container
2405 * @return string $list_navigator_html the html content
2407 * @access public
2409 * @todo use $pos from $_url_params
2411 public static function getListNavigator(
2412 $count, $pos, $_url_params, $script, $frame, $max_count, $name = 'pos',
2413 $classes = array()
2416 $class = $frame == 'frame_navigation' ? ' class="ajax"' : '';
2418 $list_navigator_html = '';
2420 if ($max_count < $count) {
2422 $classes[] = 'pageselector';
2423 $list_navigator_html .= '<div class="' . implode(' ', $classes) . '">';
2425 if ($frame != 'frame_navigation') {
2426 $list_navigator_html .= __('Page number:');
2429 // Move to the beginning or to the previous page
2430 if ($pos > 0) {
2431 $caption1 = ''; $caption2 = '';
2432 if (self::showIcons('TableNavigationLinksMode')) {
2433 $caption1 .= '&lt;&lt; ';
2434 $caption2 .= '&lt; ';
2436 if (self::showText('TableNavigationLinksMode')) {
2437 $caption1 .= _pgettext('First page', 'Begin');
2438 $caption2 .= _pgettext('Previous page', 'Previous');
2440 $title1 = ' title="' . _pgettext('First page', 'Begin') . '"';
2441 $title2 = ' title="' . _pgettext('Previous page', 'Previous') . '"';
2443 $_url_params[$name] = 0;
2444 $list_navigator_html .= '<a' . $class . $title1 . ' href="' . $script
2445 . URL::getCommon($_url_params) . '">' . $caption1
2446 . '</a>';
2448 $_url_params[$name] = $pos - $max_count;
2449 $list_navigator_html .= ' <a' . $class . $title2
2450 . ' href="' . $script . URL::getCommon($_url_params) . '">'
2451 . $caption2 . '</a>';
2454 $list_navigator_html .= '<form action="' . basename($script)
2455 . '" method="post">';
2457 $list_navigator_html .= URL::getHiddenInputs($_url_params);
2458 $list_navigator_html .= self::pageselector(
2459 $name,
2460 $max_count,
2461 floor(($pos + 1) / $max_count) + 1,
2462 ceil($count / $max_count)
2464 $list_navigator_html .= '</form>';
2466 if ($pos + $max_count < $count) {
2467 $caption3 = ''; $caption4 = '';
2468 if (self::showText('TableNavigationLinksMode')) {
2469 $caption3 .= _pgettext('Next page', 'Next');
2470 $caption4 .= _pgettext('Last page', 'End');
2472 if (self::showIcons('TableNavigationLinksMode')) {
2473 $caption3 .= ' &gt;';
2474 $caption4 .= ' &gt;&gt;';
2475 if (! self::showText('TableNavigationLinksMode')) {
2479 $title3 = ' title="' . _pgettext('Next page', 'Next') . '"';
2480 $title4 = ' title="' . _pgettext('Last page', 'End') . '"';
2482 $_url_params[$name] = $pos + $max_count;
2483 $list_navigator_html .= '<a' . $class . $title3 . ' href="' . $script
2484 . URL::getCommon($_url_params) . '" >' . $caption3
2485 . '</a>';
2487 $_url_params[$name] = floor($count / $max_count) * $max_count;
2488 if ($_url_params[$name] == $count) {
2489 $_url_params[$name] = $count - $max_count;
2492 $list_navigator_html .= ' <a' . $class . $title4
2493 . ' href="' . $script . URL::getCommon($_url_params) . '" >'
2494 . $caption4 . '</a>';
2496 $list_navigator_html .= '</div>' . "\n";
2499 return $list_navigator_html;
2503 * replaces %u in given path with current user name
2505 * example:
2506 * <code>
2507 * $user_dir = userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2509 * </code>
2511 * @param string $dir with wildcard for user
2513 * @return string per user directory
2515 public static function userDir($dir)
2517 // add trailing slash
2518 if (mb_substr($dir, -1) != '/') {
2519 $dir .= '/';
2522 return str_replace('%u', PMA_securePath($GLOBALS['cfg']['Server']['user']), $dir);
2526 * returns html code for db link to default db page
2528 * @param string $database database
2530 * @return string html link to default db page
2532 public static function getDbLink($database = null)
2534 if (strlen($database) === 0) {
2535 if (strlen($GLOBALS['db']) === 0) {
2536 return '';
2538 $database = $GLOBALS['db'];
2539 } else {
2540 $database = self::unescapeMysqlWildcards($database);
2543 return '<a href="'
2544 . Util::getScriptNameForOption(
2545 $GLOBALS['cfg']['DefaultTabDatabase'], 'database'
2547 . URL::getCommon(array('db' => $database)) . '" title="'
2548 . htmlspecialchars(
2549 sprintf(
2550 __('Jump to database "%s".'),
2551 $database
2554 . '">' . htmlspecialchars($database) . '</a>';
2558 * Prepare a lightbulb hint explaining a known external bug
2559 * that affects a functionality
2561 * @param string $functionality localized message explaining the func.
2562 * @param string $component 'mysql' (eventually, 'php')
2563 * @param string $minimum_version of this component
2564 * @param string $bugref bug reference for this component
2566 * @return String
2568 public static function getExternalBug(
2569 $functionality, $component, $minimum_version, $bugref
2571 $ext_but_html = '';
2572 if (($component == 'mysql') && (PMA_MYSQL_INT_VERSION < $minimum_version)) {
2573 $ext_but_html .= self::showHint(
2574 sprintf(
2575 __('The %s functionality is affected by a known bug, see %s'),
2576 $functionality,
2577 PMA_linkURL('https://bugs.mysql.com/') . $bugref
2581 return $ext_but_html;
2585 * Generates a set of radio HTML fields
2587 * @param string $html_field_name the radio HTML field
2588 * @param array $choices the choices values and labels
2589 * @param string $checked_choice the choice to check by default
2590 * @param boolean $line_break whether to add HTML line break after a choice
2591 * @param boolean $escape_label whether to use htmlspecialchars() on label
2592 * @param string $class enclose each choice with a div of this class
2593 * @param string $id_prefix prefix for the id attribute, name will be
2594 * used if this is not supplied
2596 * @return string set of html radio fiels
2598 public static function getRadioFields(
2599 $html_field_name, $choices, $checked_choice = '',
2600 $line_break = true, $escape_label = true, $class = '',
2601 $id_prefix = ''
2603 $radio_html = '';
2605 foreach ($choices as $choice_value => $choice_label) {
2607 if (! empty($class)) {
2608 $radio_html .= '<div class="' . $class . '">';
2611 if (! $id_prefix) {
2612 $id_prefix = $html_field_name;
2614 $html_field_id = $id_prefix . '_' . $choice_value;
2615 $radio_html .= '<input type="radio" name="' . $html_field_name . '" id="'
2616 . $html_field_id . '" value="'
2617 . htmlspecialchars($choice_value) . '"';
2619 if ($choice_value == $checked_choice) {
2620 $radio_html .= ' checked="checked"';
2623 $radio_html .= ' />' . "\n"
2624 . '<label for="' . $html_field_id . '">'
2625 . ($escape_label
2626 ? htmlspecialchars($choice_label)
2627 : $choice_label)
2628 . '</label>';
2630 if ($line_break) {
2631 $radio_html .= '<br />';
2634 if (! empty($class)) {
2635 $radio_html .= '</div>';
2637 $radio_html .= "\n";
2640 return $radio_html;
2644 * Generates and returns an HTML dropdown
2646 * @param string $select_name name for the select element
2647 * @param array $choices choices values
2648 * @param string $active_choice the choice to select by default
2649 * @param string $id id of the select element; can be different in
2650 * case the dropdown is present more than once
2651 * on the page
2652 * @param string $class class for the select element
2653 * @param string $placeholder Placeholder for dropdown if nothing else
2654 * is selected
2656 * @return string html content
2658 * @todo support titles
2660 public static function getDropdown(
2661 $select_name, $choices, $active_choice, $id, $class = '', $placeholder = null
2663 $result = '<select'
2664 . ' name="' . htmlspecialchars($select_name) . '"'
2665 . ' id="' . htmlspecialchars($id) . '"'
2666 . (! empty($class) ? ' class="' . htmlspecialchars($class) . '"' : '')
2667 . '>';
2669 $resultOptions = '';
2670 $selected = false;
2672 foreach ($choices as $one_choice_value => $one_choice_label) {
2673 $resultOptions .= '<option value="'
2674 . htmlspecialchars($one_choice_value) . '"';
2676 if ($one_choice_value == $active_choice) {
2677 $resultOptions .= ' selected="selected"';
2678 $selected = true;
2680 $resultOptions .= '>' . htmlspecialchars($one_choice_label)
2681 . '</option>';
2684 if (!empty($placeholder)) {
2685 $resultOptions = '<option value="" disabled="disabled"'
2686 . ( !$selected ? ' selected="selected"' : '' )
2687 . '>' . $placeholder . '</option>'
2688 . $resultOptions;
2691 $result .= $resultOptions
2692 . '</select>';
2694 return $result;
2698 * Generates a slider effect (jQjuery)
2699 * Takes care of generating the initial <div> and the link
2700 * controlling the slider; you have to generate the </div> yourself
2701 * after the sliding section.
2703 * @param string $id the id of the <div> on which to apply the effect
2704 * @param string $message the message to show as a link
2706 * @return string html div element
2709 public static function getDivForSliderEffect($id = '', $message = '')
2711 return Template::get('div_for_slider_effect')->render([
2712 'id' => $id,
2713 'InitialSlidersState' => $GLOBALS['cfg']['InitialSlidersState'],
2714 'message' => $message,
2719 * Creates an AJAX sliding toggle button
2720 * (or and equivalent form when AJAX is disabled)
2722 * @param string $action The URL for the request to be executed
2723 * @param string $select_name The name for the dropdown box
2724 * @param array $options An array of options (see rte_footer.lib.php)
2725 * @param string $callback A JS snippet to execute when the request is
2726 * successfully processed
2728 * @return string HTML code for the toggle button
2730 public static function toggleButton($action, $select_name, $options, $callback)
2732 // Do the logic first
2733 $link = "$action&amp;" . urlencode($select_name) . "=";
2734 $link_on = $link . urlencode($options[1]['value']);
2735 $link_off = $link . urlencode($options[0]['value']);
2737 if ($options[1]['selected'] == true) {
2738 $state = 'on';
2739 } else if ($options[0]['selected'] == true) {
2740 $state = 'off';
2741 } else {
2742 $state = 'on';
2745 return Template::get('toggle_button')->render(
2747 'pmaThemeImage' => $GLOBALS['pmaThemeImage'],
2748 'text_dir' => $GLOBALS['text_dir'],
2749 'link_on' => $link_on,
2750 'toggleOn' => str_replace(' ', '&nbsp;', htmlspecialchars(
2751 $options[1]['label'])),
2752 'toggleOff' => str_replace(' ', '&nbsp;', htmlspecialchars(
2753 $options[0]['label'])),
2754 'link_off' => $link_off,
2755 'callback' => $callback,
2756 'state' => $state
2758 } // end toggleButton()
2761 * Clears cache content which needs to be refreshed on user change.
2763 * @return void
2765 public static function clearUserCache()
2767 self::cacheUnset('is_superuser');
2768 self::cacheUnset('is_createuser');
2769 self::cacheUnset('is_grantuser');
2773 * Calculates session cache key
2775 * @return string
2777 public static function cacheKey()
2779 if (isset($GLOBALS['cfg']['Server']['user'])) {
2780 return 'server_' . $GLOBALS['server'] . '_' . $GLOBALS['cfg']['Server']['user'];
2781 } else {
2782 return 'server_' . $GLOBALS['server'];
2787 * Verifies if something is cached in the session
2789 * @param string $var variable name
2791 * @return boolean
2793 public static function cacheExists($var)
2795 return isset($_SESSION['cache'][self::cacheKey()][$var]);
2799 * Gets cached information from the session
2801 * @param string $var variable name
2802 * @param \Closure $callback callback to fetch the value
2804 * @return mixed
2806 public static function cacheGet($var, $callback = null)
2808 if (self::cacheExists($var)) {
2809 return $_SESSION['cache'][self::cacheKey()][$var];
2810 } else {
2811 if ($callback) {
2812 $val = $callback();
2813 self::cacheSet($var, $val);
2814 return $val;
2816 return null;
2821 * Caches information in the session
2823 * @param string $var variable name
2824 * @param mixed $val value
2826 * @return mixed
2828 public static function cacheSet($var, $val = null)
2830 $_SESSION['cache'][self::cacheKey()][$var] = $val;
2834 * Removes cached information from the session
2836 * @param string $var variable name
2838 * @return void
2840 public static function cacheUnset($var)
2842 unset($_SESSION['cache'][self::cacheKey()][$var]);
2846 * Converts a bit value to printable format;
2847 * in MySQL a BIT field can be from 1 to 64 bits so we need this
2848 * function because in PHP, decbin() supports only 32 bits
2849 * on 32-bit servers
2851 * @param integer $value coming from a BIT field
2852 * @param integer $length length
2854 * @return string the printable value
2856 public static function printableBitValue($value, $length)
2858 // if running on a 64-bit server or the length is safe for decbin()
2859 if (PHP_INT_SIZE == 8 || $length < 33) {
2860 $printable = decbin($value);
2861 } else {
2862 // FIXME: does not work for the leftmost bit of a 64-bit value
2863 $i = 0;
2864 $printable = '';
2865 while ($value >= pow(2, $i)) {
2866 ++$i;
2868 if ($i != 0) {
2869 --$i;
2872 while ($i >= 0) {
2873 if ($value - pow(2, $i) < 0) {
2874 $printable = '0' . $printable;
2875 } else {
2876 $printable = '1' . $printable;
2877 $value = $value - pow(2, $i);
2879 --$i;
2881 $printable = strrev($printable);
2883 $printable = str_pad($printable, $length, '0', STR_PAD_LEFT);
2884 return $printable;
2888 * Verifies whether the value contains a non-printable character
2890 * @param string $value value
2892 * @return integer
2894 public static function containsNonPrintableAscii($value)
2896 return preg_match('@[^[:print:]]@', $value);
2900 * Converts a BIT type default value
2901 * for example, b'010' becomes 010
2903 * @param string $bit_default_value value
2905 * @return string the converted value
2907 public static function convertBitDefaultValue($bit_default_value)
2909 return rtrim(ltrim($bit_default_value, "b'"), "'");
2913 * Extracts the various parts from a column spec
2915 * @param string $columnspec Column specification
2917 * @return array associative array containing type, spec_in_brackets
2918 * and possibly enum_set_values (another array)
2920 public static function extractColumnSpec($columnspec)
2922 $first_bracket_pos = mb_strpos($columnspec, '(');
2923 if ($first_bracket_pos) {
2924 $spec_in_brackets = chop(
2925 mb_substr(
2926 $columnspec,
2927 $first_bracket_pos + 1,
2928 mb_strrpos($columnspec, ')') - $first_bracket_pos - 1
2931 // convert to lowercase just to be sure
2932 $type = mb_strtolower(
2933 chop(mb_substr($columnspec, 0, $first_bracket_pos))
2935 } else {
2936 // Split trailing attributes such as unsigned,
2937 // binary, zerofill and get data type name
2938 $type_parts = explode(' ', $columnspec);
2939 $type = mb_strtolower($type_parts[0]);
2940 $spec_in_brackets = '';
2943 if ('enum' == $type || 'set' == $type) {
2944 // Define our working vars
2945 $enum_set_values = self::parseEnumSetValues($columnspec, false);
2946 $printtype = $type
2947 . '(' . str_replace("','", "', '", $spec_in_brackets) . ')';
2948 $binary = false;
2949 $unsigned = false;
2950 $zerofill = false;
2951 } else {
2952 $enum_set_values = array();
2954 /* Create printable type name */
2955 $printtype = mb_strtolower($columnspec);
2957 // Strip the "BINARY" attribute, except if we find "BINARY(" because
2958 // this would be a BINARY or VARBINARY column type;
2959 // by the way, a BLOB should not show the BINARY attribute
2960 // because this is not accepted in MySQL syntax.
2961 if (preg_match('@binary@', $printtype)
2962 && ! preg_match('@binary[\(]@', $printtype)
2964 $printtype = preg_replace('@binary@', '', $printtype);
2965 $binary = true;
2966 } else {
2967 $binary = false;
2970 $printtype = preg_replace(
2971 '@zerofill@', '', $printtype, -1, $zerofill_cnt
2973 $zerofill = ($zerofill_cnt > 0);
2974 $printtype = preg_replace(
2975 '@unsigned@', '', $printtype, -1, $unsigned_cnt
2977 $unsigned = ($unsigned_cnt > 0);
2978 $printtype = trim($printtype);
2981 $attribute = ' ';
2982 if ($binary) {
2983 $attribute = 'BINARY';
2985 if ($unsigned) {
2986 $attribute = 'UNSIGNED';
2988 if ($zerofill) {
2989 $attribute = 'UNSIGNED ZEROFILL';
2992 $can_contain_collation = false;
2993 if (! $binary
2994 && preg_match(
2995 "@^(char|varchar|text|tinytext|mediumtext|longtext|set|enum)@", $type
2998 $can_contain_collation = true;
3001 // for the case ENUM('&#8211;','&ldquo;')
3002 $displayed_type = htmlspecialchars($printtype);
3003 if (mb_strlen($printtype) > $GLOBALS['cfg']['LimitChars']) {
3004 $displayed_type = '<abbr title="' . htmlspecialchars($printtype) . '">';
3005 $displayed_type .= htmlspecialchars(
3006 mb_substr(
3007 $printtype, 0, $GLOBALS['cfg']['LimitChars']
3008 ) . '...'
3010 $displayed_type .= '</abbr>';
3013 return array(
3014 'type' => $type,
3015 'spec_in_brackets' => $spec_in_brackets,
3016 'enum_set_values' => $enum_set_values,
3017 'print_type' => $printtype,
3018 'binary' => $binary,
3019 'unsigned' => $unsigned,
3020 'zerofill' => $zerofill,
3021 'attribute' => $attribute,
3022 'can_contain_collation' => $can_contain_collation,
3023 'displayed_type' => $displayed_type
3028 * Verifies if this table's engine supports foreign keys
3030 * @param string $engine engine
3032 * @return boolean
3034 public static function isForeignKeySupported($engine)
3036 $engine = strtoupper($engine);
3037 if (($engine == 'INNODB') || ($engine == 'PBXT')) {
3038 return true;
3039 } elseif ($engine == 'NDBCLUSTER' || $engine == 'NDB') {
3040 $ndbver = strtolower(
3041 $GLOBALS['dbi']->fetchValue("SELECT @@ndb_version_string")
3043 if (substr($ndbver, 0, 4) == 'ndb-') {
3044 $ndbver = substr($ndbver, 4);
3046 return version_compare($ndbver, 7.3, '>=');
3047 } else {
3048 return false;
3053 * Is Foreign key check enabled?
3055 * @return bool
3057 public static function isForeignKeyCheck()
3059 if ($GLOBALS['cfg']['DefaultForeignKeyChecks'] === 'enable') {
3060 return true;
3061 } else if ($GLOBALS['cfg']['DefaultForeignKeyChecks'] === 'disable') {
3062 return false;
3064 return ($GLOBALS['dbi']->getVariable('FOREIGN_KEY_CHECKS') == 'ON');
3068 * Get HTML for Foreign key check checkbox
3070 * @return string HTML for checkbox
3072 public static function getFKCheckbox()
3074 $checked = self::isForeignKeyCheck();
3075 $html = '<input type="hidden" name="fk_checks" value="0" />';
3076 $html .= '<input type="checkbox" name="fk_checks"'
3077 . ' id="fk_checks" value="1"'
3078 . ($checked ? ' checked="checked"' : '') . '/>';
3079 $html .= '<label for="fk_checks">' . __('Enable foreign key checks')
3080 . '</label>';
3081 return $html;
3085 * Handle foreign key check request
3087 * @return bool Default foreign key checks value
3089 public static function handleDisableFKCheckInit()
3091 $default_fk_check_value
3092 = $GLOBALS['dbi']->getVariable('FOREIGN_KEY_CHECKS') == 'ON';
3093 if (isset($_REQUEST['fk_checks'])) {
3094 if (empty($_REQUEST['fk_checks'])) {
3095 // Disable foreign key checks
3096 $GLOBALS['dbi']->setVariable('FOREIGN_KEY_CHECKS', 'OFF');
3097 } else {
3098 // Enable foreign key checks
3099 $GLOBALS['dbi']->setVariable('FOREIGN_KEY_CHECKS', 'ON');
3101 } // else do nothing, go with default
3102 return $default_fk_check_value;
3106 * Cleanup changes done for foreign key check
3108 * @param bool $default_fk_check_value original value for 'FOREIGN_KEY_CHECKS'
3110 * @return void
3112 public static function handleDisableFKCheckCleanup($default_fk_check_value)
3114 $GLOBALS['dbi']->setVariable(
3115 'FOREIGN_KEY_CHECKS', $default_fk_check_value ? 'ON' : 'OFF'
3120 * Converts GIS data to Well Known Text format
3122 * @param string $data GIS data
3123 * @param bool $includeSRID Add SRID to the WKT
3125 * @return string GIS data in Well Know Text format
3127 public static function asWKT($data, $includeSRID = false)
3129 // Convert to WKT format
3130 $hex = bin2hex($data);
3131 $wktsql = "SELECT ASTEXT(x'" . $hex . "')";
3132 if ($includeSRID) {
3133 $wktsql .= ", SRID(x'" . $hex . "')";
3136 $wktresult = $GLOBALS['dbi']->tryQuery(
3137 $wktsql, null, DatabaseInterface::QUERY_STORE
3139 $wktarr = $GLOBALS['dbi']->fetchRow($wktresult, 0);
3140 $wktval = $wktarr[0];
3142 if ($includeSRID) {
3143 $srid = $wktarr[1];
3144 $wktval = "'" . $wktval . "'," . $srid;
3146 @$GLOBALS['dbi']->freeResult($wktresult);
3148 return $wktval;
3152 * If the string starts with a \r\n pair (0x0d0a) add an extra \n
3154 * @param string $string string
3156 * @return string with the chars replaced
3158 public static function duplicateFirstNewline($string)
3160 $first_occurence = mb_strpos($string, "\r\n");
3161 if ($first_occurence === 0) {
3162 $string = "\n" . $string;
3164 return $string;
3168 * Get the action word corresponding to a script name
3169 * in order to display it as a title in navigation panel
3171 * @param string $target a valid value for $cfg['NavigationTreeDefaultTabTable'],
3172 * $cfg['NavigationTreeDefaultTabTable2'],
3173 * $cfg['DefaultTabTable'] or $cfg['DefaultTabDatabase']
3175 * @return string Title for the $cfg value
3177 public static function getTitleForTarget($target)
3179 $mapping = array(
3180 'structure' => __('Structure'),
3181 'sql' => __('SQL'),
3182 'search' =>__('Search'),
3183 'insert' =>__('Insert'),
3184 'browse' => __('Browse'),
3185 'operations' => __('Operations'),
3187 // For backward compatiblity
3189 // Values for $cfg['DefaultTabTable']
3190 'tbl_structure.php' => __('Structure'),
3191 'tbl_sql.php' => __('SQL'),
3192 'tbl_select.php' =>__('Search'),
3193 'tbl_change.php' =>__('Insert'),
3194 'sql.php' => __('Browse'),
3195 // Values for $cfg['DefaultTabDatabase']
3196 'db_structure.php' => __('Structure'),
3197 'db_sql.php' => __('SQL'),
3198 'db_search.php' => __('Search'),
3199 'db_operations.php' => __('Operations'),
3201 return isset($mapping[$target]) ? $mapping[$target] : false;
3205 * Get the script name corresponding to a plain English config word
3206 * in order to append in links on navigation and main panel
3208 * @param string $target a valid value for
3209 * $cfg['NavigationTreeDefaultTabTable'],
3210 * $cfg['NavigationTreeDefaultTabTable2'],
3211 * $cfg['DefaultTabTable'], $cfg['DefaultTabDatabase'] or
3212 * $cfg['DefaultTabServer']
3213 * @param string $location one out of 'server', 'table', 'database'
3215 * @return string script name corresponding to the config word
3217 public static function getScriptNameForOption($target, $location)
3219 if ($location == 'server') {
3220 // Values for $cfg['DefaultTabServer']
3221 switch ($target) {
3222 case 'welcome':
3223 return 'index.php';
3224 case 'databases':
3225 return 'server_databases.php';
3226 case 'status':
3227 return 'server_status.php';
3228 case 'variables':
3229 return 'server_variables.php';
3230 case 'privileges':
3231 return 'server_privileges.php';
3233 } elseif ($location == 'database') {
3234 // Values for $cfg['DefaultTabDatabase']
3235 switch ($target) {
3236 case 'structure':
3237 return 'db_structure.php';
3238 case 'sql':
3239 return 'db_sql.php';
3240 case 'search':
3241 return 'db_search.php';
3242 case 'operations':
3243 return 'db_operations.php';
3245 } elseif ($location == 'table') {
3246 // Values for $cfg['DefaultTabTable'],
3247 // $cfg['NavigationTreeDefaultTabTable'] and
3248 // $cfg['NavigationTreeDefaultTabTable2']
3249 switch ($target) {
3250 case 'structure':
3251 return 'tbl_structure.php';
3252 case 'sql':
3253 return 'tbl_sql.php';
3254 case 'search':
3255 return 'tbl_select.php';
3256 case 'insert':
3257 return 'tbl_change.php';
3258 case 'browse':
3259 return 'sql.php';
3263 return $target;
3267 * Formats user string, expanding @VARIABLES@, accepting strftime format
3268 * string.
3270 * @param string $string Text where to do expansion.
3271 * @param array|string $escape Function to call for escaping variable values.
3272 * Can also be an array of:
3273 * - the escape method name
3274 * - the class that contains the method
3275 * - location of the class (for inclusion)
3276 * @param array $updates Array with overrides for default parameters
3277 * (obtained from GLOBALS).
3279 * @return string
3281 public static function expandUserString(
3282 $string, $escape = null, $updates = array()
3284 /* Content */
3285 $vars = array();
3286 $vars['http_host'] = PMA_getenv('HTTP_HOST');
3287 $vars['server_name'] = $GLOBALS['cfg']['Server']['host'];
3288 $vars['server_verbose'] = $GLOBALS['cfg']['Server']['verbose'];
3290 if (empty($GLOBALS['cfg']['Server']['verbose'])) {
3291 $vars['server_verbose_or_name'] = $GLOBALS['cfg']['Server']['host'];
3292 } else {
3293 $vars['server_verbose_or_name'] = $GLOBALS['cfg']['Server']['verbose'];
3296 $vars['database'] = $GLOBALS['db'];
3297 $vars['table'] = $GLOBALS['table'];
3298 $vars['phpmyadmin_version'] = 'phpMyAdmin ' . PMA_VERSION;
3300 /* Update forced variables */
3301 foreach ($updates as $key => $val) {
3302 $vars[$key] = $val;
3305 /* Replacement mapping */
3307 * The __VAR__ ones are for backward compatibility, because user
3308 * might still have it in cookies.
3310 $replace = array(
3311 '@HTTP_HOST@' => $vars['http_host'],
3312 '@SERVER@' => $vars['server_name'],
3313 '__SERVER__' => $vars['server_name'],
3314 '@VERBOSE@' => $vars['server_verbose'],
3315 '@VSERVER@' => $vars['server_verbose_or_name'],
3316 '@DATABASE@' => $vars['database'],
3317 '__DB__' => $vars['database'],
3318 '@TABLE@' => $vars['table'],
3319 '__TABLE__' => $vars['table'],
3320 '@PHPMYADMIN@' => $vars['phpmyadmin_version'],
3323 /* Optional escaping */
3324 if (! is_null($escape)) {
3325 if (is_array($escape)) {
3326 $escape_class = new $escape[1];
3327 $escape_method = $escape[0];
3329 foreach ($replace as $key => $val) {
3330 if (is_array($escape)) {
3331 $replace[$key] = $escape_class->$escape_method($val);
3332 } else {
3333 $replace[$key] = ($escape == 'backquote')
3334 ? self::$escape($val)
3335 : $escape($val);
3340 /* Backward compatibility in 3.5.x */
3341 if (mb_strpos($string, '@FIELDS@') !== false) {
3342 $string = strtr($string, array('@FIELDS@' => '@COLUMNS@'));
3345 /* Fetch columns list if required */
3346 if (mb_strpos($string, '@COLUMNS@') !== false) {
3347 $columns_list = $GLOBALS['dbi']->getColumns(
3348 $GLOBALS['db'], $GLOBALS['table']
3351 // sometimes the table no longer exists at this point
3352 if (! is_null($columns_list)) {
3353 $column_names = array();
3354 foreach ($columns_list as $column) {
3355 if (! is_null($escape)) {
3356 $column_names[] = self::$escape($column['Field']);
3357 } else {
3358 $column_names[] = $column['Field'];
3361 $replace['@COLUMNS@'] = implode(',', $column_names);
3362 } else {
3363 $replace['@COLUMNS@'] = '*';
3367 /* Do the replacement */
3368 return strtr(strftime($string), $replace);
3372 * Prepare the form used to browse anywhere on the local server for a file to
3373 * import
3375 * @param string $max_upload_size maximum upload size
3377 * @return String
3379 public static function getBrowseUploadFileBlock($max_upload_size)
3381 $block_html = '';
3383 if ($GLOBALS['is_upload'] && ! empty($GLOBALS['cfg']['UploadDir'])) {
3384 $block_html .= '<label for="radio_import_file">';
3385 } else {
3386 $block_html .= '<label for="input_import_file">';
3389 $block_html .= __("Browse your computer:") . '</label>'
3390 . '<div id="upload_form_status" style="display: none;"></div>'
3391 . '<div id="upload_form_status_info" style="display: none;"></div>'
3392 . '<input type="file" name="import_file" id="input_import_file" />'
3393 . self::getFormattedMaximumUploadSize($max_upload_size) . "\n"
3394 // some browsers should respect this :)
3395 . self::generateHiddenMaxFileSize($max_upload_size) . "\n";
3397 return $block_html;
3401 * Prepare the form used to select a file to import from the server upload
3402 * directory
3404 * @param ImportPlugin[] $import_list array of import plugins
3405 * @param string $uploaddir upload directory
3407 * @return String
3409 public static function getSelectUploadFileBlock($import_list, $uploaddir)
3411 $block_html = '';
3412 $block_html .= '<label for="radio_local_import_file">'
3413 . sprintf(
3414 __("Select from the web server upload directory <b>%s</b>:"),
3415 htmlspecialchars(self::userDir($uploaddir))
3417 . '</label>';
3419 $extensions = '';
3420 foreach ($import_list as $import_plugin) {
3421 if (! empty($extensions)) {
3422 $extensions .= '|';
3424 $extensions .= $import_plugin->getProperties()->getExtension();
3427 $matcher = '@\.(' . $extensions . ')(\.('
3428 . PMA_supportedDecompressions() . '))?$@';
3430 $active = (isset($GLOBALS['timeout_passed']) && $GLOBALS['timeout_passed']
3431 && isset($GLOBALS['local_import_file']))
3432 ? $GLOBALS['local_import_file']
3433 : '';
3435 $files = PMA_getFileSelectOptions(
3436 self::userDir($uploaddir),
3437 $matcher,
3438 $active
3441 if ($files === false) {
3442 Message::error(
3443 __('The directory you set for upload work cannot be reached.')
3444 )->display();
3445 } elseif (! empty($files)) {
3446 $block_html .= "\n"
3447 . ' <select style="margin: 5px" size="1" '
3448 . 'name="local_import_file" '
3449 . 'id="select_local_import_file">' . "\n"
3450 . ' <option value="">&nbsp;</option>' . "\n"
3451 . $files
3452 . ' </select>' . "\n";
3453 } elseif (empty($files)) {
3454 $block_html .= '<i>' . __('There are no files to upload!') . '</i>';
3457 return $block_html;
3462 * Build titles and icons for action links
3464 * @return array the action titles
3466 public static function buildActionTitles()
3468 $titles = array();
3470 $titles['Browse'] = self::getIcon('b_browse.png', __('Browse'));
3471 $titles['NoBrowse'] = self::getIcon('bd_browse.png', __('Browse'));
3472 $titles['Search'] = self::getIcon('b_select.png', __('Search'));
3473 $titles['NoSearch'] = self::getIcon('bd_select.png', __('Search'));
3474 $titles['Insert'] = self::getIcon('b_insrow.png', __('Insert'));
3475 $titles['NoInsert'] = self::getIcon('bd_insrow.png', __('Insert'));
3476 $titles['Structure'] = self::getIcon('b_props.png', __('Structure'));
3477 $titles['Drop'] = self::getIcon('b_drop.png', __('Drop'));
3478 $titles['NoDrop'] = self::getIcon('bd_drop.png', __('Drop'));
3479 $titles['Empty'] = self::getIcon('b_empty.png', __('Empty'));
3480 $titles['NoEmpty'] = self::getIcon('bd_empty.png', __('Empty'));
3481 $titles['Edit'] = self::getIcon('b_edit.png', __('Edit'));
3482 $titles['NoEdit'] = self::getIcon('bd_edit.png', __('Edit'));
3483 $titles['Export'] = self::getIcon('b_export.png', __('Export'));
3484 $titles['NoExport'] = self::getIcon('bd_export.png', __('Export'));
3485 $titles['Execute'] = self::getIcon('b_nextpage.png', __('Execute'));
3486 $titles['NoExecute'] = self::getIcon('bd_nextpage.png', __('Execute'));
3487 // For Favorite/NoFavorite, we need icon only.
3488 $titles['Favorite'] = self::getIcon('b_favorite.png', '');
3489 $titles['NoFavorite']= self::getIcon('b_no_favorite.png', '');
3491 return $titles;
3495 * This function processes the datatypes supported by the DB,
3496 * as specified in Types->getColumns() and either returns an array
3497 * (useful for quickly checking if a datatype is supported)
3498 * or an HTML snippet that creates a drop-down list.
3500 * @param bool $html Whether to generate an html snippet or an array
3501 * @param string $selected The value to mark as selected in HTML mode
3503 * @return mixed An HTML snippet or an array of datatypes.
3506 public static function getSupportedDatatypes($html = false, $selected = '')
3508 if ($html) {
3510 // NOTE: the SELECT tag in not included in this snippet.
3511 $retval = '';
3513 foreach ($GLOBALS['PMA_Types']->getColumns() as $key => $value) {
3514 if (is_array($value)) {
3515 $retval .= "<optgroup label='" . htmlspecialchars($key) . "'>";
3516 foreach ($value as $subvalue) {
3517 if ($subvalue == $selected) {
3518 $retval .= sprintf(
3519 '<option selected="selected" title="%s">%s</option>',
3520 $GLOBALS['PMA_Types']->getTypeDescription($subvalue),
3521 $subvalue
3523 } else if ($subvalue === '-') {
3524 $retval .= '<option disabled="disabled">';
3525 $retval .= $subvalue;
3526 $retval .= '</option>';
3527 } else {
3528 $retval .= sprintf(
3529 '<option title="%s">%s</option>',
3530 $GLOBALS['PMA_Types']->getTypeDescription($subvalue),
3531 $subvalue
3535 $retval .= '</optgroup>';
3536 } else {
3537 if ($selected == $value) {
3538 $retval .= sprintf(
3539 '<option selected="selected" title="%s">%s</option>',
3540 $GLOBALS['PMA_Types']->getTypeDescription($value),
3541 $value
3543 } else {
3544 $retval .= sprintf(
3545 '<option title="%s">%s</option>',
3546 $GLOBALS['PMA_Types']->getTypeDescription($value),
3547 $value
3552 } else {
3553 $retval = array();
3554 foreach ($GLOBALS['PMA_Types']->getColumns() as $value) {
3555 if (is_array($value)) {
3556 foreach ($value as $subvalue) {
3557 if ($subvalue !== '-') {
3558 $retval[] = $subvalue;
3561 } else {
3562 if ($value !== '-') {
3563 $retval[] = $value;
3569 return $retval;
3570 } // end getSupportedDatatypes()
3573 * Returns a list of datatypes that are not (yet) handled by PMA.
3574 * Used by: tbl_change.php and libraries/db_routines.inc.php
3576 * @return array list of datatypes
3578 public static function unsupportedDatatypes()
3580 $no_support_types = array();
3581 return $no_support_types;
3585 * Return GIS data types
3587 * @param bool $upper_case whether to return values in upper case
3589 * @return string[] GIS data types
3591 public static function getGISDatatypes($upper_case = false)
3593 $gis_data_types = array(
3594 'geometry',
3595 'point',
3596 'linestring',
3597 'polygon',
3598 'multipoint',
3599 'multilinestring',
3600 'multipolygon',
3601 'geometrycollection'
3603 if ($upper_case) {
3604 for ($i = 0, $nb = count($gis_data_types); $i < $nb; $i++) {
3605 $gis_data_types[$i]
3606 = mb_strtoupper($gis_data_types[$i]);
3609 return $gis_data_types;
3613 * Generates GIS data based on the string passed.
3615 * @param string $gis_string GIS string
3617 * @return string GIS data enclosed in 'GeomFromText' function
3619 public static function createGISData($gis_string)
3621 $gis_string = trim($gis_string);
3622 $geom_types = '(POINT|MULTIPOINT|LINESTRING|MULTILINESTRING|'
3623 . 'POLYGON|MULTIPOLYGON|GEOMETRYCOLLECTION)';
3624 if (preg_match("/^'" . $geom_types . "\(.*\)',[0-9]*$/i", $gis_string)) {
3625 return 'GeomFromText(' . $gis_string . ')';
3626 } elseif (preg_match("/^" . $geom_types . "\(.*\)$/i", $gis_string)) {
3627 return "GeomFromText('" . $gis_string . "')";
3628 } else {
3629 return $gis_string;
3634 * Returns the names and details of the functions
3635 * that can be applied on geometry data types.
3637 * @param string $geom_type if provided the output is limited to the functions
3638 * that are applicable to the provided geometry type.
3639 * @param bool $binary if set to false functions that take two geometries
3640 * as arguments will not be included.
3641 * @param bool $display if set to true separators will be added to the
3642 * output array.
3644 * @return array names and details of the functions that can be applied on
3645 * geometry data types.
3647 public static function getGISFunctions(
3648 $geom_type = null, $binary = true, $display = false
3650 $funcs = array();
3651 if ($display) {
3652 $funcs[] = array('display' => ' ');
3655 // Unary functions common to all geometry types
3656 $funcs['Dimension'] = array('params' => 1, 'type' => 'int');
3657 $funcs['Envelope'] = array('params' => 1, 'type' => 'Polygon');
3658 $funcs['GeometryType'] = array('params' => 1, 'type' => 'text');
3659 $funcs['SRID'] = array('params' => 1, 'type' => 'int');
3660 $funcs['IsEmpty'] = array('params' => 1, 'type' => 'int');
3661 $funcs['IsSimple'] = array('params' => 1, 'type' => 'int');
3663 $geom_type = trim(mb_strtolower($geom_type));
3664 if ($display && $geom_type != 'geometry' && $geom_type != 'multipoint') {
3665 $funcs[] = array('display' => '--------');
3668 // Unary functions that are specific to each geometry type
3669 if ($geom_type == 'point') {
3670 $funcs['X'] = array('params' => 1, 'type' => 'float');
3671 $funcs['Y'] = array('params' => 1, 'type' => 'float');
3673 } elseif ($geom_type == 'multipoint') {
3674 // no functions here
3675 } elseif ($geom_type == 'linestring') {
3676 $funcs['EndPoint'] = array('params' => 1, 'type' => 'point');
3677 $funcs['GLength'] = array('params' => 1, 'type' => 'float');
3678 $funcs['NumPoints'] = array('params' => 1, 'type' => 'int');
3679 $funcs['StartPoint'] = array('params' => 1, 'type' => 'point');
3680 $funcs['IsRing'] = array('params' => 1, 'type' => 'int');
3682 } elseif ($geom_type == 'multilinestring') {
3683 $funcs['GLength'] = array('params' => 1, 'type' => 'float');
3684 $funcs['IsClosed'] = array('params' => 1, 'type' => 'int');
3686 } elseif ($geom_type == 'polygon') {
3687 $funcs['Area'] = array('params' => 1, 'type' => 'float');
3688 $funcs['ExteriorRing'] = array('params' => 1, 'type' => 'linestring');
3689 $funcs['NumInteriorRings'] = array('params' => 1, 'type' => 'int');
3691 } elseif ($geom_type == 'multipolygon') {
3692 $funcs['Area'] = array('params' => 1, 'type' => 'float');
3693 $funcs['Centroid'] = array('params' => 1, 'type' => 'point');
3694 // Not yet implemented in MySQL
3695 //$funcs['PointOnSurface'] = array('params' => 1, 'type' => 'point');
3697 } elseif ($geom_type == 'geometrycollection') {
3698 $funcs['NumGeometries'] = array('params' => 1, 'type' => 'int');
3701 // If we are asked for binary functions as well
3702 if ($binary) {
3703 // section separator
3704 if ($display) {
3705 $funcs[] = array('display' => '--------');
3708 if (PMA_MYSQL_INT_VERSION < 50601) {
3709 $funcs['Crosses'] = array('params' => 2, 'type' => 'int');
3710 $funcs['Contains'] = array('params' => 2, 'type' => 'int');
3711 $funcs['Disjoint'] = array('params' => 2, 'type' => 'int');
3712 $funcs['Equals'] = array('params' => 2, 'type' => 'int');
3713 $funcs['Intersects'] = array('params' => 2, 'type' => 'int');
3714 $funcs['Overlaps'] = array('params' => 2, 'type' => 'int');
3715 $funcs['Touches'] = array('params' => 2, 'type' => 'int');
3716 $funcs['Within'] = array('params' => 2, 'type' => 'int');
3717 } else {
3718 // If MySQl version is greater than or equal 5.6.1,
3719 // use the ST_ prefix.
3720 $funcs['ST_Crosses'] = array('params' => 2, 'type' => 'int');
3721 $funcs['ST_Contains'] = array('params' => 2, 'type' => 'int');
3722 $funcs['ST_Disjoint'] = array('params' => 2, 'type' => 'int');
3723 $funcs['ST_Equals'] = array('params' => 2, 'type' => 'int');
3724 $funcs['ST_Intersects'] = array('params' => 2, 'type' => 'int');
3725 $funcs['ST_Overlaps'] = array('params' => 2, 'type' => 'int');
3726 $funcs['ST_Touches'] = array('params' => 2, 'type' => 'int');
3727 $funcs['ST_Within'] = array('params' => 2, 'type' => 'int');
3730 if ($display) {
3731 $funcs[] = array('display' => '--------');
3733 // Minimum bounding rectangle functions
3734 $funcs['MBRContains'] = array('params' => 2, 'type' => 'int');
3735 $funcs['MBRDisjoint'] = array('params' => 2, 'type' => 'int');
3736 $funcs['MBREquals'] = array('params' => 2, 'type' => 'int');
3737 $funcs['MBRIntersects'] = array('params' => 2, 'type' => 'int');
3738 $funcs['MBROverlaps'] = array('params' => 2, 'type' => 'int');
3739 $funcs['MBRTouches'] = array('params' => 2, 'type' => 'int');
3740 $funcs['MBRWithin'] = array('params' => 2, 'type' => 'int');
3742 return $funcs;
3746 * Returns default function for a particular column.
3748 * @param array $field Data about the column for which
3749 * to generate the dropdown
3750 * @param bool $insert_mode Whether the operation is 'insert'
3752 * @global array $cfg PMA configuration
3753 * @global mixed $data data of currently edited row
3754 * (used to detect whether to choose defaults)
3756 * @return string An HTML snippet of a dropdown list with function
3757 * names appropriate for the requested column.
3759 public static function getDefaultFunctionForField($field, $insert_mode)
3762 * @todo Except for $cfg, no longer use globals but pass as parameters
3763 * from higher levels
3765 global $cfg, $data;
3767 $default_function = '';
3769 // Can we get field class based values?
3770 $current_class = $GLOBALS['PMA_Types']->getTypeClass($field['True_Type']);
3771 if (! empty($current_class)) {
3772 if (isset($cfg['DefaultFunctions']['FUNC_' . $current_class])) {
3773 $default_function
3774 = $cfg['DefaultFunctions']['FUNC_' . $current_class];
3778 // what function defined as default?
3779 // for the first timestamp we don't set the default function
3780 // if there is a default value for the timestamp
3781 // (not including CURRENT_TIMESTAMP)
3782 // and the column does not have the
3783 // ON UPDATE DEFAULT TIMESTAMP attribute.
3784 if (($field['True_Type'] == 'timestamp')
3785 && $field['first_timestamp']
3786 && empty($field['Default'])
3787 && empty($data)
3788 && $field['Extra'] != 'on update CURRENT_TIMESTAMP'
3789 && $field['Null'] == 'NO'
3791 $default_function = $cfg['DefaultFunctions']['first_timestamp'];
3794 // For primary keys of type char(36) or varchar(36) UUID if the default
3795 // function
3796 // Only applies to insert mode, as it would silently trash data on updates.
3797 if ($insert_mode
3798 && $field['Key'] == 'PRI'
3799 && ($field['Type'] == 'char(36)' || $field['Type'] == 'varchar(36)')
3801 $default_function = $cfg['DefaultFunctions']['FUNC_UUID'];
3804 return $default_function;
3808 * Creates a dropdown box with MySQL functions for a particular column.
3810 * @param array $field Data about the column for which
3811 * to generate the dropdown
3812 * @param bool $insert_mode Whether the operation is 'insert'
3814 * @return string An HTML snippet of a dropdown list with function
3815 * names appropriate for the requested column.
3817 public static function getFunctionsForField($field, $insert_mode, $foreignData)
3819 $default_function = self::getDefaultFunctionForField($field, $insert_mode);
3820 $dropdown_built = array();
3822 // Create the output
3823 $retval = '<option></option>' . "\n";
3824 // loop on the dropdown array and print all available options for that
3825 // field.
3826 $functions = $GLOBALS['PMA_Types']->getFunctions($field['True_Type']);
3827 foreach ($functions as $function) {
3828 $retval .= '<option';
3829 if (isset($foreignData['foreign_link']) && $foreignData['foreign_link'] !== false && $default_function === $function) {
3830 $retval .= ' selected="selected"';
3832 $retval .= '>' . $function . '</option>' . "\n";
3833 $dropdown_built[$function] = true;
3836 // Create separator before all functions list
3837 if (count($functions) > 0) {
3838 $retval .= '<option value="" disabled="disabled">--------</option>'
3839 . "\n";
3842 // For compatibility's sake, do not let out all other functions. Instead
3843 // print a separator (blank) and then show ALL functions which weren't
3844 // shown yet.
3845 $functions = $GLOBALS['PMA_Types']->getAllFunctions();
3846 foreach ($functions as $function) {
3847 // Skip already included functions
3848 if (isset($dropdown_built[$function])) {
3849 continue;
3851 $retval .= '<option';
3852 if ($default_function === $function) {
3853 $retval .= ' selected="selected"';
3855 $retval .= '>' . $function . '</option>' . "\n";
3856 } // end for
3858 return $retval;
3859 } // end getFunctionsForField()
3862 * Checks if the current user has a specific privilege and returns true if the
3863 * user indeed has that privilege or false if (s)he doesn't. This function must
3864 * only be used for features that are available since MySQL 5, because it
3865 * relies on the INFORMATION_SCHEMA database to be present.
3867 * Example: currentUserHasPrivilege('CREATE ROUTINE', 'mydb');
3868 * // Checks if the currently logged in user has the global
3869 * // 'CREATE ROUTINE' privilege or, if not, checks if the
3870 * // user has this privilege on database 'mydb'.
3872 * @param string $priv The privilege to check
3873 * @param mixed $db null, to only check global privileges
3874 * string, db name where to also check for privileges
3875 * @param mixed $tbl null, to only check global/db privileges
3876 * string, table name where to also check for privileges
3878 * @return bool
3880 public static function currentUserHasPrivilege($priv, $db = null, $tbl = null)
3882 // Get the username for the current user in the format
3883 // required to use in the information schema database.
3884 list($user, $host) = $GLOBALS['dbi']->getCurrentUserAndHost();
3886 if ($user === '') { // MySQL is started with --skip-grant-tables
3887 return true;
3890 $username = "''";
3891 $username .= str_replace("'", "''", $user);
3892 $username .= "''@''";
3893 $username .= str_replace("'", "''", $host);
3894 $username .= "''";
3896 // Prepare the query
3897 $query = "SELECT `PRIVILEGE_TYPE` FROM `INFORMATION_SCHEMA`.`%s` "
3898 . "WHERE GRANTEE='%s' AND PRIVILEGE_TYPE='%s'";
3900 // Check global privileges first.
3901 $user_privileges = $GLOBALS['dbi']->fetchValue(
3902 sprintf(
3903 $query,
3904 'USER_PRIVILEGES',
3905 $username,
3906 $priv
3909 if ($user_privileges) {
3910 return true;
3912 // If a database name was provided and user does not have the
3913 // required global privilege, try database-wise permissions.
3914 if ($db !== null) {
3915 $query .= " AND '%s' LIKE `TABLE_SCHEMA`";
3916 $schema_privileges = $GLOBALS['dbi']->fetchValue(
3917 sprintf(
3918 $query,
3919 'SCHEMA_PRIVILEGES',
3920 $username,
3921 $priv,
3922 $GLOBALS['dbi']->escapeString($db)
3925 if ($schema_privileges) {
3926 return true;
3928 } else {
3929 // There was no database name provided and the user
3930 // does not have the correct global privilege.
3931 return false;
3933 // If a table name was also provided and we still didn't
3934 // find any valid privileges, try table-wise privileges.
3935 if ($tbl !== null) {
3936 // need to escape wildcards in db and table names, see bug #3518484
3937 $tbl = str_replace(array('%', '_'), array('\%', '\_'), $tbl);
3938 $query .= " AND TABLE_NAME='%s'";
3939 $table_privileges = $GLOBALS['dbi']->fetchValue(
3940 sprintf(
3941 $query,
3942 'TABLE_PRIVILEGES',
3943 $username,
3944 $priv,
3945 $GLOBALS['dbi']->escapeString($db),
3946 $GLOBALS['dbi']->escapeString($tbl)
3949 if ($table_privileges) {
3950 return true;
3953 // If we reached this point, the user does not
3954 // have even valid table-wise privileges.
3955 return false;
3959 * Returns server type for current connection
3961 * Known types are: MariaDB and MySQL (default)
3963 * @return string
3965 public static function getServerType()
3967 $server_type = 'MySQL';
3969 if (mb_stripos(PMA_MYSQL_STR_VERSION, 'mariadb') !== false) {
3970 $server_type = 'MariaDB';
3971 return $server_type;
3974 if (mb_stripos(PMA_MYSQL_VERSION_COMMENT, 'percona') !== false) {
3975 $server_type = 'Percona Server';
3976 return $server_type;
3979 return $server_type;
3983 * Prepare HTML code for display button.
3985 * @return String
3987 public static function getButton()
3989 return '<p class="print_ignore">'
3990 . '<input type="button" class="button" id="print" value="'
3991 . __('Print') . '" />'
3992 . '</p>';
3996 * Parses ENUM/SET values
3998 * @param string $definition The definition of the column
3999 * for which to parse the values
4000 * @param bool $escapeHtml Whether to escape html entities
4002 * @return array
4004 public static function parseEnumSetValues($definition, $escapeHtml = true)
4006 $values_string = htmlentities($definition, ENT_COMPAT, "UTF-8");
4007 // There is a JS port of the below parser in functions.js
4008 // If you are fixing something here,
4009 // you need to also update the JS port.
4010 $values = array();
4011 $in_string = false;
4012 $buffer = '';
4014 for ($i = 0, $length = mb_strlen($values_string);
4015 $i < $length;
4016 $i++
4018 $curr = mb_substr($values_string, $i, 1);
4019 $next = ($i == mb_strlen($values_string) - 1)
4020 ? ''
4021 : mb_substr($values_string, $i + 1, 1);
4023 if (! $in_string && $curr == "'") {
4024 $in_string = true;
4025 } else if (($in_string && $curr == "\\") && $next == "\\") {
4026 $buffer .= "&#92;";
4027 $i++;
4028 } else if (($in_string && $next == "'")
4029 && ($curr == "'" || $curr == "\\")
4031 $buffer .= "&#39;";
4032 $i++;
4033 } else if ($in_string && $curr == "'") {
4034 $in_string = false;
4035 $values[] = $buffer;
4036 $buffer = '';
4037 } else if ($in_string) {
4038 $buffer .= $curr;
4043 if (strlen($buffer) > 0) {
4044 // The leftovers in the buffer are the last value (if any)
4045 $values[] = $buffer;
4048 if (! $escapeHtml) {
4049 foreach ($values as $key => $value) {
4050 $values[$key] = html_entity_decode($value, ENT_QUOTES, 'UTF-8');
4054 return $values;
4058 * Get regular expression which occur first inside the given sql query.
4060 * @param array $regex_array Comparing regular expressions.
4061 * @param String $query SQL query to be checked.
4063 * @return String Matching regular expression.
4065 public static function getFirstOccurringRegularExpression($regex_array, $query)
4067 $minimum_first_occurence_index = null;
4068 $regex = null;
4070 foreach ($regex_array as $test_regex) {
4071 if (preg_match($test_regex, $query, $matches, PREG_OFFSET_CAPTURE)) {
4072 if (is_null($minimum_first_occurence_index)
4073 || ($matches[0][1] < $minimum_first_occurence_index)
4075 $regex = $test_regex;
4076 $minimum_first_occurence_index = $matches[0][1];
4080 return $regex;
4084 * Return the list of tabs for the menu with corresponding names
4086 * @param string $level 'server', 'db' or 'table' level
4088 * @return array list of tabs for the menu
4090 public static function getMenuTabList($level = null)
4092 $tabList = array(
4093 'server' => array(
4094 'databases' => __('Databases'),
4095 'sql' => __('SQL'),
4096 'status' => __('Status'),
4097 'rights' => __('Users'),
4098 'export' => __('Export'),
4099 'import' => __('Import'),
4100 'settings' => __('Settings'),
4101 'binlog' => __('Binary log'),
4102 'replication' => __('Replication'),
4103 'vars' => __('Variables'),
4104 'charset' => __('Charsets'),
4105 'plugins' => __('Plugins'),
4106 'engine' => __('Engines')
4108 'db' => array(
4109 'structure' => __('Structure'),
4110 'sql' => __('SQL'),
4111 'search' => __('Search'),
4112 'qbe' => __('Query'),
4113 'export' => __('Export'),
4114 'import' => __('Import'),
4115 'operation' => __('Operations'),
4116 'privileges' => __('Privileges'),
4117 'routines' => __('Routines'),
4118 'events' => __('Events'),
4119 'triggers' => __('Triggers'),
4120 'tracking' => __('Tracking'),
4121 'designer' => __('Designer'),
4122 'central_columns' => __('Central columns')
4124 'table' => array(
4125 'browse' => __('Browse'),
4126 'structure' => __('Structure'),
4127 'sql' => __('SQL'),
4128 'search' => __('Search'),
4129 'insert' => __('Insert'),
4130 'export' => __('Export'),
4131 'import' => __('Import'),
4132 'privileges' => __('Privileges'),
4133 'operation' => __('Operations'),
4134 'tracking' => __('Tracking'),
4135 'triggers' => __('Triggers'),
4139 if ($level == null) {
4140 return $tabList;
4141 } else if (array_key_exists($level, $tabList)) {
4142 return $tabList[$level];
4143 } else {
4144 return null;
4149 * Returns information with regards to handling the http request
4151 * @param array $context Data about the context for which
4152 * to http request is sent
4154 * @return array of updated context information
4156 public static function handleContext(array $context)
4158 if (strlen($GLOBALS['cfg']['ProxyUrl']) > 0) {
4159 $context['http'] = array(
4160 'proxy' => $GLOBALS['cfg']['ProxyUrl'],
4161 'request_fulluri' => true
4163 if (strlen($GLOBALS['cfg']['ProxyUser']) > 0) {
4164 $auth = base64_encode(
4165 $GLOBALS['cfg']['ProxyUser'] . ':' . $GLOBALS['cfg']['ProxyPass']
4167 $context['http']['header'] .= 'Proxy-Authorization: Basic '
4168 . $auth . "\r\n";
4171 return $context;
4174 * Updates an existing curl as necessary
4176 * @param resource $curl_handle A curl_handle resource
4177 * created by curl_init which should
4178 * have several options set
4180 * @return resource curl_handle with updated options
4182 public static function configureCurl($curl_handle)
4184 if (strlen($GLOBALS['cfg']['ProxyUrl']) > 0) {
4185 curl_setopt($curl_handle, CURLOPT_PROXY, $GLOBALS['cfg']['ProxyUrl']);
4186 if (strlen($GLOBALS['cfg']['ProxyUser']) > 0) {
4187 curl_setopt(
4188 $curl_handle,
4189 CURLOPT_PROXYUSERPWD,
4190 $GLOBALS['cfg']['ProxyUser'] . ':' . $GLOBALS['cfg']['ProxyPass']
4194 curl_setopt($curl_handle, CURLOPT_USERAGENT, 'phpMyAdmin/' . PMA_VERSION);
4195 return $curl_handle;
4199 * Add fractional seconds to time, datetime and timestamp strings.
4200 * If the string contains fractional seconds,
4201 * pads it with 0s up to 6 decimal places.
4203 * @param string $value time, datetime or timestamp strings
4205 * @return string time, datetime or timestamp strings with fractional seconds
4207 public static function addMicroseconds($value)
4209 if (empty($value) || $value == 'CURRENT_TIMESTAMP') {
4210 return $value;
4213 if (mb_strpos($value, '.') === false) {
4214 return $value . '.000000';
4217 $value .= '000000';
4218 return mb_substr(
4219 $value,
4221 mb_strpos($value, '.') + 7
4226 * Reads the file, detects the compression MIME type, closes the file
4227 * and returns the MIME type
4229 * @param resource $file the file handle
4231 * @return string the MIME type for compression, or 'none'
4233 public static function getCompressionMimeType($file)
4235 $test = fread($file, 4);
4236 $len = strlen($test);
4237 fclose($file);
4238 if ($len >= 2 && $test[0] == chr(31) && $test[1] == chr(139)) {
4239 return 'application/gzip';
4241 if ($len >= 3 && substr($test, 0, 3) == 'BZh') {
4242 return 'application/bzip2';
4244 if ($len >= 4 && $test == "PK\003\004") {
4245 return 'application/zip';
4247 return 'none';
4251 * Renders a single link for the top of the navigation panel
4253 * @param string $link The url for the link
4254 * @param bool $showText Whether to show the text or to
4255 * only use it for title attributes
4256 * @param string $text The text to display and use for title attributes
4257 * @param bool $showIcon Whether to show the icon
4258 * @param string $icon The filename of the icon to show
4259 * @param string $linkId Value to use for the ID attribute
4260 * @param boolean $disableAjax Whether to disable ajax page loading for this link
4261 * @param string $linkTarget The name of the target frame for the link
4262 * @param array $classes HTML classes to apply
4264 * @return string HTML code for one link
4266 public static function getNavigationLink(
4267 $link,
4268 $showText,
4269 $text,
4270 $showIcon,
4271 $icon,
4272 $linkId = '',
4273 $disableAjax = false,
4274 $linkTarget = '',
4275 $classes = array()
4277 $retval = '<a href="' . $link . '"';
4278 if (! empty($linkId)) {
4279 $retval .= ' id="' . $linkId . '"';
4281 if (! empty($linkTarget)) {
4282 $retval .= ' target="' . $linkTarget . '"';
4284 if ($disableAjax) {
4285 $classes[] = 'disableAjax';
4287 if (!empty($classes)) {
4288 $retval .= ' class="' . join(" ", $classes) . '"';
4290 $retval .= ' title="' . $text . '">';
4291 if ($showIcon) {
4292 $retval .= Util::getImage(
4293 $icon,
4294 $text
4297 if ($showText) {
4298 $retval .= $text;
4300 $retval .= '</a>';
4301 if ($showText) {
4302 $retval .= '<br />';
4304 return $retval;
4308 * Provide COLLATE clause, if required, to perform case sensitive comparisons
4309 * for queries on information_schema.
4311 * @return string COLLATE clause if needed or empty string.
4313 public static function getCollateForIS()
4315 $names = $GLOBALS['dbi']->getLowerCaseNames();
4316 if ($names === '0') {
4317 return "COLLATE utf8_bin";
4318 } elseif ($names === '2') {
4319 return "COLLATE utf8_general_ci";
4321 return "";
4325 * Process the index data.
4327 * @param array $indexes index data
4329 * @return array processes index data
4331 public static function processIndexData($indexes)
4333 $lastIndex = '';
4335 $primary = '';
4336 $pk_array = array(); // will be use to emphasis prim. keys in the table
4337 $indexes_info = array();
4338 $indexes_data = array();
4340 // view
4341 foreach ($indexes as $row) {
4342 // Backups the list of primary keys
4343 if ($row['Key_name'] == 'PRIMARY') {
4344 $primary .= $row['Column_name'] . ', ';
4345 $pk_array[$row['Column_name']] = 1;
4347 // Retains keys informations
4348 if ($row['Key_name'] != $lastIndex) {
4349 $indexes[] = $row['Key_name'];
4350 $lastIndex = $row['Key_name'];
4352 $indexes_info[$row['Key_name']]['Sequences'][] = $row['Seq_in_index'];
4353 $indexes_info[$row['Key_name']]['Non_unique'] = $row['Non_unique'];
4354 if (isset($row['Cardinality'])) {
4355 $indexes_info[$row['Key_name']]['Cardinality'] = $row['Cardinality'];
4357 // I don't know what does following column mean....
4358 // $indexes_info[$row['Key_name']]['Packed'] = $row['Packed'];
4360 $indexes_info[$row['Key_name']]['Comment'] = $row['Comment'];
4362 $indexes_data[$row['Key_name']][$row['Seq_in_index']]['Column_name']
4363 = $row['Column_name'];
4364 if (isset($row['Sub_part'])) {
4365 $indexes_data[$row['Key_name']][$row['Seq_in_index']]['Sub_part']
4366 = $row['Sub_part'];
4369 } // end while
4371 return array($primary, $pk_array, $indexes_info, $indexes_data);
4375 * Function to get html for the start row and number of rows panel
4377 * @param string $sql_query sql query
4379 * @return string html
4381 public static function getStartAndNumberOfRowsPanel($sql_query)
4383 $pos = isset($_REQUEST['pos'])
4384 ? $_REQUEST['pos']
4385 : $_SESSION['tmpval']['pos'];
4386 if (isset($_REQUEST['session_max_rows'])) {
4387 $rows = $_REQUEST['session_max_rows'];
4388 } else {
4389 if ($_SESSION['tmpval']['max_rows'] != 'all') {
4390 $rows = $_SESSION['tmpval']['max_rows'];
4391 } else {
4392 $rows = $GLOBALS['cfg']['MaxRows'];
4396 return Template::get('startAndNumberOfRowsPanel')
4397 ->render(
4398 array(
4399 'pos' => $pos,
4400 'unlim_num_rows' => intval($_REQUEST['unlim_num_rows']),
4401 'rows' => $rows,
4402 'sql_query' => $sql_query,
4408 * Returns whether the database server supports virtual columns
4410 * @return bool
4412 public static function isVirtualColumnsSupported()
4414 $serverType = self::getServerType();
4415 return $serverType == 'MySQL' && PMA_MYSQL_INT_VERSION >= 50705
4416 || ($serverType == 'MariaDB' && PMA_MYSQL_INT_VERSION >= 50200);
4420 * Returns the proper class clause according to the column type
4422 * @param string $type the column type
4424 * @return string $class_clause the HTML class clause
4426 public static function getClassForType($type)
4428 if ('set' == $type
4429 || 'enum' == $type
4431 $class_clause = '';
4432 } else {
4433 $class_clause = ' class="nowrap"';
4435 return $class_clause;
4439 * Gets the list of tables in the current db and information about these
4440 * tables if possible
4442 * @param string $db database name
4443 * @param string $sub_part part of script name
4445 * @return array
4448 public static function getDbInfo($db, $sub_part)
4450 global $cfg;
4453 * limits for table list
4455 if (! isset($_SESSION['tmpval']['table_limit_offset'])
4456 || $_SESSION['tmpval']['table_limit_offset_db'] != $db
4458 $_SESSION['tmpval']['table_limit_offset'] = 0;
4459 $_SESSION['tmpval']['table_limit_offset_db'] = $db;
4461 if (isset($_REQUEST['pos'])) {
4462 $_SESSION['tmpval']['table_limit_offset'] = (int) $_REQUEST['pos'];
4464 $pos = $_SESSION['tmpval']['table_limit_offset'];
4467 * whether to display extended stats
4469 $is_show_stats = $cfg['ShowStats'];
4472 * whether selected db is information_schema
4474 $db_is_system_schema = false;
4476 if ($GLOBALS['dbi']->isSystemSchema($db)) {
4477 $is_show_stats = false;
4478 $db_is_system_schema = true;
4482 * information about tables in db
4484 $tables = array();
4486 $tooltip_truename = array();
4487 $tooltip_aliasname = array();
4489 // Special speedup for newer MySQL Versions (in 4.0 format changed)
4490 if (true === $cfg['SkipLockedTables']) {
4491 $db_info_result = $GLOBALS['dbi']->query(
4492 'SHOW OPEN TABLES FROM ' . Util::backquote($db) . ' WHERE In_use > 0;'
4495 // Blending out tables in use
4496 if ($db_info_result && $GLOBALS['dbi']->numRows($db_info_result) > 0) {
4497 $tables = self::getTablesWhenOpen($db, $db_info_result);
4499 } elseif ($db_info_result) {
4500 $GLOBALS['dbi']->freeResult($db_info_result);
4504 if (empty($tables)) {
4505 // Set some sorting defaults
4506 $sort = 'Name';
4507 $sort_order = 'ASC';
4509 if (isset($_REQUEST['sort'])) {
4510 $sortable_name_mappings = array(
4511 'table' => 'Name',
4512 'records' => 'Rows',
4513 'type' => 'Engine',
4514 'collation' => 'Collation',
4515 'size' => 'Data_length',
4516 'overhead' => 'Data_free',
4517 'creation' => 'Create_time',
4518 'last_update' => 'Update_time',
4519 'last_check' => 'Check_time',
4520 'comment' => 'Comment',
4523 // Make sure the sort type is implemented
4524 if (isset($sortable_name_mappings[$_REQUEST['sort']])) {
4525 $sort = $sortable_name_mappings[$_REQUEST['sort']];
4526 if ($_REQUEST['sort_order'] == 'DESC') {
4527 $sort_order = 'DESC';
4532 $groupWithSeparator = false;
4533 $tbl_type = null;
4534 $limit_offset = 0;
4535 $limit_count = false;
4536 $groupTable = array();
4538 if (! empty($_REQUEST['tbl_group']) || ! empty($_REQUEST['tbl_type'])) {
4539 if (! empty($_REQUEST['tbl_type'])) {
4540 // only tables for selected type
4541 $tbl_type = $_REQUEST['tbl_type'];
4543 if (! empty($_REQUEST['tbl_group'])) {
4544 // only tables for selected group
4545 $tbl_group = $_REQUEST['tbl_group'];
4546 // include the table with the exact name of the group if such
4547 // exists
4548 $groupTable = $GLOBALS['dbi']->getTablesFull(
4549 $db, $tbl_group, false, null, $limit_offset,
4550 $limit_count, $sort, $sort_order, $tbl_type
4552 $groupWithSeparator = $tbl_group
4553 . $GLOBALS['cfg']['NavigationTreeTableSeparator'];
4555 } else {
4556 // all tables in db
4557 // - get the total number of tables
4558 // (needed for proper working of the MaxTableList feature)
4559 $tables = $GLOBALS['dbi']->getTables($db);
4560 $total_num_tables = count($tables);
4561 if (isset($sub_part) && $sub_part == '_export') {
4562 // (don't fetch only a subset if we are coming from
4563 // db_export.php, because I think it's too risky to display only
4564 // a subset of the table names when exporting a db)
4567 * @todo Page selector for table names?
4569 } else {
4570 // fetch the details for a possible limited subset
4571 $limit_offset = $pos;
4572 $limit_count = true;
4575 $tables = array_merge(
4576 $groupTable,
4577 $GLOBALS['dbi']->getTablesFull(
4578 $db, $groupWithSeparator, ($groupWithSeparator !== false), null,
4579 $limit_offset, $limit_count, $sort, $sort_order, $tbl_type
4584 $num_tables = count($tables);
4585 // (needed for proper working of the MaxTableList feature)
4586 if (! isset($total_num_tables)) {
4587 $total_num_tables = $num_tables;
4591 * If coming from a Show MySQL link on the home page,
4592 * put something in $sub_part
4594 if (empty($sub_part)) {
4595 $sub_part = '_structure';
4598 return array(
4599 $tables,
4600 $num_tables,
4601 $total_num_tables,
4602 $sub_part,
4603 $is_show_stats,
4604 $db_is_system_schema,
4605 $tooltip_truename,
4606 $tooltip_aliasname,
4607 $pos
4612 * Gets the list of tables in the current db, taking into account
4613 * that they might be "in use"
4615 * @param string $db database name
4616 * @param object $db_info_result result set
4618 * @return array $tables list of tables
4621 public static function getTablesWhenOpen($db, $db_info_result)
4623 $sot_cache = $tables = array();
4625 while ($tmp = $GLOBALS['dbi']->fetchAssoc($db_info_result)) {
4626 $sot_cache[$tmp['Table']] = true;
4628 $GLOBALS['dbi']->freeResult($db_info_result);
4630 // is there at least one "in use" table?
4631 if (isset($sot_cache)) {
4632 $tblGroupSql = "";
4633 $whereAdded = false;
4634 if (PMA_isValid($_REQUEST['tbl_group'])) {
4635 $group = Util::escapeMysqlWildcards($_REQUEST['tbl_group']);
4636 $groupWithSeparator = Util::escapeMysqlWildcards(
4637 $_REQUEST['tbl_group']
4638 . $GLOBALS['cfg']['NavigationTreeTableSeparator']
4640 $tblGroupSql .= " WHERE ("
4641 . Util::backquote('Tables_in_' . $db)
4642 . " LIKE '" . $groupWithSeparator . "%'"
4643 . " OR "
4644 . Util::backquote('Tables_in_' . $db)
4645 . " LIKE '" . $group . "')";
4646 $whereAdded = true;
4648 if (PMA_isValid($_REQUEST['tbl_type'], array('table', 'view'))) {
4649 $tblGroupSql .= $whereAdded ? " AND" : " WHERE";
4650 if ($_REQUEST['tbl_type'] == 'view') {
4651 $tblGroupSql .= " `Table_type` != 'BASE TABLE'";
4652 } else {
4653 $tblGroupSql .= " `Table_type` = 'BASE TABLE'";
4656 $db_info_result = $GLOBALS['dbi']->query(
4657 'SHOW FULL TABLES FROM ' . Util::backquote($db) . $tblGroupSql,
4658 null, DatabaseInterface::QUERY_STORE
4660 unset($tblGroupSql, $whereAdded);
4662 if ($db_info_result && $GLOBALS['dbi']->numRows($db_info_result) > 0) {
4663 $names = array();
4664 while ($tmp = $GLOBALS['dbi']->fetchRow($db_info_result)) {
4665 if (! isset($sot_cache[$tmp[0]])) {
4666 $names[] = $tmp[0];
4667 } else { // table in use
4668 $tables[$tmp[0]] = array(
4669 'TABLE_NAME' => $tmp[0],
4670 'ENGINE' => '',
4671 'TABLE_TYPE' => '',
4672 'TABLE_ROWS' => 0,
4673 'TABLE_COMMENT' => '',
4676 } // end while
4677 if (count($names) > 0) {
4678 $tables = array_merge(
4679 $tables,
4680 $GLOBALS['dbi']->getTablesFull($db, $names)
4683 if ($GLOBALS['cfg']['NaturalOrder']) {
4684 uksort($tables, 'strnatcasecmp');
4687 } elseif ($db_info_result) {
4688 $GLOBALS['dbi']->freeResult($db_info_result);
4690 unset($sot_cache);
4692 return $tables;
4696 * Returs list of used PHP extensions.
4698 * @return array of strings
4700 public static function listPHPExtensions()
4702 $result = array();
4703 if (DatabaseInterface::checkDbExtension('mysqli')) {
4704 $result[] = 'mysqli';
4705 } else {
4706 $result[] = 'mysql';
4709 if (extension_loaded('curl')) {
4710 $result[] = 'curl';
4713 if (extension_loaded('mbstring')) {
4714 $result[] = 'mbstring';
4717 return $result;
4721 * Converts given (request) paramter to string
4723 * @param mixed $value Value to convert
4725 * @return string
4727 public static function requestString($value)
4729 while (is_array($value) || is_object($value)) {
4730 $value = reset($value);
4732 return trim((string)$value);
4736 * Creates HTTP request using curl
4738 * @param mixed $response HTTP response
4739 * @param interger $http_status HTTP response status code
4740 * @param bool $return_only_status If set to true, the method would only return response status
4742 * @return mixed
4744 public static function httpRequestReturn($response, $http_status, $return_only_status)
4746 if ($http_status == 404) {
4747 return false;
4749 if ($http_status != 200) {
4750 return null;
4752 if ($return_only_status) {
4753 return true;
4755 return $response;
4759 * Creates HTTP request using curl
4761 * @param string $url Url to send the request
4762 * @param string $method HTTP request method (GET, POST, PUT, DELETE, etc)
4763 * @param bool $return_only_status If set to true, the method would only return response status
4764 * @param mixed $content Content to be sent with HTTP request
4765 * @param string $header Header to be set for the HTTP request
4767 * @return mixed
4769 public static function httpRequestCurl($url, $method, $return_only_status = false, $content = null, $header = "")
4771 $curl_handle = curl_init($url);
4772 if ($curl_handle === false) {
4773 return null;
4775 $curl_handle = Util::configureCurl($curl_handle);
4777 if ($method != "GET") {
4778 curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, $method);
4780 if ($header) {
4781 curl_setopt($curl_handle, CURLOPT_HTTPHEADER, array($header));
4782 curl_setopt($curl_handle, CURLOPT_HEADER, true);
4785 if ($method == "POST") {
4786 curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $content);
4789 curl_setopt($curl_handle, CURLOPT_SSL_VERIFYHOST, '2');
4790 curl_setopt($curl_handle, CURLOPT_SSL_VERIFYPEER, '1');
4792 curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER,true);
4793 curl_setopt($curl_handle, CURLOPT_FOLLOWLOCATION, 0);
4794 curl_setopt($curl_handle, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
4795 curl_setopt($curl_handle, CURLOPT_TIMEOUT, 10);
4796 curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 10);
4797 $response = @curl_exec($curl_handle);
4798 if ($response === false) {
4799 return null;
4801 $http_status = curl_getinfo($curl_handle, CURLINFO_HTTP_CODE);
4802 return Util::httpRequestReturn($response, $http_status, $return_only_status);
4806 * Creates HTTP request using file_get_contents
4808 * @param string $url Url to send the request
4809 * @param string $method HTTP request method (GET, POST, PUT, DELETE, etc)
4810 * @param bool $return_only_status If set to true, the method would only return response status
4811 * @param mixed $content Content to be sent with HTTP request
4812 * @param string $header Header to be set for the HTTP request
4814 * @return mixed
4816 public static function httpRequestFopen($url, $method, $return_only_status = false, $content = null, $header = "")
4818 $context = array(
4819 'http' => array(
4820 'method' => $method,
4821 'request_fulluri' => true,
4822 'timeout' => 10,
4823 'user_agent' => 'phpMyAdmin',
4824 'header' => "Accept: */*",
4827 if ($header) {
4828 $context['http']['header'] .= "\n" . $header;
4830 if ($method == "POST") {
4831 $context['http']['content'] = $content;
4834 $context = Util::handleContext($context);
4835 $response = @file_get_contents(
4836 $url,
4837 false,
4838 stream_context_create($context)
4840 if (! isset($http_response_header)) {
4841 return null;
4843 preg_match("#HTTP/[0-9\.]+\s+([0-9]+)#", $http_response_header[0], $out );
4844 $http_status = intval($out[1]);
4845 return Util::httpRequestReturn($response, $http_status, $return_only_status);
4849 * Creates HTTP request
4851 * @param string $url Url to send the request
4852 * @param string $method HTTP request method (GET, POST, PUT, DELETE, etc)
4853 * @param bool $return_only_status If set to true, the method would only return response status
4854 * @param mixed $content Content to be sent with HTTP request
4855 * @param string $header Header to be set for the HTTP request
4857 * @return mixed
4859 public static function httpRequest($url, $method, $return_only_status = false, $content = null, $header = "")
4861 if (function_exists('curl_init')) {
4862 return Util::httpRequestCurl($url, $method, $return_only_status, $content, $header);
4863 } else if (ini_get('allow_url_fopen')) {
4864 return Util::httpRequestFopen($url, $method, $return_only_status, $content, $header);
4866 return null;