Merge pull request #13681 from mauriciofauth/functions

Refactor some function calls to static method calls
This commit is contained in:
Maurício Meneghini Fauth 2017-09-14 00:07:18 -03:00 committed by GitHub
commit 6f2f10dac5
30 changed files with 2938 additions and 2897 deletions

View File

@ -6,10 +6,10 @@
* @package PhpMyAdmin-Designer
*/
use PhpMyAdmin\Database\Designer;
use PhpMyAdmin\PmdCommon;
use PhpMyAdmin\Response;
require_once 'libraries/common.inc.php';
require_once 'libraries/pmd_common.php';
$response = Response::getInstance();
@ -26,11 +26,11 @@ if (isset($_REQUEST['dialog'])) {
$GLOBALS['db'], $_REQUEST['selected_page']
);
} else if ($_REQUEST['dialog'] == 'add_table') {
$script_display_field = PMA_getTablesInfo();
$script_display_field = PmdCommon::getTablesInfo();
$required = $GLOBALS['db'] . '.' . $GLOBALS['table'];
$tab_column = PMA_getColumnsInfo();
$tables_all_keys = PMA_getAllKeys();
$tables_pk_or_unique_keys = PMA_getPKOrUniqueKeys();
$tab_column = PmdCommon::getColumnsInfo();
$tables_all_keys = PmdCommon::getAllKeys();
$tables_pk_or_unique_keys = PmdCommon::getPkOrUniqueKeys();
$req_key = array_search($required, $GLOBALS['PMD']['TABLE_NAME']);
@ -56,24 +56,24 @@ if (isset($_REQUEST['dialog'])) {
if (isset($_REQUEST['operation'])) {
if ($_REQUEST['operation'] == 'deletePage') {
$success = PMA_deletePage($_REQUEST['selected_page']);
$success = PmdCommon::deletePage($_REQUEST['selected_page']);
$response->setRequestStatus($success);
} elseif ($_REQUEST['operation'] == 'savePage') {
if ($_REQUEST['save_page'] == 'same') {
$page = $_REQUEST['selected_page'];
} else { // new
$page = PMA_createNewPage($_REQUEST['selected_value'], $GLOBALS['db']);
$page = PmdCommon::createNewPage($_REQUEST['selected_value'], $GLOBALS['db']);
$response->addJSON('id', $page);
}
$success = PMA_saveTablePositions($page);
$success = PmdCommon::saveTablePositions($page);
$response->setRequestStatus($success);
} elseif ($_REQUEST['operation'] == 'setDisplayField') {
PMA_saveDisplayField(
PmdCommon::saveDisplayField(
$_REQUEST['db'], $_REQUEST['table'], $_REQUEST['field']
);
$response->setRequestStatus(true);
} elseif ($_REQUEST['operation'] == 'addNewRelation') {
list($success, $message) = PMA_addNewRelation(
list($success, $message) = PmdCommon::addNewRelation(
$_REQUEST['db'],
$_REQUEST['T1'],
$_REQUEST['F1'],
@ -87,7 +87,7 @@ if (isset($_REQUEST['operation'])) {
$response->setRequestStatus($success);
$response->addJSON('message', $message);
} elseif ($_REQUEST['operation'] == 'removeRelation') {
list($success, $message) = PMA_removeRelation(
list($success, $message) = PmdCommon::removeRelation(
$_REQUEST['T1'],
$_REQUEST['F1'],
$_REQUEST['T2'],
@ -96,7 +96,7 @@ if (isset($_REQUEST['operation'])) {
$response->setRequestStatus($success);
$response->addJSON('message', $message);
} elseif ($_REQUEST['operation'] == 'save_setting_value') {
$success = PMA_saveDesignerSetting($_REQUEST['index'], $_REQUEST['value']);
$success = PmdCommon::saveDesignerSetting($_REQUEST['index'], $_REQUEST['value']);
$response->setRequestStatus($success);
}
@ -105,30 +105,30 @@ if (isset($_REQUEST['operation'])) {
require 'libraries/db_common.inc.php';
$script_display_field = PMA_getTablesInfo();
$tab_column = PMA_getColumnsInfo();
$script_tables = PMA_getScriptTabs();
$tables_pk_or_unique_keys = PMA_getPKOrUniqueKeys();
$tables_all_keys = PMA_getAllKeys();
$script_display_field = PmdCommon::getTablesInfo();
$tab_column = PmdCommon::getColumnsInfo();
$script_tables = PmdCommon::getScriptTabs();
$tables_pk_or_unique_keys = PmdCommon::getPkOrUniqueKeys();
$tables_all_keys = PmdCommon::getAllKeys();
$classes_side_menu = Designer::returnClassNamesFromMenuButtons();
$display_page = -1;
$selected_page = null;
if (isset($_REQUEST['query'])) {
$display_page = PMA_getDefaultPage($_REQUEST['db']);
$display_page = PmdCommon::getDefaultPage($_REQUEST['db']);
} else {
if (! empty($_REQUEST['page'])) {
$display_page = $_REQUEST['page'];
} else {
$display_page = PMA_getLoadingPage($_REQUEST['db']);
$display_page = PmdCommon::getLoadingPage($_REQUEST['db']);
}
}
if ($display_page != -1) {
$selected_page = PMA_getPageName($display_page);
$selected_page = PmdCommon::getPageName($display_page);
}
$tab_pos = PMA_getTablePositions($display_page);
$script_contr = PMA_getScriptContr();
$tab_pos = PmdCommon::getTablePositions($display_page);
$script_contr = PmdCommon::getScriptContr();
$params = array('lang' => $GLOBALS['lang']);
if (isset($_GET['db'])) {

View File

@ -7,6 +7,7 @@
*/
use PhpMyAdmin\Config\PageSettings;
use PhpMyAdmin\Response;
use PhpMyAdmin\SqlQueryForm;
/**
*
@ -26,7 +27,6 @@ $scripts->addFile('vendor/jquery/jquery.uitablefilter.js');
$scripts->addFile('sql.js');
require 'libraries/db_common.inc.php';
require_once 'libraries/sql_query_form.lib.php';
// After a syntax error, we return to this script
// with the typed query in the textarea.
@ -37,7 +37,7 @@ $back = 'db_sql.php';
* Query box, bookmark, insert data from textfile
*/
$response->addHTML(
PMA_getHtmlForSqlQueryForm(
SqlQueryForm::getHtml(
true, false,
isset($_REQUEST['delimiter'])
? htmlspecialchars($_REQUEST['delimiter'])

View File

@ -5,11 +5,11 @@
*
* @package PhpMyAdmin
*/
use PhpMyAdmin\ErrorReport;
use PhpMyAdmin\Response;
use PhpMyAdmin\UserPreferences;
require_once 'libraries/common.inc.php';
require_once 'libraries/error_report.lib.php';
if (!isset($_REQUEST['exception_type'])
||!in_array($_REQUEST['exception_type'], array('js', 'php'))
@ -47,10 +47,10 @@ if (isset($_REQUEST['send_error_report'])
);
}
}
$reportData = PMA_getReportData($_REQUEST['exception_type']);
$reportData = ErrorReport::getReportData($_REQUEST['exception_type']);
// report if and only if there were 'actual' errors.
if (count($reportData) > 0) {
$server_response = PMA_sendErrorReport($reportData);
$server_response = ErrorReport::send($reportData);
if ($server_response === false) {
$success = false;
} else {
@ -122,7 +122,7 @@ if (isset($_REQUEST['send_error_report'])
$response->addJSON('report_setting', $GLOBALS['cfg']['SendErrorReports']);
} else {
if ($_REQUEST['exception_type'] == 'js') {
$response->addHTML(PMA_getErrorReportForm());
$response->addHTML(ErrorReport::getForm());
} else {
// clear previous errors & save new ones.
$GLOBALS['error_handler']->savePreviousErrors();

View File

@ -1,12 +1,10 @@
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Holds the PhpMyAdmin\Controllers\Database\DatabaseStructureController
*
* @package PhpMyAdmin\Controllers
*/
namespace PhpMyAdmin\Controllers\Database;
use PhpMyAdmin\Charsets;
@ -17,6 +15,7 @@ use PhpMyAdmin\Display\CreateTable;
use PhpMyAdmin\Message;
use PhpMyAdmin\RecentFavoriteTable;
use PhpMyAdmin\Relation;
use PhpMyAdmin\Replication;
use PhpMyAdmin\Response;
use PhpMyAdmin\Sanitize;
use PhpMyAdmin\Template;
@ -903,10 +902,10 @@ class DatabaseStructureController extends DatabaseController
protected function hasTable($db, $truename)
{
foreach ($db as $db_table) {
if ($this->db == PMA_extractDbOrTable($db_table)
if ($this->db == Replication::extractDbOrTable($db_table)
&& preg_match(
"@^" .
preg_quote(mb_substr(PMA_extractDbOrTable($db_table, 'table'), 0, -1)) . "@",
preg_quote(mb_substr(Replication::extractDbOrTable($db_table, 'table'), 0, -1)) . "@",
$truename
)
) {

View File

@ -0,0 +1,331 @@
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Error reporting functions used to generate and submit error reports
*
* @package PhpMyAdmin
*/
namespace PhpMyAdmin;
use PhpMyAdmin\Relation;
use PhpMyAdmin\Template;
use PhpMyAdmin\Url;
use PhpMyAdmin\Util;
/**
* PhpMyAdmin\ErrorReport class
*
* @package PhpMyAdmin
*/
class ErrorReport
{
/**
* the url where to submit reports to
*/
const SUBMISSION_URL = "https://reports.phpmyadmin.net/incidents/create";
/**
* returns the pretty printed error report data collected from the
* current configuration or from the request parameters sent by the
* error reporting js code.
*
* @return String the report
*/
public static function getPrettyReportData()
{
$report = self::getReportData();
return json_encode($report, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
}
/**
* returns the error report data collected from the current configuration or
* from the request parameters sent by the error reporting js code.
*
* @param string $exception_type whether exception is 'js' or 'php'
*
* @return array error report if success, Empty Array otherwise
*/
public static function getReportData($exception_type = 'js')
{
$relParams = Relation::getRelationsParam();
// common params for both, php & js exceptions
$report = array(
"pma_version" => PMA_VERSION,
"browser_name" => PMA_USR_BROWSER_AGENT,
"browser_version" => PMA_USR_BROWSER_VER,
"user_os" => PMA_USR_OS,
"server_software" => $_SERVER['SERVER_SOFTWARE'],
"user_agent_string" => $_SERVER['HTTP_USER_AGENT'],
"locale" => $_COOKIE['pma_lang'],
"configuration_storage" =>
is_null($relParams['db']) ? "disabled" :
"enabled",
"php_version" => phpversion()
);
if ($exception_type == 'js') {
if (empty($_REQUEST['exception'])) {
return array();
}
$exception = $_REQUEST['exception'];
$exception["stack"] = self::translateStacktrace($exception["stack"]);
List($uri, $script_name) = self::sanitizeUrl($exception["url"]);
$exception["uri"] = $uri;
unset($exception["url"]);
$report ["exception_type"] = 'js';
$report ["exception"] = $exception;
$report ["script_name"] = $script_name;
$report ["microhistory"] = $_REQUEST['microhistory'];
if (! empty($_REQUEST['description'])) {
$report['steps'] = $_REQUEST['description'];
}
} elseif ($exception_type == 'php') {
$errors = array();
// create php error report
$i = 0;
if (!isset($_SESSION['prev_errors'])
|| $_SESSION['prev_errors'] == ''
) {
return array();
}
foreach ($_SESSION['prev_errors'] as $errorObj) {
/* @var $errorObj PhpMyAdmin\Error */
if ($errorObj->getLine()
&& $errorObj->getType()
&& $errorObj->getNumber() != E_USER_WARNING
) {
$errors[$i++] = array(
"lineNum" => $errorObj->getLine(),
"file" => $errorObj->getFile(),
"type" => $errorObj->getType(),
"msg" => $errorObj->getOnlyMessage(),
"stackTrace" => $errorObj->getBacktrace(5),
"stackhash" => $errorObj->getHash()
);
}
}
// if there were no 'actual' errors to be submitted.
if ($i==0) {
return array(); // then return empty array
}
$report ["exception_type"] = 'php';
$report["errors"] = $errors;
} else {
return array();
}
return $report;
}
/**
* Sanitize a url to remove the identifiable host name and extract the
* current script name from the url fragment
*
* It returns two things in an array. The first is the uri without the
* hostname and identifying query params. The second is the name of the
* php script in the url
*
* @param String $url the url to sanitize
*
* @return array the uri and script name
*/
public static function sanitizeUrl($url)
{
$components = parse_url($url);
if (isset($components["fragment"])
&& preg_match("<PMAURL-\d+:>", $components["fragment"], $matches)
) {
$uri = str_replace($matches[0], "", $components["fragment"]);
$url = "https://example.com/" . $uri;
$components = parse_url($url);
}
// get script name
preg_match("<([a-zA-Z\-_\d]*\.php)$>", $components["path"], $matches);
if (count($matches) < 2) {
$script_name = 'index.php';
} else {
$script_name = $matches[1];
}
// remove deployment specific details to make uri more generic
if (isset($components["query"])) {
parse_str($components["query"], $query_array);
unset($query_array["db"]);
unset($query_array["table"]);
unset($query_array["token"]);
unset($query_array["server"]);
$query = http_build_query($query_array);
} else {
$query = '';
}
$uri = $script_name . "?" . $query;
return array($uri, $script_name);
}
/**
* Sends report data to the error reporting server
*
* @param array $report the report info to be sent
*
* @return String the reply of the server
*/
public static function send($report)
{
$response = Util::httpRequest(
self::SUBMISSION_URL,
"POST",
false,
json_encode($report),
"Content-Type: application/json"
);
return $response;
}
/**
* Returns number of lines in given javascript file.
*
* @param string $filename javascript filename
*
* @return Number of lines
*
* @todo Should gracefully handle non existing files
*/
public static function countLines($filename)
{
/**
* The generated file that contains the line numbers for the js files
* If you change any of the js files you can run the scripts/line-counts.sh
*/
if (is_readable('js/line_counts.php')) {
include_once 'js/line_counts.php';
}
global $LINE_COUNT;
if (defined('LINE_COUNTS')) {
return $LINE_COUNT[$filename];
}
// ensure that the file is inside the phpMyAdmin folder
$depath = 1;
foreach (explode('/', $filename) as $part) {
if ($part == '..') {
$depath--;
} elseif ($part != '.' || $part === '') {
$depath++;
}
if ($depath < 0) {
return 0;
}
}
$linecount = 0;
$handle = fopen('./js/' . $filename, 'r');
while (!feof($handle)) {
$line = fgets($handle);
if ($line === false) {
break;
}
$linecount++;
}
fclose($handle);
return $linecount;
}
/**
* returns the translated line number and the file name from the cumulative line
* number and an array of files
*
* uses the $LINE_COUNT global array of file names and line numbers
*
* @param array $filenames list of files in order of concatenation
* @param Integer $cumulative_number the cumulative line number in the
* concatenated files
*
* @return array the filename and line number
* Returns two variables in an array:
* - A String $filename the filename where the requested cumulative number
* exists
* - Integer $linenumber the translated line number in the returned file
*/
public static function getLineNumber($filenames, $cumulative_number)
{
$cumulative_sum = 0;
foreach ($filenames as $filename) {
$filecount = self::countLines($filename);
if ($cumulative_number <= $cumulative_sum + $filecount + 2) {
$linenumber = $cumulative_number - $cumulative_sum;
break;
}
$cumulative_sum += $filecount + 2;
}
if (! isset($filename)) {
$filename = '';
}
return array($filename, $linenumber);
}
/**
* translates the cumulative line numbers in the stack trace as well as sanitize
* urls and trim long lines in the context
*
* @param array $stack the stack trace
*
* @return array $stack the modified stack trace
*/
public static function translateStacktrace($stack)
{
foreach ($stack as &$level) {
foreach ($level["context"] as &$line) {
if (mb_strlen($line) > 80) {
$line = mb_substr($line, 0, 75) . "//...";
}
}
if (preg_match("<js/get_scripts.js.php\?(.*)>", $level["url"], $matches)) {
parse_str($matches[1], $vars);
List($file_name, $line_number) = self::getLineNumber(
$vars["scripts"], $level["line"]
);
$level["filename"] = $file_name;
$level["line"] = $line_number;
} else {
unset($level["context"]);
List($uri, $script_name) = self::sanitizeUrl($level["url"]);
$level["uri"] = $uri;
$level["scriptname"] = $script_name;
}
unset($level["url"]);
}
unset($level);
return $stack;
}
/**
* generates the error report form to collect user description and preview the
* report before being sent
*
* @return String the form
*/
public static function getForm()
{
$datas = array(
'report_data' => self::getPrettyReportData(),
'hidden_inputs' => Url::getHiddenInputs(),
'hidden_fields' => null,
);
$reportData = self::getReportData();
if (!empty($reportData)) {
$datas['hidden_fields'] = Url::getHiddenFields($reportData);
}
return Template::get('error/report_form')
->render($datas);
}
}

View File

@ -0,0 +1,775 @@
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Common functions for Designer
*
* @package PhpMyAdmin-Designer
*/
namespace PhpMyAdmin;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\Index;
use PhpMyAdmin\Relation;
use PhpMyAdmin\Table;
use PhpMyAdmin\Util;
/**
* PhpMyAdmin\PmdCommon class
*
* @package PhpMyAdmin-Designer
*/
class PmdCommon
{
/**
* Retrieves table info and stores it in $GLOBALS['PMD']
*
* @return array with table info
*/
public static function getTablesInfo()
{
$retval = array();
$GLOBALS['PMD']['TABLE_NAME'] = array();// that foreach no error
$GLOBALS['PMD']['OWNER'] = array();
$GLOBALS['PMD']['TABLE_NAME_SMALL'] = array();
$tables = $GLOBALS['dbi']->getTablesFull($GLOBALS['db']);
// seems to be needed later
$GLOBALS['dbi']->selectDb($GLOBALS['db']);
$i = 0;
foreach ($tables as $one_table) {
$GLOBALS['PMD']['TABLE_NAME'][$i]
= $GLOBALS['db'] . "." . $one_table['TABLE_NAME'];
$GLOBALS['PMD']['OWNER'][$i] = $GLOBALS['db'];
$GLOBALS['PMD']['TABLE_NAME_SMALL'][$i] = htmlspecialchars(
$one_table['TABLE_NAME'], ENT_QUOTES
);
$GLOBALS['PMD_URL']['TABLE_NAME'][$i]
= $GLOBALS['db'] . "." . $one_table['TABLE_NAME'];
$GLOBALS['PMD_URL']['OWNER'][$i] = $GLOBALS['db'];
$GLOBALS['PMD_URL']['TABLE_NAME_SMALL'][$i]
= $one_table['TABLE_NAME'];
$GLOBALS['PMD_OUT']['TABLE_NAME'][$i] = htmlspecialchars(
$GLOBALS['db'] . "." . $one_table['TABLE_NAME'], ENT_QUOTES
);
$GLOBALS['PMD_OUT']['OWNER'][$i] = htmlspecialchars(
$GLOBALS['db'], ENT_QUOTES
);
$GLOBALS['PMD_OUT']['TABLE_NAME_SMALL'][$i] = htmlspecialchars(
$one_table['TABLE_NAME'], ENT_QUOTES
);
$GLOBALS['PMD']['TABLE_TYPE'][$i] = mb_strtoupper(
$one_table['ENGINE']
);
$DF = Relation::getDisplayField($GLOBALS['db'], $one_table['TABLE_NAME']);
if ($DF != '') {
$retval[$GLOBALS['PMD_URL']["TABLE_NAME_SMALL"][$i]] = $DF;
}
$i++;
}
return $retval;
}
/**
* Retrieves table column info
*
* @return array table column nfo
*/
public static function getColumnsInfo()
{
$GLOBALS['dbi']->selectDb($GLOBALS['db']);
$tab_column = array();
for ($i = 0, $cnt = count($GLOBALS['PMD']["TABLE_NAME"]); $i < $cnt; $i++) {
$fields_rs = $GLOBALS['dbi']->query(
$GLOBALS['dbi']->getColumnsSql(
$GLOBALS['db'],
$GLOBALS['PMD_URL']["TABLE_NAME_SMALL"][$i],
null,
true
),
null,
DatabaseInterface::QUERY_STORE
);
$tbl_name_i = $GLOBALS['PMD']['TABLE_NAME'][$i];
$j = 0;
while ($row = $GLOBALS['dbi']->fetchAssoc($fields_rs)) {
$tab_column[$tbl_name_i]['COLUMN_ID'][$j] = $j;
$tab_column[$tbl_name_i]['COLUMN_NAME'][$j] = $row['Field'];
$tab_column[$tbl_name_i]['TYPE'][$j] = $row['Type'];
$tab_column[$tbl_name_i]['NULLABLE'][$j] = $row['Null'];
$j++;
}
}
return $tab_column;
}
/**
* Returns JavaScript code for initializing vars
*
* @return string JavaScript code
*/
public static function getScriptContr()
{
$GLOBALS['dbi']->selectDb($GLOBALS['db']);
$con = array();
$con["C_NAME"] = array();
$i = 0;
$alltab_rs = $GLOBALS['dbi']->query(
'SHOW TABLES FROM ' . Util::backquote($GLOBALS['db']),
null,
DatabaseInterface::QUERY_STORE
);
while ($val = @$GLOBALS['dbi']->fetchRow($alltab_rs)) {
$row = Relation::getForeigners($GLOBALS['db'], $val[0], '', 'internal');
if ($row !== false) {
foreach ($row as $field => $value) {
$con['C_NAME'][$i] = '';
$con['DTN'][$i] = urlencode($GLOBALS['db'] . "." . $val[0]);
$con['DCN'][$i] = urlencode($field);
$con['STN'][$i] = urlencode(
$value['foreign_db'] . "." . $value['foreign_table']
);
$con['SCN'][$i] = urlencode($value['foreign_field']);
$i++;
}
}
$row = Relation::getForeigners($GLOBALS['db'], $val[0], '', 'foreign');
if ($row !== false) {
foreach ($row['foreign_keys_data'] as $one_key) {
foreach ($one_key['index_list'] as $index => $one_field) {
$con['C_NAME'][$i] = $one_key['constraint'];
$con['DTN'][$i] = urlencode($GLOBALS['db'] . "." . $val[0]);
$con['DCN'][$i] = urlencode($one_field);
$con['STN'][$i] = urlencode(
(isset($one_key['ref_db_name']) ?
$one_key['ref_db_name'] : $GLOBALS['db'])
. "." . $one_key['ref_table_name']
);
$con['SCN'][$i] = urlencode($one_key['ref_index_list'][$index]);
$i++;
}
}
}
}
$ti = 0;
$retval = array();
for ($i = 0, $cnt = count($con["C_NAME"]); $i < $cnt; $i++) {
$c_name_i = $con['C_NAME'][$i];
$dtn_i = $con['DTN'][$i];
$retval[$ti] = array();
$retval[$ti][$c_name_i] = array();
if (in_array($dtn_i, $GLOBALS['PMD_URL']["TABLE_NAME"])
&& in_array($con['STN'][$i], $GLOBALS['PMD_URL']["TABLE_NAME"])
) {
$retval[$ti][$c_name_i][$dtn_i] = array();
$retval[$ti][$c_name_i][$dtn_i][$con['DCN'][$i]] = array(
0 => $con['STN'][$i],
1 => $con['SCN'][$i]
);
}
$ti++;
}
return $retval;
}
/**
* Returns UNIQUE and PRIMARY indices
*
* @return array unique or primary indices
*/
public static function getPkOrUniqueKeys()
{
return self::getAllKeys(true);
}
/**
* Returns all indices
*
* @param bool $unique_only whether to include only unique ones
*
* @return array indices
*/
public static function getAllKeys($unique_only = false)
{
$keys = array();
foreach ($GLOBALS['PMD']['TABLE_NAME_SMALL'] as $I => $table) {
$schema = $GLOBALS['PMD']['OWNER'][$I];
// for now, take into account only the first index segment
foreach (Index::getFromTable($table, $schema) as $index) {
if ($unique_only && ! $index->isUnique()) {
continue;
}
$columns = $index->getColumns();
foreach ($columns as $column_name => $dummy) {
$keys[$schema . '.' . $table . '.' . $column_name] = 1;
}
}
}
return $keys;
}
/**
* Return script to create j_tab and h_tab arrays
*
* @return string
*/
public static function getScriptTabs()
{
$retval = array(
'j_tabs' => array(),
'h_tabs' => array()
);
for ($i = 0, $cnt = count($GLOBALS['PMD']['TABLE_NAME']); $i < $cnt; $i++) {
$j = 0;
if (Util::isForeignKeySupported($GLOBALS['PMD']['TABLE_TYPE'][$i])) {
$j = 1;
}
$retval['j_tabs'][$GLOBALS['PMD_URL']['TABLE_NAME'][$i]] = $j;
$retval['h_tabs'][$GLOBALS['PMD_URL']['TABLE_NAME'][$i]] = 1;
}
return $retval;
}
/**
* Returns table positions of a given pdf page
*
* @param int $pg pdf page id
*
* @return array of table positions
*/
public static function getTablePositions($pg)
{
$cfgRelation = Relation::getRelationsParam();
if (! $cfgRelation['pdfwork']) {
return null;
}
$query = "
SELECT CONCAT_WS('.', `db_name`, `table_name`) AS `name`,
`x` AS `X`,
`y` AS `Y`,
1 AS `V`,
1 AS `H`
FROM " . Util::backquote($cfgRelation['db'])
. "." . Util::backquote($cfgRelation['table_coords']) . "
WHERE pdf_page_number = " . intval($pg);
$tab_pos = $GLOBALS['dbi']->fetchResult(
$query,
'name',
null,
$GLOBALS['controllink'],
DatabaseInterface::QUERY_STORE
);
return $tab_pos;
}
/**
* Returns page name of a given pdf page
*
* @param int $pg pdf page id
*
* @return String table name
*/
public static function getPageName($pg)
{
$cfgRelation = Relation::getRelationsParam();
if (! $cfgRelation['pdfwork']) {
return null;
}
$query = "SELECT `page_descr`"
. " FROM " . Util::backquote($cfgRelation['db'])
. "." . Util::backquote($cfgRelation['pdf_pages'])
. " WHERE " . Util::backquote('page_nr') . " = " . intval($pg);
$page_name = $GLOBALS['dbi']->fetchResult(
$query,
null,
null,
$GLOBALS['controllink'],
DatabaseInterface::QUERY_STORE
);
return count($page_name) ? $page_name[0] : null;
}
/**
* Deletes a given pdf page and its corresponding coordinates
*
* @param int $pg page id
*
* @return boolean success/failure
*/
public static function deletePage($pg)
{
$cfgRelation = Relation::getRelationsParam();
if (! $cfgRelation['pdfwork']) {
return false;
}
$query = "DELETE FROM " . Util::backquote($cfgRelation['db'])
. "." . Util::backquote($cfgRelation['table_coords'])
. " WHERE " . Util::backquote('pdf_page_number') . " = " . intval($pg);
$success = Relation::queryAsControlUser(
$query, true, DatabaseInterface::QUERY_STORE
);
if ($success) {
$query = "DELETE FROM " . Util::backquote($cfgRelation['db'])
. "." . Util::backquote($cfgRelation['pdf_pages'])
. " WHERE " . Util::backquote('page_nr') . " = " . intval($pg);
$success = Relation::queryAsControlUser(
$query, true, DatabaseInterface::QUERY_STORE
);
}
return (boolean) $success;
}
/**
* Returns the id of the default pdf page of the database.
* Default page is the one which has the same name as the database.
*
* @param string $db database
*
* @return int id of the default pdf page for the database
*/
public static function getDefaultPage($db)
{
$cfgRelation = Relation::getRelationsParam();
if (! $cfgRelation['pdfwork']) {
return null;
}
$query = "SELECT `page_nr`"
. " FROM " . Util::backquote($cfgRelation['db'])
. "." . Util::backquote($cfgRelation['pdf_pages'])
. " WHERE `db_name` = '" . $GLOBALS['dbi']->escapeString($db) . "'"
. " AND `page_descr` = '" . $GLOBALS['dbi']->escapeString($db) . "'";
$default_page_no = $GLOBALS['dbi']->fetchResult(
$query,
null,
null,
$GLOBALS['controllink'],
DatabaseInterface::QUERY_STORE
);
if (count($default_page_no)) {
return intval($default_page_no[0]);
}
return -1;
}
/**
* Get the id of the page to load. If a default page exists it will be returned.
* If no such exists, returns the id of the first page of the database.
*
* @param string $db database
*
* @return int id of the page to load
*/
public static function getLoadingPage($db)
{
$cfgRelation = Relation::getRelationsParam();
if (! $cfgRelation['pdfwork']) {
return null;
}
$page_no = -1;
$default_page_no = self::getDefaultPage($db);
if ($default_page_no != -1) {
$page_no = $default_page_no;
} else {
$query = "SELECT MIN(`page_nr`)"
. " FROM " . Util::backquote($cfgRelation['db'])
. "." . Util::backquote($cfgRelation['pdf_pages'])
. " WHERE `db_name` = '" . $GLOBALS['dbi']->escapeString($db) . "'";
$min_page_no = $GLOBALS['dbi']->fetchResult(
$query,
null,
null,
$GLOBALS['controllink'],
DatabaseInterface::QUERY_STORE
);
if (count($min_page_no[0])) {
$page_no = $min_page_no[0];
}
}
return intval($page_no);
}
/**
* Creates a new page and returns its auto-incrementing id
*
* @param string $pageName name of the page
* @param string $db name of the database
*
* @return int|null
*/
public static function createNewPage($pageName, $db)
{
$cfgRelation = Relation::getRelationsParam();
if ($cfgRelation['pdfwork']) {
$pageNumber = Relation::createPage(
$pageName,
$cfgRelation,
$db
);
return $pageNumber;
}
return null;
}
/**
* Saves positions of table(s) of a given pdf page
*
* @param int $pg pdf page id
*
* @return boolean success/failure
*/
public static function saveTablePositions($pg)
{
$cfgRelation = Relation::getRelationsParam();
if (! $cfgRelation['pdfwork']) {
return false;
}
$query = "DELETE FROM "
. Util::backquote($GLOBALS['cfgRelation']['db'])
. "." . Util::backquote(
$GLOBALS['cfgRelation']['table_coords']
)
. " WHERE `db_name` = '" . $GLOBALS['dbi']->escapeString($_REQUEST['db'])
. "'"
. " AND `pdf_page_number` = '" . $GLOBALS['dbi']->escapeString($pg)
. "'";
$res = Relation::queryAsControlUser(
$query,
true,
DatabaseInterface::QUERY_STORE
);
if (!$res) {
return (boolean)$res;
}
foreach ($_REQUEST['t_h'] as $key => $value) {
list($DB, $TAB) = explode(".", $key);
if (!$value) {
continue;
}
$query = "INSERT INTO "
. Util::backquote($GLOBALS['cfgRelation']['db']) . "."
. Util::backquote($GLOBALS['cfgRelation']['table_coords'])
. " (`db_name`, `table_name`, `pdf_page_number`, `x`, `y`)"
. " VALUES ("
. "'" . $GLOBALS['dbi']->escapeString($DB) . "', "
. "'" . $GLOBALS['dbi']->escapeString($TAB) . "', "
. "'" . $GLOBALS['dbi']->escapeString($pg) . "', "
. "'" . $GLOBALS['dbi']->escapeString($_REQUEST['t_x'][$key]) . "', "
. "'" . $GLOBALS['dbi']->escapeString($_REQUEST['t_y'][$key]) . "')";
$res = Relation::queryAsControlUser(
$query, true, DatabaseInterface::QUERY_STORE
);
}
return (boolean) $res;
}
/**
* Saves the display field for a table.
*
* @param string $db database name
* @param string $table table name
* @param string $field display field name
*
* @return boolean
*/
public static function saveDisplayField($db, $table, $field)
{
$cfgRelation = Relation::getRelationsParam();
if (!$cfgRelation['displaywork']) {
return false;
}
$upd_query = new Table($table, $db, $GLOBALS['dbi']);
$upd_query->updateDisplayField($field, $cfgRelation);
return true;
}
/**
* Adds a new foreign relation
*
* @param string $db database name
* @param string $T1 foreign table
* @param string $F1 foreign field
* @param string $T2 master table
* @param string $F2 master field
* @param string $on_delete on delete action
* @param string $on_update on update action
*
* @return array array of success/failure and message
*/
public static function addNewRelation($db, $T1, $F1, $T2, $F2, $on_delete, $on_update, $DB1, $DB2)
{
$tables = $GLOBALS['dbi']->getTablesFull($DB1, $T1);
$type_T1 = mb_strtoupper($tables[$T1]['ENGINE']);
$tables = $GLOBALS['dbi']->getTablesFull($DB2, $T2);
$type_T2 = mb_strtoupper($tables[$T2]['ENGINE']);
// native foreign key
if (Util::isForeignKeySupported($type_T1)
&& Util::isForeignKeySupported($type_T2)
&& $type_T1 == $type_T2
) {
// relation exists?
$existrel_foreign = Relation::getForeigners($DB2, $T2, '', 'foreign');
$foreigner = Relation::searchColumnInForeigners($existrel_foreign, $F2);
if ($foreigner
&& isset($foreigner['constraint'])
) {
return array(false, __('Error: relationship already exists.'));
}
// note: in InnoDB, the index does not requires to be on a PRIMARY
// or UNIQUE key
// improve: check all other requirements for InnoDB relations
$result = $GLOBALS['dbi']->query(
'SHOW INDEX FROM ' . Util::backquote($DB1)
. '.' . Util::backquote($T1) . ';'
);
// will be use to emphasis prim. keys in the table view
$index_array1 = array();
while ($row = $GLOBALS['dbi']->fetchAssoc($result)) {
$index_array1[$row['Column_name']] = 1;
}
$GLOBALS['dbi']->freeResult($result);
$result = $GLOBALS['dbi']->query(
'SHOW INDEX FROM ' . Util::backquote($DB2)
. '.' . Util::backquote($T2) . ';'
);
// will be used to emphasis prim. keys in the table view
$index_array2 = array();
while ($row = $GLOBALS['dbi']->fetchAssoc($result)) {
$index_array2[$row['Column_name']] = 1;
}
$GLOBALS['dbi']->freeResult($result);
if (! empty($index_array1[$F1]) && ! empty($index_array2[$F2])) {
$upd_query = 'ALTER TABLE ' . Util::backquote($DB2)
. '.' . Util::backquote($T2)
. ' ADD FOREIGN KEY ('
. Util::backquote($F2) . ')'
. ' REFERENCES '
. Util::backquote($DB1) . '.'
. Util::backquote($T1) . '('
. Util::backquote($F1) . ')';
if ($on_delete != 'nix') {
$upd_query .= ' ON DELETE ' . $on_delete;
}
if ($on_update != 'nix') {
$upd_query .= ' ON UPDATE ' . $on_update;
}
$upd_query .= ';';
if ($GLOBALS['dbi']->tryQuery($upd_query)) {
return array(true, __('FOREIGN KEY relationship has been added.'));
}
$error = $GLOBALS['dbi']->getError();
return array(
false,
__('Error: FOREIGN KEY relationship could not be added!')
. "<br/>" . $error
);
}
return array(false, __('Error: Missing index on column(s).'));
}
// internal (pmadb) relation
if ($GLOBALS['cfgRelation']['relwork'] == false) {
return array(false, __('Error: Relational features are disabled!'));
}
// no need to recheck if the keys are primary or unique at this point,
// this was checked on the interface part
$q = "INSERT INTO "
. Util::backquote($GLOBALS['cfgRelation']['db'])
. "."
. Util::backquote($GLOBALS['cfgRelation']['relation'])
. "(master_db, master_table, master_field, "
. "foreign_db, foreign_table, foreign_field)"
. " values("
. "'" . $GLOBALS['dbi']->escapeString($DB2) . "', "
. "'" . $GLOBALS['dbi']->escapeString($T2) . "', "
. "'" . $GLOBALS['dbi']->escapeString($F2) . "', "
. "'" . $GLOBALS['dbi']->escapeString($DB1) . "', "
. "'" . $GLOBALS['dbi']->escapeString($T1) . "', "
. "'" . $GLOBALS['dbi']->escapeString($F1) . "')";
if (Relation::queryAsControlUser($q, false, DatabaseInterface::QUERY_STORE)
) {
return array(true, __('Internal relationship has been added.'));
}
$error = $GLOBALS['dbi']->getError($GLOBALS['controllink']);
return array(
false,
__('Error: Internal relationship could not be added!')
. "<br/>" . $error
);
}
/**
* Removes a foreign relation
*
* @param string $T1 foreign db.table
* @param string $F1 foreign field
* @param string $T2 master db.table
* @param string $F2 master field
*
* @return array array of success/failure and message
*/
public static function removeRelation($T1, $F1, $T2, $F2)
{
list($DB1, $T1) = explode(".", $T1);
list($DB2, $T2) = explode(".", $T2);
$tables = $GLOBALS['dbi']->getTablesFull($DB1, $T1);
$type_T1 = mb_strtoupper($tables[$T1]['ENGINE']);
$tables = $GLOBALS['dbi']->getTablesFull($DB2, $T2);
$type_T2 = mb_strtoupper($tables[$T2]['ENGINE']);
if (Util::isForeignKeySupported($type_T1)
&& Util::isForeignKeySupported($type_T2)
&& $type_T1 == $type_T2
) {
// InnoDB
$existrel_foreign = Relation::getForeigners($DB2, $T2, '', 'foreign');
$foreigner = Relation::searchColumnInForeigners($existrel_foreign, $F2);
if (isset($foreigner['constraint'])) {
$upd_query = 'ALTER TABLE ' . Util::backquote($DB2)
. '.' . Util::backquote($T2) . ' DROP FOREIGN KEY '
. Util::backquote($foreigner['constraint']) . ';';
if ($GLOBALS['dbi']->query($upd_query)) {
return array(true, __('FOREIGN KEY relationship has been removed.'));
}
$error = $GLOBALS['dbi']->getError();
return array(
false,
__('Error: FOREIGN KEY relationship could not be removed!')
. "<br/>" . $error
);
}
}
// internal relations
$delete_query = "DELETE FROM "
. Util::backquote($GLOBALS['cfgRelation']['db']) . "."
. $GLOBALS['cfgRelation']['relation'] . " WHERE "
. "master_db = '" . $GLOBALS['dbi']->escapeString($DB2) . "'"
. " AND master_table = '" . $GLOBALS['dbi']->escapeString($T2) . "'"
. " AND master_field = '" . $GLOBALS['dbi']->escapeString($F2) . "'"
. " AND foreign_db = '" . $GLOBALS['dbi']->escapeString($DB1) . "'"
. " AND foreign_table = '" . $GLOBALS['dbi']->escapeString($T1) . "'"
. " AND foreign_field = '" . $GLOBALS['dbi']->escapeString($F1) . "'";
$result = Relation::queryAsControlUser(
$delete_query,
false,
DatabaseInterface::QUERY_STORE
);
if (!$result) {
$error = $GLOBALS['dbi']->getError($GLOBALS['controllink']);
return array(
false,
__('Error: Internal relationship could not be removed!') . "<br/>" . $error
);
}
return array(true, __('Internal relationship has been removed.'));
}
/**
* Save value for a designer setting
*
* @param string $index setting
* @param string $value value
*
* @return bool whether the operation succeeded
*/
public static function saveDesignerSetting($index, $value)
{
$cfgRelation = Relation::getRelationsParam();
$cfgDesigner = array(
'user' => $GLOBALS['cfg']['Server']['user'],
'db' => $cfgRelation['db'],
'table' => $cfgRelation['designer_settings']
);
$success = true;
if ($GLOBALS['cfgRelation']['designersettingswork']) {
$orig_data_query = "SELECT settings_data"
. " FROM " . Util::backquote($cfgDesigner['db'])
. "." . Util::backquote($cfgDesigner['table'])
. " WHERE username = '"
. $GLOBALS['dbi']->escapeString($cfgDesigner['user']) . "';";
$orig_data = $GLOBALS['dbi']->fetchSingleRow(
$orig_data_query, 'ASSOC', $GLOBALS['controllink']
);
if (! empty($orig_data)) {
$orig_data = json_decode($orig_data['settings_data'], true);
$orig_data[$index] = $value;
$orig_data = json_encode($orig_data);
$save_query = "UPDATE "
. Util::backquote($cfgDesigner['db'])
. "." . Util::backquote($cfgDesigner['table'])
. " SET settings_data = '" . $orig_data . "'"
. " WHERE username = '"
. $GLOBALS['dbi']->escapeString($cfgDesigner['user']) . "';";
$success = Relation::queryAsControlUser($save_query);
} else {
$save_data = array($index => $value);
$query = "INSERT INTO "
. Util::backquote($cfgDesigner['db'])
. "." . Util::backquote($cfgDesigner['table'])
. " (username, settings_data)"
. " VALUES('" . $cfgDesigner['user'] . "',"
. " '" . json_encode($save_data) . "');";
$success = Relation::queryAsControlUser($query);
}
}
return (bool) $success;
}
}

View File

@ -0,0 +1,173 @@
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Replication helpers
*
* @package PhpMyAdmin
*/
namespace PhpMyAdmin;
use PhpMyAdmin\Core;
use PhpMyAdmin\DatabaseInterface;
/**
* PhpMyAdmin\Replication class
*
* @package PhpMyAdmin
*/
class Replication
{
/**
* Fill global replication_info variable.
*
* @param string $type Type: master, slave
* @param string $replicationInfoKey Key in replication_info variable
* @param array $mysqlInfo MySQL data about replication
* @param string $mysqlKey MySQL key
*
* @return array
*/
public static function fillInfo(
$type, $replicationInfoKey, $mysqlInfo, $mysqlKey
) {
$GLOBALS['replication_info'][$type][$replicationInfoKey]
= empty($mysqlInfo[$mysqlKey])
? array()
: explode(
",",
$mysqlInfo[$mysqlKey]
);
return $GLOBALS['replication_info'][$type][$replicationInfoKey];
}
/**
* Extracts database or table name from string
*
* @param string $string contains "dbname.tablename"
* @param string $what what to extract (db|table)
*
* @return string the extracted part
*/
public static function extractDbOrTable($string, $what = 'db')
{
$list = explode(".", $string);
if ('db' == $what) {
return $list[0];
} else {
return $list[1];
}
}
/**
* Configures replication slave
*
* @param string $action possible values: START or STOP
* @param string $control default: null,
* possible values: SQL_THREAD or IO_THREAD or null.
* If it is set to null, it controls both
* SQL_THREAD and IO_THREAD
* @param mixed $link mysql link
*
* @return mixed output of DatabaseInterface::tryQuery
*/
public static function slaveControl($action, $control = null, $link = null)
{
$action = mb_strtoupper($action);
$control = mb_strtoupper($control);
if ($action != "START" && $action != "STOP") {
return -1;
}
if ($control != "SQL_THREAD" && $control != "IO_THREAD" && $control != null) {
return -1;
}
return $GLOBALS['dbi']->tryQuery($action . " SLAVE " . $control . ";", $link);
}
/**
* Changes master for replication slave
*
* @param string $user replication user on master
* @param string $password password for the user
* @param string $host master's hostname or IP
* @param int $port port, where mysql is running
* @param array $pos position of mysql replication,
* array should contain fields File and Position
* @param bool $stop shall we stop slave?
* @param bool $start shall we start slave?
* @param mixed $link mysql link
*
* @return string output of CHANGE MASTER mysql command
*/
public static function slaveChangeMaster($user, $password, $host, $port,
$pos, $stop = true, $start = true, $link = null
) {
if ($stop) {
self::slaveControl("STOP", null, $link);
}
$out = $GLOBALS['dbi']->tryQuery(
'CHANGE MASTER TO ' .
'MASTER_HOST=\'' . $host . '\',' .
'MASTER_PORT=' . ($port * 1) . ',' .
'MASTER_USER=\'' . $user . '\',' .
'MASTER_PASSWORD=\'' . $password . '\',' .
'MASTER_LOG_FILE=\'' . $pos["File"] . '\',' .
'MASTER_LOG_POS=' . $pos["Position"] . ';', $link
);
if ($start) {
self::slaveControl("START", null, $link);
}
return $out;
}
/**
* This function provides connection to remote mysql server
*
* @param string $user mysql username
* @param string $password password for the user
* @param string $host mysql server's hostname or IP
* @param int $port mysql remote port
* @param string $socket path to unix socket
*
* @return mixed $link mysql link on success
*/
public static function connectToMaster(
$user, $password, $host = null, $port = null, $socket = null
) {
$server = array();
$server['user'] = $user;
$server['password'] = $password;
$server["host"] = Core::sanitizeMySQLHost($host);
$server["port"] = $port;
$server["socket"] = $socket;
// 5th parameter set to true means that it's an auxiliary connection
// and we must not go back to login page if it fails
return $GLOBALS['dbi']->connect(DatabaseInterface::CONNECT_AUXILIARY, $server);
}
/**
* Fetches position and file of current binary log on master
*
* @param mixed $link mysql link
*
* @return array an array containing File and Position in MySQL replication
* on master server, useful for self::slaveChangeMaster
*/
public static function slaveBinLogMaster($link = null)
{
$data = $GLOBALS['dbi']->fetchResult('SHOW MASTER STATUS', null, null, $link);
$output = array();
if (! empty($data)) {
$output["File"] = $data[0]["File"];
$output["Position"] = $data[0]["Position"];
}
return $output;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -9,6 +9,7 @@
*/
namespace PhpMyAdmin\Server;
use PhpMyAdmin\ReplicationGui;
use PhpMyAdmin\Server\Status\Data;
use PhpMyAdmin\Util;
@ -126,7 +127,7 @@ class Status
if (isset($GLOBALS['replication_info'][$type]['status'])
&& $GLOBALS['replication_info'][$type]['status']
) {
$retval .= PMA_getHtmlForReplicationStatusTable($type);
$retval .= ReplicationGui::getHtmlForReplicationStatusTable($type);
}
}

View File

@ -1371,7 +1371,7 @@ EOT;
$message = Message::getMessageForAffectedRows($num_rows);
// Ok, here is an explanation for the !$is_select.
// The form generated by sql_query_form.lib.php
// The form generated by PhpMyAdmin\SqlQueryForm
// and db_sql.php has many submit buttons
// on the same form, and some confusion arises from the
// fact that $message_to_show is sent for every case.

View File

@ -0,0 +1,442 @@
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* functions for displaying the sql query form
*
* @usedby server_sql.php
* @usedby db_sql.php
* @usedby tbl_sql.php
* @usedby tbl_structure.php
* @usedby tbl_tracking.php
* @package PhpMyAdmin
*/
namespace PhpMyAdmin;
use PhpMyAdmin\Bookmark;
use PhpMyAdmin\Encoding;
use PhpMyAdmin\Url;
use PhpMyAdmin\Util;
/**
* PhpMyAdmin\SqlQueryForm class
*
* @package PhpMyAdmin
*/
class SqlQueryForm
{
/**
* return HTML for the sql query boxes
*
* @param boolean|string $query query to display in the textarea
* or true to display last executed
* @param boolean|string $display_tab sql|full|false
* what part to display
* false if not inside querywindow
* @param string $delimiter delimiter
*
* @return string
*
* @usedby server_sql.php
* @usedby db_sql.php
* @usedby tbl_sql.php
* @usedby tbl_structure.php
* @usedby tbl_tracking.php
*/
public static function getHtml(
$query = true, $display_tab = false, $delimiter = ';'
) {
$html = '';
if (! $display_tab) {
$display_tab = 'full';
}
// query to show
if (true === $query) {
$query = $GLOBALS['sql_query'];
}
// set enctype to multipart for file uploads
if ($GLOBALS['is_upload']) {
$enctype = ' enctype="multipart/form-data"';
} else {
$enctype = '';
}
$table = '';
$db = '';
if (strlen($GLOBALS['db']) === 0) {
// prepare for server related
$goto = empty($GLOBALS['goto']) ?
'server_sql.php' : $GLOBALS['goto'];
} elseif (strlen($GLOBALS['table']) === 0) {
// prepare for db related
$db = $GLOBALS['db'];
$goto = empty($GLOBALS['goto']) ?
'db_sql.php' : $GLOBALS['goto'];
} else {
$table = $GLOBALS['table'];
$db = $GLOBALS['db'];
$goto = empty($GLOBALS['goto']) ?
'tbl_sql.php' : $GLOBALS['goto'];
}
// start output
$html .= '<form method="post" action="import.php" ' . $enctype;
$html .= ' class="ajax lock-page"';
$html .= ' id="sqlqueryform" name="sqlform">' . "\n";
$html .= '<input type="hidden" name="is_js_confirmed" value="0" />'
. "\n" . Url::getHiddenInputs($db, $table) . "\n"
. '<input type="hidden" name="pos" value="0" />' . "\n"
. '<input type="hidden" name="goto" value="'
. htmlspecialchars($goto) . '" />' . "\n"
. '<input type="hidden" name="message_to_show" value="'
. __('Your SQL query has been executed successfully.') . '" />'
. "\n" . '<input type="hidden" name="prev_sql_query" value="'
. htmlspecialchars($query) . '" />' . "\n";
// display querybox
if ($display_tab === 'full' || $display_tab === 'sql') {
$html .= self::getHtmlForInsert(
$query, $delimiter
);
}
// Bookmark Support
if ($display_tab === 'full') {
$cfgBookmark = Bookmark::getParams();
if ($cfgBookmark) {
$html .= self::getHtmlForBookmark();
}
}
// Japanese encoding setting
if (Encoding::canConvertKanji()) {
$html .= Encoding::kanjiEncodingForm();
}
$html .= '</form>' . "\n";
// print an empty div, which will be later filled with
// the sql query results by ajax
$html .= '<div id="sqlqueryresultsouter"></div>';
return $html;
}
/**
* Get initial values for Sql Query Form Insert
*
* @param string $query query to display in the textarea
*
* @return array ($legend, $query, $columns_list)
*
* @usedby self::getHtmlForInsert()
*/
public static function init($query)
{
$columns_list = array();
if (strlen($GLOBALS['db']) === 0) {
// prepare for server related
$legend = sprintf(
__('Run SQL query/queries on server “%s”'),
htmlspecialchars(
! empty($GLOBALS['cfg']['Servers'][$GLOBALS['server']]['verbose'])
? $GLOBALS['cfg']['Servers'][$GLOBALS['server']]['verbose']
: $GLOBALS['cfg']['Servers'][$GLOBALS['server']]['host']
)
);
} elseif (strlen($GLOBALS['table']) === 0) {
// prepare for db related
$db = $GLOBALS['db'];
// if you want navigation:
$tmp_db_link = '<a href="' . Util::getScriptNameForOption(
$GLOBALS['cfg']['DefaultTabDatabase'], 'database'
)
. Url::getCommon(array('db' => $db)) . '"';
$tmp_db_link .= '>'
. htmlspecialchars($db) . '</a>';
$legend = sprintf(__('Run SQL query/queries on database %s'), $tmp_db_link);
if (empty($query)) {
$query = Util::expandUserString(
$GLOBALS['cfg']['DefaultQueryDatabase'], 'backquote'
);
}
} else {
$db = $GLOBALS['db'];
$table = $GLOBALS['table'];
// Get the list and number of fields
// we do a try_query here, because we could be in the query window,
// trying to synchronize and the table has not yet been created
$columns_list = $GLOBALS['dbi']->getColumns(
$db, $GLOBALS['table'], null, true
);
$tmp_tbl_link = '<a href="' . Util::getScriptNameForOption(
$GLOBALS['cfg']['DefaultTabTable'], 'table'
) . Url::getCommon(array('db' => $db, 'table' => $table)) . '" >';
$tmp_tbl_link .= htmlspecialchars($db)
. '.' . htmlspecialchars($table) . '</a>';
$legend = sprintf(__('Run SQL query/queries on table %s'), $tmp_tbl_link);
if (empty($query)) {
$query = Util::expandUserString(
$GLOBALS['cfg']['DefaultQueryTable'], 'backquote'
);
}
}
$legend .= ': ' . Util::showMySQLDocu('SELECT');
return array($legend, $query, $columns_list);
}
/**
* return HTML for Sql Query Form Insert
*
* @param string $query query to display in the textarea
* @param string $delimiter default delimiter to use
*
* @return string
*
* @usedby self::getHtml()
*/
public static function getHtmlForInsert(
$query = '', $delimiter = ';'
) {
// enable auto select text in textarea
if ($GLOBALS['cfg']['TextareaAutoSelect']) {
$auto_sel = ' onclick="selectContent(this, sql_box_locked, true);"';
} else {
$auto_sel = '';
}
$locking = '';
$height = $GLOBALS['cfg']['TextareaRows'] * 2;
list($legend, $query, $columns_list) = self::init($query);
if (! empty($columns_list)) {
$sqlquerycontainer_id = 'sqlquerycontainer';
} else {
$sqlquerycontainer_id = 'sqlquerycontainerfull';
}
$html = '<a id="querybox"></a>'
. '<div id="queryboxcontainer">'
. '<fieldset id="queryboxf">';
$html .= '<legend>' . $legend . '</legend>';
$html .= '<div id="queryfieldscontainer">';
$html .= '<div id="' . $sqlquerycontainer_id . '">'
. '<textarea tabindex="100" name="sql_query" id="sqlquery"'
. ' cols="' . $GLOBALS['cfg']['TextareaCols'] . '"'
. ' rows="' . $height . '"'
. $auto_sel . $locking . '>'
. htmlspecialchars($query)
. '</textarea>';
$html .= '<div id="querymessage"></div>';
// Add buttons to generate query easily for
// select all, single select, insert, update and delete
if (! empty($columns_list)) {
$html .= '<input type="button" value="SELECT *" id="selectall"'
. ' class="button sqlbutton" />';
$html .= '<input type="button" value="SELECT" id="select"'
. ' class="button sqlbutton" />';
$html .= '<input type="button" value="INSERT" id="insert"'
. ' class="button sqlbutton" />';
$html .= '<input type="button" value="UPDATE" id="update"'
. ' class="button sqlbutton" />';
$html .= '<input type="button" value="DELETE" id="delete"'
. ' class="button sqlbutton" />';
}
$html .= '<input type="button" value="' . __('Clear') . '" id="clear"'
. ' class="button sqlbutton" />';
if ($GLOBALS['cfg']['CodemirrorEnable']) {
$html .= '<input type="button" value="' . __('Format') . '" id="format"'
. ' class="button sqlbutton" />';
}
$html .= '<input type="button" value="' . __('Get auto-saved query')
. '" id="saved" class="button sqlbutton" />';
// parameter binding
$html .= '<div>';
$html .= '<input type="checkbox" name="parameterized" id="parameterized" />';
$html .= '<label for="parameterized">' . __('Bind parameters') . '</label>';
$html .= Util::showDocu('faq', 'faq6-40');
$html .= '<div id="parametersDiv"></div>';
$html .= '</div>';
$html .= '</div>' . "\n";
if (! empty($columns_list)) {
$html .= '<div id="tablefieldscontainer">'
. '<label>' . __('Columns') . '</label>'
. '<select id="tablefields" name="dummy" '
. 'size="' . ($GLOBALS['cfg']['TextareaRows'] - 2) . '" '
. 'multiple="multiple" ondblclick="insertValueQuery()">';
foreach ($columns_list as $field) {
$html .= '<option value="'
. Util::backquote(htmlspecialchars($field['Field']))
. '"';
if (isset($field['Field'])
&& strlen($field['Field']) > 0
&& isset($field['Comment'])
) {
$html .= ' title="' . htmlspecialchars($field['Comment']) . '"';
}
$html .= '>' . htmlspecialchars($field['Field']) . '</option>' . "\n";
}
$html .= '</select>'
. '<div id="tablefieldinsertbuttoncontainer">';
if (Util::showIcons('ActionLinksMode')) {
$html .= '<input type="button" class="button" name="insert"'
. ' value="&lt;&lt;" onclick="insertValueQuery()"'
. ' title="' . __('Insert') . '" />';
} else {
$html .= '<input type="button" class="button" name="insert"'
. ' value="' . __('Insert') . '"'
. ' onclick="insertValueQuery()" />';
}
$html .= '</div>' . "\n"
. '</div>' . "\n";
}
$html .= '<div class="clearfloat"></div>' . "\n";
$html .= '</div>' . "\n";
$cfgBookmark = Bookmark::getParams();
if ($cfgBookmark) {
$html .= '<div id="bookmarkoptions">';
$html .= '<div class="formelement">';
$html .= '<label for="bkm_label">'
. __('Bookmark this SQL query:') . '</label>';
$html .= '<input type="text" name="bkm_label" id="bkm_label"'
. ' tabindex="110" value="" />';
$html .= '</div>';
$html .= '<div class="formelement">';
$html .= '<input type="checkbox" name="bkm_all_users" tabindex="111"'
. ' id="id_bkm_all_users" value="true" />';
$html .= '<label for="id_bkm_all_users">'
. __('Let every user access this bookmark') . '</label>';
$html .= '</div>';
$html .= '<div class="formelement">';
$html .= '<input type="checkbox" name="bkm_replace" tabindex="112"'
. ' id="id_bkm_replace" value="true" />';
$html .= '<label for="id_bkm_replace">'
. __('Replace existing bookmark of same name') . '</label>';
$html .= '</div>';
$html .= '</div>';
}
$html .= '<div class="clearfloat"></div>' . "\n";
$html .= '</fieldset>' . "\n"
. '</div>' . "\n";
$html .= '<fieldset id="queryboxfooter" class="tblFooters">' . "\n";
$html .= '<div class="formelement">' . "\n";
$html .= '</div>' . "\n";
$html .= '<div class="formelement">';
$html .= '<label for="id_sql_delimiter">[ ' . __('Delimiter')
. '</label>' . "\n";
$html .= '<input type="text" name="sql_delimiter" tabindex="131" size="3" '
. 'value="' . $delimiter . '" '
. 'id="id_sql_delimiter" /> ]';
$html .= '</div>';
$html .= '<div class="formelement">';
$html .= '<input type="checkbox" name="show_query" value="1" '
. 'id="checkbox_show_query" tabindex="132" checked="checked" />'
. '<label for="checkbox_show_query">' . __('Show this query here again')
. '</label>';
$html .= '</div>';
$html .= '<div class="formelement">';
$html .= '<input type="checkbox" name="retain_query_box" value="1" '
. 'id="retain_query_box" tabindex="133" '
. ($GLOBALS['cfg']['RetainQueryBox'] === false
? '' : ' checked="checked"')
. ' />'
. '<label for="retain_query_box">' . __('Retain query box')
. '</label>';
$html .= '</div>';
$html .= '<div class="formelement">';
$html .= '<input type="checkbox" name="rollback_query" value="1" '
. 'id="rollback_query" tabindex="134" />'
. '<label for="rollback_query">' . __('Rollback when finished')
. '</label>';
$html .= '</div>';
// Disable/Enable foreign key checks
$html .= '<div class="formelement">';
$html .= Util::getFKCheckbox();
$html .= '</div>';
$html .= '<input type="submit" id="button_submit_query" name="SQL"';
$html .= ' tabindex="200" value="' . __('Go') . '" />' . "\n";
$html .= '<div class="clearfloat"></div>' . "\n";
$html .= '</fieldset>' . "\n";
return $html;
}
/**
* return HTML for sql Query Form Bookmark
*
* @return string|null
*
* @usedby self::getHtml()
*/
public static function getHtmlForBookmark()
{
$bookmark_list = Bookmark::getList($GLOBALS['db']);
if (empty($bookmark_list) || count($bookmark_list) < 1) {
return null;
}
$html = '<fieldset id="fieldsetBookmarkOptions">';
$html .= '<legend>';
$html .= __('Bookmarked SQL query') . '</legend>' . "\n";
$html .= '<div class="formelement">';
$html .= '<select name="id_bookmark" id="id_bookmark">' . "\n";
$html .= '<option value="">&nbsp;</option>' . "\n";
foreach ($bookmark_list as $bookmark) {
$html .= '<option value="' . htmlspecialchars($bookmark->getId()) . '"'
. ' data-varcount="' . $bookmark->getVariableCount()
. '">'
. htmlspecialchars($bookmark->getLabel())
. (empty($bookmark->getUser()) ? (' (' . __('shared') . ')') : '')
. '</option>' . "\n";
}
// &nbsp; is required for correct display with styles/line height
$html .= '</select>&nbsp;' . "\n";
$html .= '</div>' . "\n";
$html .= '<div class="formelement">' . "\n";
$html .= '<input type="radio" name="action_bookmark" value="0"'
. ' id="radio_bookmark_exe" checked="checked" />'
. '<label for="radio_bookmark_exe">' . __('Submit')
. '</label>' . "\n";
$html .= '<input type="radio" name="action_bookmark" value="1"'
. ' id="radio_bookmark_view" />'
. '<label for="radio_bookmark_view">' . __('View only')
. '</label>' . "\n";
$html .= '<input type="radio" name="action_bookmark" value="2"'
. ' id="radio_bookmark_del" />'
. '<label for="radio_bookmark_del">' . __('Delete')
. '</label>' . "\n";
$html .= '</div>' . "\n";
$html .= '<div class="clearfloat"></div>' . "\n";
$html .= '<div class="formelement hide">' . "\n";
$html .= __('Variables');
$html .= Util::showDocu('faq', 'faqbookmark');
$html .= '<div id="bookmark_variables"></div>';
$html .= '</div>' . "\n";
$html .= '</fieldset>' . "\n";
$html .= '<fieldset id="fieldsetBookmarkOptionsFooter" class="tblFooters">';
$html .= '<input type="submit" name="SQL" id="button_submit_bookmark" value="'
. __('Go') . '" />';
$html .= '<div class="clearfloat"></div>' . "\n";
$html .= '</fieldset>' . "\n";
return $html;
}
}

View File

@ -12,6 +12,7 @@ use PhpMyAdmin\Message;
use PhpMyAdmin\Relation;
use PhpMyAdmin\Response;
use PhpMyAdmin\Sanitize;
use PhpMyAdmin\SqlQueryForm;
use PhpMyAdmin\Template;
use PhpMyAdmin\Tracker;
use PhpMyAdmin\Url;
@ -1142,9 +1143,8 @@ class Tracking
$table_temp = $GLOBALS['table'];
$GLOBALS['db'] = $GLOBALS['table'] = '';
include_once './libraries/sql_query_form.lib.php';
$html .= PMA_getHtmlForSqlQueryForm($new_query, 'sql');
$html .= SqlQueryForm::getHtml($new_query, 'sql');
$GLOBALS['db'] = $db_temp;
$GLOBALS['table'] = $table_temp;

View File

@ -1,323 +0,0 @@
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Error reporting functions used to generate and submit error reports
*
* @package PhpMyAdmin
*/
use PhpMyAdmin\Relation;
use PhpMyAdmin\Url;
if (! defined('PHPMYADMIN')) {
exit;
}
/**
* The generated file that contains the line numbers for the js files
* If you change any of the js files you can run the scripts/line-counts.sh
*/
if (is_readable('js/line_counts.php')) {
include_once 'js/line_counts.php';
}
/**
* the url where to submit reports to
*/
define('SUBMISSION_URL', "https://reports.phpmyadmin.net/incidents/create");
/**
* returns the pretty printed error report data collected from the
* current configuration or from the request parameters sent by the
* error reporting js code.
*
* @return String the report
*/
function PMA_getPrettyReportData()
{
$report = PMA_getReportData();
return json_encode($report, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
}
/**
* returns the error report data collected from the current configuration or
* from the request parameters sent by the error reporting js code.
*
* @param string $exception_type whether exception is 'js' or 'php'
*
* @return array error report if success, Empty Array otherwise
*/
function PMA_getReportData($exception_type = 'js')
{
$relParams = Relation::getRelationsParam();
// common params for both, php & js exceptions
$report = array(
"pma_version" => PMA_VERSION,
"browser_name" => PMA_USR_BROWSER_AGENT,
"browser_version" => PMA_USR_BROWSER_VER,
"user_os" => PMA_USR_OS,
"server_software" => $_SERVER['SERVER_SOFTWARE'],
"user_agent_string" => $_SERVER['HTTP_USER_AGENT'],
"locale" => $_COOKIE['pma_lang'],
"configuration_storage" =>
is_null($relParams['db']) ? "disabled" :
"enabled",
"php_version" => phpversion()
);
if ($exception_type == 'js') {
if (empty($_REQUEST['exception'])) {
return array();
}
$exception = $_REQUEST['exception'];
$exception["stack"] = PMA_translateStacktrace($exception["stack"]);
List($uri, $script_name) = PMA_sanitizeUrl($exception["url"]);
$exception["uri"] = $uri;
unset($exception["url"]);
$report ["exception_type"] = 'js';
$report ["exception"] = $exception;
$report ["script_name"] = $script_name;
$report ["microhistory"] = $_REQUEST['microhistory'];
if (! empty($_REQUEST['description'])) {
$report['steps'] = $_REQUEST['description'];
}
} elseif ($exception_type == 'php') {
$errors = array();
// create php error report
$i = 0;
if (!isset($_SESSION['prev_errors'])
|| $_SESSION['prev_errors'] == ''
) {
return array();
}
foreach ($_SESSION['prev_errors'] as $errorObj) {
/* @var $errorObj PhpMyAdmin\Error */
if ($errorObj->getLine()
&& $errorObj->getType()
&& $errorObj->getNumber() != E_USER_WARNING
) {
$errors[$i++] = array(
"lineNum" => $errorObj->getLine(),
"file" => $errorObj->getFile(),
"type" => $errorObj->getType(),
"msg" => $errorObj->getOnlyMessage(),
"stackTrace" => $errorObj->getBacktrace(5),
"stackhash" => $errorObj->getHash()
);
}
}
// if there were no 'actual' errors to be submitted.
if ($i==0) {
return array(); // then return empty array
}
$report ["exception_type"] = 'php';
$report["errors"] = $errors;
} else {
return array();
}
return $report;
}
/**
* Sanitize a url to remove the identifiable host name and extract the
* current script name from the url fragment
*
* It returns two things in an array. The first is the uri without the
* hostname and identifying query params. The second is the name of the
* php script in the url
*
* @param String $url the url to sanitize
*
* @return array the uri and script name
*/
function PMA_sanitizeUrl($url)
{
$components = parse_url($url);
if (isset($components["fragment"])
&& preg_match("<PMAURL-\d+:>", $components["fragment"], $matches)
) {
$uri = str_replace($matches[0], "", $components["fragment"]);
$url = "https://example.com/" . $uri;
$components = parse_url($url);
}
// get script name
preg_match("<([a-zA-Z\-_\d]*\.php)$>", $components["path"], $matches);
if (count($matches) < 2) {
$script_name = 'index.php';
} else {
$script_name = $matches[1];
}
// remove deployment specific details to make uri more generic
if (isset($components["query"])) {
parse_str($components["query"], $query_array);
unset($query_array["db"]);
unset($query_array["table"]);
unset($query_array["token"]);
unset($query_array["server"]);
$query = http_build_query($query_array);
} else {
$query = '';
}
$uri = $script_name . "?" . $query;
return array($uri, $script_name);
}
/**
* Sends report data to the error reporting server
*
* @param array $report the report info to be sent
*
* @return String the reply of the server
*/
function PMA_sendErrorReport($report)
{
$response = PhpMyAdmin\Util::httpRequest(
SUBMISSION_URL,
"POST",
false,
json_encode($report),
"Content-Type: application/json"
);
return $response;
}
/**
* Returns number of lines in given javascript file.
*
* @param string $filename javascript filename
*
* @return Number of lines
*
* @todo Should gracefully handle non existing files
*/
function PMA_countLines($filename)
{
global $LINE_COUNT;
if (defined('LINE_COUNTS')) {
return $LINE_COUNT[$filename];
}
// ensure that the file is inside the phpMyAdmin folder
$depath = 1;
foreach (explode('/', $filename) as $part) {
if ($part == '..') {
$depath--;
} elseif ($part != '.' || $part === '') {
$depath++;
}
if ($depath < 0) {
return 0;
}
}
$linecount = 0;
$handle = fopen('./js/' . $filename, 'r');
while (!feof($handle)) {
$line = fgets($handle);
if ($line === false) {
break;
}
$linecount++;
}
fclose($handle);
return $linecount;
}
/**
* returns the translated line number and the file name from the cumulative line
* number and an array of files
*
* uses the $LINE_COUNT global array of file names and line numbers
*
* @param array $filenames list of files in order of concatenation
* @param Integer $cumulative_number the cumulative line number in the
* concatenated files
*
* @return array the filename and line number
* Returns two variables in an array:
* - A String $filename the filename where the requested cumulative number
* exists
* - Integer $linenumber the translated line number in the returned file
*/
function PMA_getLineNumber($filenames, $cumulative_number)
{
$cumulative_sum = 0;
foreach ($filenames as $filename) {
$filecount = PMA_countLines($filename);
if ($cumulative_number <= $cumulative_sum + $filecount + 2) {
$linenumber = $cumulative_number - $cumulative_sum;
break;
}
$cumulative_sum += $filecount + 2;
}
if (! isset($filename)) {
$filename = '';
}
return array($filename, $linenumber);
}
/**
* translates the cumulative line numbers in the stack trace as well as sanitize
* urls and trim long lines in the context
*
* @param array $stack the stack trace
*
* @return array $stack the modified stack trace
*/
function PMA_translateStacktrace($stack)
{
foreach ($stack as &$level) {
foreach ($level["context"] as &$line) {
if (mb_strlen($line) > 80) {
$line = mb_substr($line, 0, 75) . "//...";
}
}
if (preg_match("<js/get_scripts.js.php\?(.*)>", $level["url"], $matches)) {
parse_str($matches[1], $vars);
List($file_name, $line_number) = PMA_getLineNumber(
$vars["scripts"], $level["line"]
);
$level["filename"] = $file_name;
$level["line"] = $line_number;
} else {
unset($level["context"]);
List($uri, $script_name) = PMA_sanitizeUrl($level["url"]);
$level["uri"] = $uri;
$level["scriptname"] = $script_name;
}
unset($level["url"]);
}
unset($level);
return $stack;
}
/**
* generates the error report form to collect user description and preview the
* report before being sent
*
* @return String the form
*/
function PMA_getErrorReportForm()
{
$datas = array(
'report_data' => PMA_getPrettyReportData(),
'hidden_inputs' => Url::getHiddenInputs(),
'hidden_fields' => null,
);
$reportData = PMA_getReportData();
if (!empty($reportData)) {
$datas['hidden_fields'] = Url::getHiddenFields($reportData);
}
return PhpMyAdmin\Template::get('error/report_form')
->render($datas);
}

View File

@ -1,773 +0,0 @@
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Common functions for Designer
*
* @package PhpMyAdmin-Designer
*/
use PhpMyAdmin\Relation;
use PhpMyAdmin\Table;
/**
* Block attempts to directly run this script
*/
if (! defined('PHPMYADMIN')) {
exit;
}
$GLOBALS['PMD']['STYLE'] = 'default';
$cfgRelation = Relation::getRelationsParam();
/**
* Retrieves table info and stores it in $GLOBALS['PMD']
*
* @return array with table info
*/
function PMA_getTablesInfo()
{
$retval = array();
$GLOBALS['PMD']['TABLE_NAME'] = array();// that foreach no error
$GLOBALS['PMD']['OWNER'] = array();
$GLOBALS['PMD']['TABLE_NAME_SMALL'] = array();
$tables = $GLOBALS['dbi']->getTablesFull($GLOBALS['db']);
// seems to be needed later
$GLOBALS['dbi']->selectDb($GLOBALS['db']);
$i = 0;
foreach ($tables as $one_table) {
$GLOBALS['PMD']['TABLE_NAME'][$i]
= $GLOBALS['db'] . "." . $one_table['TABLE_NAME'];
$GLOBALS['PMD']['OWNER'][$i] = $GLOBALS['db'];
$GLOBALS['PMD']['TABLE_NAME_SMALL'][$i] = htmlspecialchars(
$one_table['TABLE_NAME'], ENT_QUOTES
);
$GLOBALS['PMD_URL']['TABLE_NAME'][$i]
= $GLOBALS['db'] . "." . $one_table['TABLE_NAME'];
$GLOBALS['PMD_URL']['OWNER'][$i] = $GLOBALS['db'];
$GLOBALS['PMD_URL']['TABLE_NAME_SMALL'][$i]
= $one_table['TABLE_NAME'];
$GLOBALS['PMD_OUT']['TABLE_NAME'][$i] = htmlspecialchars(
$GLOBALS['db'] . "." . $one_table['TABLE_NAME'], ENT_QUOTES
);
$GLOBALS['PMD_OUT']['OWNER'][$i] = htmlspecialchars(
$GLOBALS['db'], ENT_QUOTES
);
$GLOBALS['PMD_OUT']['TABLE_NAME_SMALL'][$i] = htmlspecialchars(
$one_table['TABLE_NAME'], ENT_QUOTES
);
$GLOBALS['PMD']['TABLE_TYPE'][$i] = mb_strtoupper(
$one_table['ENGINE']
);
$DF = Relation::getDisplayField($GLOBALS['db'], $one_table['TABLE_NAME']);
if ($DF != '') {
$retval[$GLOBALS['PMD_URL']["TABLE_NAME_SMALL"][$i]] = $DF;
}
$i++;
}
return $retval;
}
/**
* Retrieves table column info
*
* @return array table column nfo
*/
function PMA_getColumnsInfo()
{
$GLOBALS['dbi']->selectDb($GLOBALS['db']);
$tab_column = array();
for ($i = 0, $cnt = count($GLOBALS['PMD']["TABLE_NAME"]); $i < $cnt; $i++) {
$fields_rs = $GLOBALS['dbi']->query(
$GLOBALS['dbi']->getColumnsSql(
$GLOBALS['db'],
$GLOBALS['PMD_URL']["TABLE_NAME_SMALL"][$i],
null,
true
),
null,
PhpMyAdmin\DatabaseInterface::QUERY_STORE
);
$tbl_name_i = $GLOBALS['PMD']['TABLE_NAME'][$i];
$j = 0;
while ($row = $GLOBALS['dbi']->fetchAssoc($fields_rs)) {
$tab_column[$tbl_name_i]['COLUMN_ID'][$j] = $j;
$tab_column[$tbl_name_i]['COLUMN_NAME'][$j] = $row['Field'];
$tab_column[$tbl_name_i]['TYPE'][$j] = $row['Type'];
$tab_column[$tbl_name_i]['NULLABLE'][$j] = $row['Null'];
$j++;
}
}
return $tab_column;
}
/**
* Returns JavaScript code for initializing vars
*
* @return string JavaScript code
*/
function PMA_getScriptContr()
{
$GLOBALS['dbi']->selectDb($GLOBALS['db']);
$con = array();
$con["C_NAME"] = array();
$i = 0;
$alltab_rs = $GLOBALS['dbi']->query(
'SHOW TABLES FROM ' . PhpMyAdmin\Util::backquote($GLOBALS['db']),
null,
PhpMyAdmin\DatabaseInterface::QUERY_STORE
);
while ($val = @$GLOBALS['dbi']->fetchRow($alltab_rs)) {
$row = Relation::getForeigners($GLOBALS['db'], $val[0], '', 'internal');
if ($row !== false) {
foreach ($row as $field => $value) {
$con['C_NAME'][$i] = '';
$con['DTN'][$i] = urlencode($GLOBALS['db'] . "." . $val[0]);
$con['DCN'][$i] = urlencode($field);
$con['STN'][$i] = urlencode(
$value['foreign_db'] . "." . $value['foreign_table']
);
$con['SCN'][$i] = urlencode($value['foreign_field']);
$i++;
}
}
$row = Relation::getForeigners($GLOBALS['db'], $val[0], '', 'foreign');
if ($row !== false) {
foreach ($row['foreign_keys_data'] as $one_key) {
foreach ($one_key['index_list'] as $index => $one_field) {
$con['C_NAME'][$i] = $one_key['constraint'];
$con['DTN'][$i] = urlencode($GLOBALS['db'] . "." . $val[0]);
$con['DCN'][$i] = urlencode($one_field);
$con['STN'][$i] = urlencode(
(isset($one_key['ref_db_name']) ?
$one_key['ref_db_name'] : $GLOBALS['db'])
. "." . $one_key['ref_table_name']
);
$con['SCN'][$i] = urlencode($one_key['ref_index_list'][$index]);
$i++;
}
}
}
}
$ti = 0;
$retval = array();
for ($i = 0, $cnt = count($con["C_NAME"]); $i < $cnt; $i++) {
$c_name_i = $con['C_NAME'][$i];
$dtn_i = $con['DTN'][$i];
$retval[$ti] = array();
$retval[$ti][$c_name_i] = array();
if (in_array($dtn_i, $GLOBALS['PMD_URL']["TABLE_NAME"])
&& in_array($con['STN'][$i], $GLOBALS['PMD_URL']["TABLE_NAME"])
) {
$retval[$ti][$c_name_i][$dtn_i] = array();
$retval[$ti][$c_name_i][$dtn_i][$con['DCN'][$i]] = array(
0 => $con['STN'][$i],
1 => $con['SCN'][$i]
);
}
$ti++;
}
return $retval;
}
/**
* Returns UNIQUE and PRIMARY indices
*
* @return array unique or primary indices
*/
function PMA_getPKOrUniqueKeys()
{
return PMA_getAllKeys(true);
}
/**
* Returns all indices
*
* @param bool $unique_only whether to include only unique ones
*
* @return array indices
*/
function PMA_getAllKeys($unique_only = false)
{
$keys = array();
foreach ($GLOBALS['PMD']['TABLE_NAME_SMALL'] as $I => $table) {
$schema = $GLOBALS['PMD']['OWNER'][$I];
// for now, take into account only the first index segment
foreach (PhpMyAdmin\Index::getFromTable($table, $schema) as $index) {
if ($unique_only && ! $index->isUnique()) {
continue;
}
$columns = $index->getColumns();
foreach ($columns as $column_name => $dummy) {
$keys[$schema . '.' . $table . '.' . $column_name] = 1;
}
}
}
return $keys;
}
/**
* Return script to create j_tab and h_tab arrays
*
* @return string
*/
function PMA_getScriptTabs()
{
$retval = array(
'j_tabs' => array(),
'h_tabs' => array()
);
for ($i = 0, $cnt = count($GLOBALS['PMD']['TABLE_NAME']); $i < $cnt; $i++) {
$j = 0;
if (PhpMyAdmin\Util::isForeignKeySupported($GLOBALS['PMD']['TABLE_TYPE'][$i])) {
$j = 1;
}
$retval['j_tabs'][$GLOBALS['PMD_URL']['TABLE_NAME'][$i]] = $j;
$retval['h_tabs'][$GLOBALS['PMD_URL']['TABLE_NAME'][$i]] = 1;
}
return $retval;
}
/**
* Returns table positions of a given pdf page
*
* @param int $pg pdf page id
*
* @return array of table positions
*/
function PMA_getTablePositions($pg)
{
$cfgRelation = Relation::getRelationsParam();
if (! $cfgRelation['pdfwork']) {
return null;
}
$query = "
SELECT CONCAT_WS('.', `db_name`, `table_name`) AS `name`,
`x` AS `X`,
`y` AS `Y`,
1 AS `V`,
1 AS `H`
FROM " . PhpMyAdmin\Util::backquote($cfgRelation['db'])
. "." . PhpMyAdmin\Util::backquote($cfgRelation['table_coords']) . "
WHERE pdf_page_number = " . intval($pg);
$tab_pos = $GLOBALS['dbi']->fetchResult(
$query,
'name',
null,
$GLOBALS['controllink'],
PhpMyAdmin\DatabaseInterface::QUERY_STORE
);
return $tab_pos;
}
/**
* Returns page name of a given pdf page
*
* @param int $pg pdf page id
*
* @return String table name
*/
function PMA_getPageName($pg)
{
$cfgRelation = Relation::getRelationsParam();
if (! $cfgRelation['pdfwork']) {
return null;
}
$query = "SELECT `page_descr`"
. " FROM " . PhpMyAdmin\Util::backquote($cfgRelation['db'])
. "." . PhpMyAdmin\Util::backquote($cfgRelation['pdf_pages'])
. " WHERE " . PhpMyAdmin\Util::backquote('page_nr') . " = " . intval($pg);
$page_name = $GLOBALS['dbi']->fetchResult(
$query,
null,
null,
$GLOBALS['controllink'],
PhpMyAdmin\DatabaseInterface::QUERY_STORE
);
return count($page_name) ? $page_name[0] : null;
}
/**
* Deletes a given pdf page and its corresponding coordinates
*
* @param int $pg page id
*
* @return boolean success/failure
*/
function PMA_deletePage($pg)
{
$cfgRelation = Relation::getRelationsParam();
if (! $cfgRelation['pdfwork']) {
return false;
}
$query = "DELETE FROM " . PhpMyAdmin\Util::backquote($cfgRelation['db'])
. "." . PhpMyAdmin\Util::backquote($cfgRelation['table_coords'])
. " WHERE " . PhpMyAdmin\Util::backquote('pdf_page_number') . " = " . intval($pg);
$success = Relation::queryAsControlUser(
$query, true, PhpMyAdmin\DatabaseInterface::QUERY_STORE
);
if ($success) {
$query = "DELETE FROM " . PhpMyAdmin\Util::backquote($cfgRelation['db'])
. "." . PhpMyAdmin\Util::backquote($cfgRelation['pdf_pages'])
. " WHERE " . PhpMyAdmin\Util::backquote('page_nr') . " = " . intval($pg);
$success = Relation::queryAsControlUser(
$query, true, PhpMyAdmin\DatabaseInterface::QUERY_STORE
);
}
return (boolean) $success;
}
/**
* Returns the id of the default pdf page of the database.
* Default page is the one which has the same name as the database.
*
* @param string $db database
*
* @return int id of the default pdf page for the database
*/
function PMA_getDefaultPage($db)
{
$cfgRelation = Relation::getRelationsParam();
if (! $cfgRelation['pdfwork']) {
return null;
}
$query = "SELECT `page_nr`"
. " FROM " . PhpMyAdmin\Util::backquote($cfgRelation['db'])
. "." . PhpMyAdmin\Util::backquote($cfgRelation['pdf_pages'])
. " WHERE `db_name` = '" . $GLOBALS['dbi']->escapeString($db) . "'"
. " AND `page_descr` = '" . $GLOBALS['dbi']->escapeString($db) . "'";
$default_page_no = $GLOBALS['dbi']->fetchResult(
$query,
null,
null,
$GLOBALS['controllink'],
PhpMyAdmin\DatabaseInterface::QUERY_STORE
);
if (count($default_page_no)) {
return intval($default_page_no[0]);
}
return -1;
}
/**
* Get the id of the page to load. If a default page exists it will be returned.
* If no such exists, returns the id of the first page of the database.
*
* @param string $db database
*
* @return int id of the page to load
*/
function PMA_getLoadingPage($db)
{
$cfgRelation = Relation::getRelationsParam();
if (! $cfgRelation['pdfwork']) {
return null;
}
$page_no = -1;
$default_page_no = PMA_getDefaultPage($db);
if ($default_page_no != -1) {
$page_no = $default_page_no;
} else {
$query = "SELECT MIN(`page_nr`)"
. " FROM " . PhpMyAdmin\Util::backquote($cfgRelation['db'])
. "." . PhpMyAdmin\Util::backquote($cfgRelation['pdf_pages'])
. " WHERE `db_name` = '" . $GLOBALS['dbi']->escapeString($db) . "'";
$min_page_no = $GLOBALS['dbi']->fetchResult(
$query,
null,
null,
$GLOBALS['controllink'],
PhpMyAdmin\DatabaseInterface::QUERY_STORE
);
if (count($min_page_no[0])) {
$page_no = $min_page_no[0];
}
}
return intval($page_no);
}
/**
* Creates a new page and returns its auto-incrementing id
*
* @param string $pageName name of the page
* @param string $db name of the database
*
* @return int|null
*/
function PMA_createNewPage($pageName, $db)
{
$cfgRelation = Relation::getRelationsParam();
if ($cfgRelation['pdfwork']) {
$pageNumber = Relation::createPage(
$pageName,
$cfgRelation,
$db
);
return $pageNumber;
}
return null;
}
/**
* Saves positions of table(s) of a given pdf page
*
* @param int $pg pdf page id
*
* @return boolean success/failure
*/
function PMA_saveTablePositions($pg)
{
$cfgRelation = Relation::getRelationsParam();
if (! $cfgRelation['pdfwork']) {
return false;
}
$query = "DELETE FROM "
. PhpMyAdmin\Util::backquote($GLOBALS['cfgRelation']['db'])
. "." . PhpMyAdmin\Util::backquote(
$GLOBALS['cfgRelation']['table_coords']
)
. " WHERE `db_name` = '" . $GLOBALS['dbi']->escapeString($_REQUEST['db'])
. "'"
. " AND `pdf_page_number` = '" . $GLOBALS['dbi']->escapeString($pg)
. "'";
$res = Relation::queryAsControlUser(
$query,
true,
PhpMyAdmin\DatabaseInterface::QUERY_STORE
);
if (!$res) {
return (boolean)$res;
}
foreach ($_REQUEST['t_h'] as $key => $value) {
list($DB, $TAB) = explode(".", $key);
if (!$value) {
continue;
}
$query = "INSERT INTO "
. PhpMyAdmin\Util::backquote($GLOBALS['cfgRelation']['db']) . "."
. PhpMyAdmin\Util::backquote($GLOBALS['cfgRelation']['table_coords'])
. " (`db_name`, `table_name`, `pdf_page_number`, `x`, `y`)"
. " VALUES ("
. "'" . $GLOBALS['dbi']->escapeString($DB) . "', "
. "'" . $GLOBALS['dbi']->escapeString($TAB) . "', "
. "'" . $GLOBALS['dbi']->escapeString($pg) . "', "
. "'" . $GLOBALS['dbi']->escapeString($_REQUEST['t_x'][$key]) . "', "
. "'" . $GLOBALS['dbi']->escapeString($_REQUEST['t_y'][$key]) . "')";
$res = Relation::queryAsControlUser(
$query, true, PhpMyAdmin\DatabaseInterface::QUERY_STORE
);
}
return (boolean) $res;
}
/**
* Saves the display field for a table.
*
* @param string $db database name
* @param string $table table name
* @param string $field display field name
*
* @return boolean
*/
function PMA_saveDisplayField($db, $table, $field)
{
$cfgRelation = Relation::getRelationsParam();
if (!$cfgRelation['displaywork']) {
return false;
}
$upd_query = new Table($table, $db, $GLOBALS['dbi']);
$upd_query->updateDisplayField($field, $cfgRelation);
return true;
}
/**
* Adds a new foreign relation
*
* @param string $db database name
* @param string $T1 foreign table
* @param string $F1 foreign field
* @param string $T2 master table
* @param string $F2 master field
* @param string $on_delete on delete action
* @param string $on_update on update action
*
* @return array array of success/failure and message
*/
function PMA_addNewRelation($db, $T1, $F1, $T2, $F2, $on_delete, $on_update, $DB1, $DB2)
{
$tables = $GLOBALS['dbi']->getTablesFull($DB1, $T1);
$type_T1 = mb_strtoupper($tables[$T1]['ENGINE']);
$tables = $GLOBALS['dbi']->getTablesFull($DB2, $T2);
$type_T2 = mb_strtoupper($tables[$T2]['ENGINE']);
// native foreign key
if (PhpMyAdmin\Util::isForeignKeySupported($type_T1)
&& PhpMyAdmin\Util::isForeignKeySupported($type_T2)
&& $type_T1 == $type_T2
) {
// relation exists?
$existrel_foreign = Relation::getForeigners($DB2, $T2, '', 'foreign');
$foreigner = Relation::searchColumnInForeigners($existrel_foreign, $F2);
if ($foreigner
&& isset($foreigner['constraint'])
) {
return array(false, __('Error: relationship already exists.'));
}
// note: in InnoDB, the index does not requires to be on a PRIMARY
// or UNIQUE key
// improve: check all other requirements for InnoDB relations
$result = $GLOBALS['dbi']->query(
'SHOW INDEX FROM ' . PhpMyAdmin\Util::backquote($DB1)
. '.' . PhpMyAdmin\Util::backquote($T1) . ';'
);
// will be use to emphasis prim. keys in the table view
$index_array1 = array();
while ($row = $GLOBALS['dbi']->fetchAssoc($result)) {
$index_array1[$row['Column_name']] = 1;
}
$GLOBALS['dbi']->freeResult($result);
$result = $GLOBALS['dbi']->query(
'SHOW INDEX FROM ' . PhpMyAdmin\Util::backquote($DB2)
. '.' . PhpMyAdmin\Util::backquote($T2) . ';'
);
// will be used to emphasis prim. keys in the table view
$index_array2 = array();
while ($row = $GLOBALS['dbi']->fetchAssoc($result)) {
$index_array2[$row['Column_name']] = 1;
}
$GLOBALS['dbi']->freeResult($result);
if (! empty($index_array1[$F1]) && ! empty($index_array2[$F2])) {
$upd_query = 'ALTER TABLE ' . PhpMyAdmin\Util::backquote($DB2)
. '.' . PhpMyAdmin\Util::backquote($T2)
. ' ADD FOREIGN KEY ('
. PhpMyAdmin\Util::backquote($F2) . ')'
. ' REFERENCES '
. PhpMyAdmin\Util::backquote($DB1) . '.'
. PhpMyAdmin\Util::backquote($T1) . '('
. PhpMyAdmin\Util::backquote($F1) . ')';
if ($on_delete != 'nix') {
$upd_query .= ' ON DELETE ' . $on_delete;
}
if ($on_update != 'nix') {
$upd_query .= ' ON UPDATE ' . $on_update;
}
$upd_query .= ';';
if ($GLOBALS['dbi']->tryQuery($upd_query)) {
return array(true, __('FOREIGN KEY relationship has been added.'));
}
$error = $GLOBALS['dbi']->getError();
return array(
false,
__('Error: FOREIGN KEY relationship could not be added!')
. "<br/>" . $error
);
}
return array(false, __('Error: Missing index on column(s).'));
}
// internal (pmadb) relation
if ($GLOBALS['cfgRelation']['relwork'] == false) {
return array(false, __('Error: Relational features are disabled!'));
}
// no need to recheck if the keys are primary or unique at this point,
// this was checked on the interface part
$q = "INSERT INTO "
. PhpMyAdmin\Util::backquote($GLOBALS['cfgRelation']['db'])
. "."
. PhpMyAdmin\Util::backquote($GLOBALS['cfgRelation']['relation'])
. "(master_db, master_table, master_field, "
. "foreign_db, foreign_table, foreign_field)"
. " values("
. "'" . $GLOBALS['dbi']->escapeString($DB2) . "', "
. "'" . $GLOBALS['dbi']->escapeString($T2) . "', "
. "'" . $GLOBALS['dbi']->escapeString($F2) . "', "
. "'" . $GLOBALS['dbi']->escapeString($DB1) . "', "
. "'" . $GLOBALS['dbi']->escapeString($T1) . "', "
. "'" . $GLOBALS['dbi']->escapeString($F1) . "')";
if (Relation::queryAsControlUser($q, false, PhpMyAdmin\DatabaseInterface::QUERY_STORE)
) {
return array(true, __('Internal relationship has been added.'));
}
$error = $GLOBALS['dbi']->getError($GLOBALS['controllink']);
return array(
false,
__('Error: Internal relationship could not be added!')
. "<br/>" . $error
);
}
/**
* Removes a foreign relation
*
* @param string $T1 foreign db.table
* @param string $F1 foreign field
* @param string $T2 master db.table
* @param string $F2 master field
*
* @return array array of success/failure and message
*/
function PMA_removeRelation($T1, $F1, $T2, $F2)
{
list($DB1, $T1) = explode(".", $T1);
list($DB2, $T2) = explode(".", $T2);
$tables = $GLOBALS['dbi']->getTablesFull($DB1, $T1);
$type_T1 = mb_strtoupper($tables[$T1]['ENGINE']);
$tables = $GLOBALS['dbi']->getTablesFull($DB2, $T2);
$type_T2 = mb_strtoupper($tables[$T2]['ENGINE']);
if (PhpMyAdmin\Util::isForeignKeySupported($type_T1)
&& PhpMyAdmin\Util::isForeignKeySupported($type_T2)
&& $type_T1 == $type_T2
) {
// InnoDB
$existrel_foreign = Relation::getForeigners($DB2, $T2, '', 'foreign');
$foreigner = Relation::searchColumnInForeigners($existrel_foreign, $F2);
if (isset($foreigner['constraint'])) {
$upd_query = 'ALTER TABLE ' . PhpMyAdmin\Util::backquote($DB2)
. '.' . PhpMyAdmin\Util::backquote($T2) . ' DROP FOREIGN KEY '
. PhpMyAdmin\Util::backquote($foreigner['constraint']) . ';';
if ($GLOBALS['dbi']->query($upd_query)) {
return array(true, __('FOREIGN KEY relationship has been removed.'));
}
$error = $GLOBALS['dbi']->getError();
return array(
false,
__('Error: FOREIGN KEY relationship could not be removed!')
. "<br/>" . $error
);
}
}
// internal relations
$delete_query = "DELETE FROM "
. PhpMyAdmin\Util::backquote($GLOBALS['cfgRelation']['db']) . "."
. $GLOBALS['cfgRelation']['relation'] . " WHERE "
. "master_db = '" . $GLOBALS['dbi']->escapeString($DB2) . "'"
. " AND master_table = '" . $GLOBALS['dbi']->escapeString($T2) . "'"
. " AND master_field = '" . $GLOBALS['dbi']->escapeString($F2) . "'"
. " AND foreign_db = '" . $GLOBALS['dbi']->escapeString($DB1) . "'"
. " AND foreign_table = '" . $GLOBALS['dbi']->escapeString($T1) . "'"
. " AND foreign_field = '" . $GLOBALS['dbi']->escapeString($F1) . "'";
$result = Relation::queryAsControlUser(
$delete_query,
false,
PhpMyAdmin\DatabaseInterface::QUERY_STORE
);
if (!$result) {
$error = $GLOBALS['dbi']->getError($GLOBALS['controllink']);
return array(
false,
__('Error: Internal relationship could not be removed!') . "<br/>" . $error
);
}
return array(true, __('Internal relationship has been removed.'));
}
/**
* Save value for a designer setting
*
* @param string $index setting
* @param string $value value
*
* @return bool whether the operation succeeded
*/
function PMA_saveDesignerSetting($index, $value)
{
$cfgRelation = Relation::getRelationsParam();
$cfgDesigner = array(
'user' => $GLOBALS['cfg']['Server']['user'],
'db' => $cfgRelation['db'],
'table' => $cfgRelation['designer_settings']
);
$success = true;
if ($GLOBALS['cfgRelation']['designersettingswork']) {
$orig_data_query = "SELECT settings_data"
. " FROM " . PhpMyAdmin\Util::backquote($cfgDesigner['db'])
. "." . PhpMyAdmin\Util::backquote($cfgDesigner['table'])
. " WHERE username = '"
. $GLOBALS['dbi']->escapeString($cfgDesigner['user']) . "';";
$orig_data = $GLOBALS['dbi']->fetchSingleRow(
$orig_data_query, 'ASSOC', $GLOBALS['controllink']
);
if (! empty($orig_data)) {
$orig_data = json_decode($orig_data['settings_data'], true);
$orig_data[$index] = $value;
$orig_data = json_encode($orig_data);
$save_query = "UPDATE "
. PhpMyAdmin\Util::backquote($cfgDesigner['db'])
. "." . PhpMyAdmin\Util::backquote($cfgDesigner['table'])
. " SET settings_data = '" . $orig_data . "'"
. " WHERE username = '"
. $GLOBALS['dbi']->escapeString($cfgDesigner['user']) . "';";
$success = Relation::queryAsControlUser($save_query);
} else {
$save_data = array($index => $value);
$query = "INSERT INTO "
. PhpMyAdmin\Util::backquote($cfgDesigner['db'])
. "." . PhpMyAdmin\Util::backquote($cfgDesigner['table'])
. " (username, settings_data)"
. " VALUES('" . $cfgDesigner['user'] . "',"
. " '" . json_encode($save_data) . "');";
$success = Relation::queryAsControlUser($query);
}
}
return (bool) $success;
}

View File

@ -5,14 +5,12 @@
*
* @package PhpMyAdmin
*/
use PhpMyAdmin\Core;
use PhpMyAdmin\DatabaseInterface;
if (! defined('PHPMYADMIN')) {
exit;
}
use PhpMyAdmin\Replication;
/**
* get master replication from server
*/
@ -102,7 +100,7 @@ $slave_variables = array(
* define important variables, which need to be watched for
* correct running of replication in slave mode
*
* @usedby PMA_getHtmlForReplicationStatusTable()
* @usedby PhpMyAdmin\ReplicationGui::getHtmlForReplicationStatusTable()
*/
// TODO change to regexp or something, to allow for negative match.
// To e.g. highlight 'Last_Error'
@ -130,198 +128,45 @@ foreach ($replication_types as $type) {
}
if ($GLOBALS['replication_info'][$type]['status']) {
if ($type == "master") {
PMA_fillReplicationInfo(
Replication::fillInfo(
$type, 'Do_DB', $server_master_replication[0],
'Binlog_Do_DB'
);
PMA_fillReplicationInfo(
Replication::fillInfo(
$type, 'Ignore_DB', $server_master_replication[0],
'Binlog_Ignore_DB'
);
} elseif ($type == "slave") {
PMA_fillReplicationInfo(
Replication::fillInfo(
$type, 'Do_DB', $server_slave_replication[0],
'Replicate_Do_DB'
);
PMA_fillReplicationInfo(
Replication::fillInfo(
$type, 'Ignore_DB', $server_slave_replication[0],
'Replicate_Ignore_DB'
);
PMA_fillReplicationInfo(
Replication::fillInfo(
$type, 'Do_Table', $server_slave_replication[0],
'Replicate_Do_Table'
);
PMA_fillReplicationInfo(
Replication::fillInfo(
$type, 'Ignore_Table', $server_slave_replication[0],
'Replicate_Ignore_Table'
);
PMA_fillReplicationInfo(
Replication::fillInfo(
$type, 'Wild_Do_Table', $server_slave_replication[0],
'Replicate_Wild_Do_Table'
);
PMA_fillReplicationInfo(
Replication::fillInfo(
$type, 'Wild_Ignore_Table', $server_slave_replication[0],
'Replicate_Wild_Ignore_Table'
);
}
}
}
/**
* Fill global replication_info variable.
*
* @param string $type Type: master, slave
* @param string $replicationInfoKey Key in replication_info variable
* @param array $mysqlInfo MySQL data about replication
* @param string $mysqlKey MySQL key
*
* @return array
*/
function PMA_fillReplicationInfo(
$type, $replicationInfoKey, $mysqlInfo, $mysqlKey
) {
$GLOBALS['replication_info'][$type][$replicationInfoKey]
= empty($mysqlInfo[$mysqlKey])
? array()
: explode(
",",
$mysqlInfo[$mysqlKey]
);
return $GLOBALS['replication_info'][$type][$replicationInfoKey];
}
/**
* Extracts database or table name from string
*
* @param string $string contains "dbname.tablename"
* @param string $what what to extract (db|table)
*
* @return string the extracted part
*/
function PMA_extractDbOrTable($string, $what = 'db')
{
$list = explode(".", $string);
if ('db' == $what) {
return $list[0];
} else {
return $list[1];
}
}
/**
* Configures replication slave
*
* @param string $action possible values: START or STOP
* @param string $control default: null,
* possible values: SQL_THREAD or IO_THREAD or null.
* If it is set to null, it controls both
* SQL_THREAD and IO_THREAD
* @param mixed $link mysql link
*
* @return mixed output of DatabaseInterface::tryQuery
*/
function PMA_Replication_Slave_control($action, $control = null, $link = null)
{
$action = mb_strtoupper($action);
$control = mb_strtoupper($control);
if ($action != "START" && $action != "STOP") {
return -1;
}
if ($control != "SQL_THREAD" && $control != "IO_THREAD" && $control != null) {
return -1;
}
return $GLOBALS['dbi']->tryQuery($action . " SLAVE " . $control . ";", $link);
}
/**
* Changes master for replication slave
*
* @param string $user replication user on master
* @param string $password password for the user
* @param string $host master's hostname or IP
* @param int $port port, where mysql is running
* @param array $pos position of mysql replication,
* array should contain fields File and Position
* @param bool $stop shall we stop slave?
* @param bool $start shall we start slave?
* @param mixed $link mysql link
*
* @return string output of CHANGE MASTER mysql command
*/
function PMA_Replication_Slave_changeMaster($user, $password, $host, $port,
$pos, $stop = true, $start = true, $link = null
) {
if ($stop) {
PMA_Replication_Slave_control("STOP", null, $link);
}
$out = $GLOBALS['dbi']->tryQuery(
'CHANGE MASTER TO ' .
'MASTER_HOST=\'' . $host . '\',' .
'MASTER_PORT=' . ($port * 1) . ',' .
'MASTER_USER=\'' . $user . '\',' .
'MASTER_PASSWORD=\'' . $password . '\',' .
'MASTER_LOG_FILE=\'' . $pos["File"] . '\',' .
'MASTER_LOG_POS=' . $pos["Position"] . ';', $link
);
if ($start) {
PMA_Replication_Slave_control("START", null, $link);
}
return $out;
}
/**
* This function provides connection to remote mysql server
*
* @param string $user mysql username
* @param string $password password for the user
* @param string $host mysql server's hostname or IP
* @param int $port mysql remote port
* @param string $socket path to unix socket
*
* @return mixed $link mysql link on success
*/
function PMA_Replication_connectToMaster(
$user, $password, $host = null, $port = null, $socket = null
) {
$server = array();
$server['user'] = $user;
$server['password'] = $password;
$server["host"] = Core::sanitizeMySQLHost($host);
$server["port"] = $port;
$server["socket"] = $socket;
// 5th parameter set to true means that it's an auxiliary connection
// and we must not go back to login page if it fails
return $GLOBALS['dbi']->connect(databaseinterface::CONNECT_AUXILIARY, $server);
}
/**
* Fetches position and file of current binary log on master
*
* @param mixed $link mysql link
*
* @return array an array containing File and Position in MySQL replication
* on master server, useful for PMA_Replication_Slave_changeMaster
*/
function PMA_Replication_Slave_binLogMaster($link = null)
{
$data = $GLOBALS['dbi']->fetchResult('SHOW MASTER STATUS', null, null, $link);
$output = array();
if (! empty($data)) {
$output["File"] = $data[0]["File"];
$output["Position"] = $data[0]["Position"];
}
return $output;
}

File diff suppressed because it is too large Load Diff

View File

@ -1,435 +0,0 @@
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* functions for displaying the sql query form
*
* @usedby server_sql.php
* @usedby db_sql.php
* @usedby tbl_sql.php
* @usedby tbl_structure.php
* @usedby tbl_tracking.php
* @package PhpMyAdmin
*/
use PhpMyAdmin\Encoding;
use PhpMyAdmin\Url;
use PhpMyAdmin\Bookmark;
if (! defined('PHPMYADMIN')) {
exit;
}
/**
* return HTML for the sql query boxes
*
* @param boolean|string $query query to display in the textarea
* or true to display last executed
* @param boolean|string $display_tab sql|full|false
* what part to display
* false if not inside querywindow
* @param string $delimiter delimiter
*
* @return string
*
* @usedby server_sql.php
* @usedby db_sql.php
* @usedby tbl_sql.php
* @usedby tbl_structure.php
* @usedby tbl_tracking.php
*/
function PMA_getHtmlForSqlQueryForm(
$query = true, $display_tab = false, $delimiter = ';'
) {
$html = '';
if (! $display_tab) {
$display_tab = 'full';
}
// query to show
if (true === $query) {
$query = $GLOBALS['sql_query'];
}
// set enctype to multipart for file uploads
if ($GLOBALS['is_upload']) {
$enctype = ' enctype="multipart/form-data"';
} else {
$enctype = '';
}
$table = '';
$db = '';
if (strlen($GLOBALS['db']) === 0) {
// prepare for server related
$goto = empty($GLOBALS['goto']) ?
'server_sql.php' : $GLOBALS['goto'];
} elseif (strlen($GLOBALS['table']) === 0) {
// prepare for db related
$db = $GLOBALS['db'];
$goto = empty($GLOBALS['goto']) ?
'db_sql.php' : $GLOBALS['goto'];
} else {
$table = $GLOBALS['table'];
$db = $GLOBALS['db'];
$goto = empty($GLOBALS['goto']) ?
'tbl_sql.php' : $GLOBALS['goto'];
}
// start output
$html .= '<form method="post" action="import.php" ' . $enctype;
$html .= ' class="ajax lock-page"';
$html .= ' id="sqlqueryform" name="sqlform">' . "\n";
$html .= '<input type="hidden" name="is_js_confirmed" value="0" />'
. "\n" . Url::getHiddenInputs($db, $table) . "\n"
. '<input type="hidden" name="pos" value="0" />' . "\n"
. '<input type="hidden" name="goto" value="'
. htmlspecialchars($goto) . '" />' . "\n"
. '<input type="hidden" name="message_to_show" value="'
. __('Your SQL query has been executed successfully.') . '" />'
. "\n" . '<input type="hidden" name="prev_sql_query" value="'
. htmlspecialchars($query) . '" />' . "\n";
// display querybox
if ($display_tab === 'full' || $display_tab === 'sql') {
$html .= PMA_getHtmlForSqlQueryFormInsert(
$query, $delimiter
);
}
// Bookmark Support
if ($display_tab === 'full') {
$cfgBookmark = Bookmark::getParams();
if ($cfgBookmark) {
$html .= PMA_getHtmlForSqlQueryFormBookmark();
}
}
// Japanese encoding setting
if (Encoding::canConvertKanji()) {
$html .= Encoding::kanjiEncodingForm();
}
$html .= '</form>' . "\n";
// print an empty div, which will be later filled with
// the sql query results by ajax
$html .= '<div id="sqlqueryresultsouter"></div>';
return $html;
}
/**
* Get initial values for Sql Query Form Insert
*
* @param string $query query to display in the textarea
*
* @return array ($legend, $query, $columns_list)
*
* @usedby PMA_getHtmlForSqlQueryFormInsert()
*/
function PMA_initQueryForm($query)
{
$columns_list = array();
if (strlen($GLOBALS['db']) === 0) {
// prepare for server related
$legend = sprintf(
__('Run SQL query/queries on server “%s”'),
htmlspecialchars(
! empty($GLOBALS['cfg']['Servers'][$GLOBALS['server']]['verbose'])
? $GLOBALS['cfg']['Servers'][$GLOBALS['server']]['verbose']
: $GLOBALS['cfg']['Servers'][$GLOBALS['server']]['host']
)
);
} elseif (strlen($GLOBALS['table']) === 0) {
// prepare for db related
$db = $GLOBALS['db'];
// if you want navigation:
$tmp_db_link = '<a href="' . PhpMyAdmin\Util::getScriptNameForOption(
$GLOBALS['cfg']['DefaultTabDatabase'], 'database'
)
. Url::getCommon(array('db' => $db)) . '"';
$tmp_db_link .= '>'
. htmlspecialchars($db) . '</a>';
$legend = sprintf(__('Run SQL query/queries on database %s'), $tmp_db_link);
if (empty($query)) {
$query = PhpMyAdmin\Util::expandUserString(
$GLOBALS['cfg']['DefaultQueryDatabase'], 'backquote'
);
}
} else {
$db = $GLOBALS['db'];
$table = $GLOBALS['table'];
// Get the list and number of fields
// we do a try_query here, because we could be in the query window,
// trying to synchronize and the table has not yet been created
$columns_list = $GLOBALS['dbi']->getColumns(
$db, $GLOBALS['table'], null, true
);
$tmp_tbl_link = '<a href="' . PhpMyAdmin\Util::getScriptNameForOption(
$GLOBALS['cfg']['DefaultTabTable'], 'table'
) . Url::getCommon(array('db' => $db, 'table' => $table)) . '" >';
$tmp_tbl_link .= htmlspecialchars($db)
. '.' . htmlspecialchars($table) . '</a>';
$legend = sprintf(__('Run SQL query/queries on table %s'), $tmp_tbl_link);
if (empty($query)) {
$query = PhpMyAdmin\Util::expandUserString(
$GLOBALS['cfg']['DefaultQueryTable'], 'backquote'
);
}
}
$legend .= ': ' . PhpMyAdmin\Util::showMySQLDocu('SELECT');
return array($legend, $query, $columns_list);
}
/**
* return HTML for Sql Query Form Insert
*
* @param string $query query to display in the textarea
* @param string $delimiter default delimiter to use
*
* @return string
*
* @usedby PMA_getHtmlForSqlQueryForm()
*/
function PMA_getHtmlForSqlQueryFormInsert(
$query = '', $delimiter = ';'
) {
// enable auto select text in textarea
if ($GLOBALS['cfg']['TextareaAutoSelect']) {
$auto_sel = ' onclick="selectContent(this, sql_box_locked, true);"';
} else {
$auto_sel = '';
}
$locking = '';
$height = $GLOBALS['cfg']['TextareaRows'] * 2;
list($legend, $query, $columns_list) = PMA_initQueryForm($query);
if (! empty($columns_list)) {
$sqlquerycontainer_id = 'sqlquerycontainer';
} else {
$sqlquerycontainer_id = 'sqlquerycontainerfull';
}
$html = '<a id="querybox"></a>'
. '<div id="queryboxcontainer">'
. '<fieldset id="queryboxf">';
$html .= '<legend>' . $legend . '</legend>';
$html .= '<div id="queryfieldscontainer">';
$html .= '<div id="' . $sqlquerycontainer_id . '">'
. '<textarea tabindex="100" name="sql_query" id="sqlquery"'
. ' cols="' . $GLOBALS['cfg']['TextareaCols'] . '"'
. ' rows="' . $height . '"'
. $auto_sel . $locking . '>'
. htmlspecialchars($query)
. '</textarea>';
$html .= '<div id="querymessage"></div>';
// Add buttons to generate query easily for
// select all, single select, insert, update and delete
if (! empty($columns_list)) {
$html .= '<input type="button" value="SELECT *" id="selectall"'
. ' class="button sqlbutton" />';
$html .= '<input type="button" value="SELECT" id="select"'
. ' class="button sqlbutton" />';
$html .= '<input type="button" value="INSERT" id="insert"'
. ' class="button sqlbutton" />';
$html .= '<input type="button" value="UPDATE" id="update"'
. ' class="button sqlbutton" />';
$html .= '<input type="button" value="DELETE" id="delete"'
. ' class="button sqlbutton" />';
}
$html .= '<input type="button" value="' . __('Clear') . '" id="clear"'
. ' class="button sqlbutton" />';
if ($GLOBALS['cfg']['CodemirrorEnable']) {
$html .= '<input type="button" value="' . __('Format') . '" id="format"'
. ' class="button sqlbutton" />';
}
$html .= '<input type="button" value="' . __('Get auto-saved query')
. '" id="saved" class="button sqlbutton" />';
// parameter binding
$html .= '<div>';
$html .= '<input type="checkbox" name="parameterized" id="parameterized" />';
$html .= '<label for="parameterized">' . __('Bind parameters') . '</label>';
$html .= PhpMyAdmin\Util::showDocu('faq', 'faq6-40');
$html .= '<div id="parametersDiv"></div>';
$html .= '</div>';
$html .= '</div>' . "\n";
if (! empty($columns_list)) {
$html .= '<div id="tablefieldscontainer">'
. '<label>' . __('Columns') . '</label>'
. '<select id="tablefields" name="dummy" '
. 'size="' . ($GLOBALS['cfg']['TextareaRows'] - 2) . '" '
. 'multiple="multiple" ondblclick="insertValueQuery()">';
foreach ($columns_list as $field) {
$html .= '<option value="'
. PhpMyAdmin\Util::backquote(htmlspecialchars($field['Field']))
. '"';
if (isset($field['Field'])
&& strlen($field['Field']) > 0
&& isset($field['Comment'])
) {
$html .= ' title="' . htmlspecialchars($field['Comment']) . '"';
}
$html .= '>' . htmlspecialchars($field['Field']) . '</option>' . "\n";
}
$html .= '</select>'
. '<div id="tablefieldinsertbuttoncontainer">';
if (PhpMyAdmin\Util::showIcons('ActionLinksMode')) {
$html .= '<input type="button" class="button" name="insert"'
. ' value="&lt;&lt;" onclick="insertValueQuery()"'
. ' title="' . __('Insert') . '" />';
} else {
$html .= '<input type="button" class="button" name="insert"'
. ' value="' . __('Insert') . '"'
. ' onclick="insertValueQuery()" />';
}
$html .= '</div>' . "\n"
. '</div>' . "\n";
}
$html .= '<div class="clearfloat"></div>' . "\n";
$html .= '</div>' . "\n";
$cfgBookmark = Bookmark::getParams();
if ($cfgBookmark) {
$html .= '<div id="bookmarkoptions">';
$html .= '<div class="formelement">';
$html .= '<label for="bkm_label">'
. __('Bookmark this SQL query:') . '</label>';
$html .= '<input type="text" name="bkm_label" id="bkm_label"'
. ' tabindex="110" value="" />';
$html .= '</div>';
$html .= '<div class="formelement">';
$html .= '<input type="checkbox" name="bkm_all_users" tabindex="111"'
. ' id="id_bkm_all_users" value="true" />';
$html .= '<label for="id_bkm_all_users">'
. __('Let every user access this bookmark') . '</label>';
$html .= '</div>';
$html .= '<div class="formelement">';
$html .= '<input type="checkbox" name="bkm_replace" tabindex="112"'
. ' id="id_bkm_replace" value="true" />';
$html .= '<label for="id_bkm_replace">'
. __('Replace existing bookmark of same name') . '</label>';
$html .= '</div>';
$html .= '</div>';
}
$html .= '<div class="clearfloat"></div>' . "\n";
$html .= '</fieldset>' . "\n"
. '</div>' . "\n";
$html .= '<fieldset id="queryboxfooter" class="tblFooters">' . "\n";
$html .= '<div class="formelement">' . "\n";
$html .= '</div>' . "\n";
$html .= '<div class="formelement">';
$html .= '<label for="id_sql_delimiter">[ ' . __('Delimiter')
. '</label>' . "\n";
$html .= '<input type="text" name="sql_delimiter" tabindex="131" size="3" '
. 'value="' . $delimiter . '" '
. 'id="id_sql_delimiter" /> ]';
$html .= '</div>';
$html .= '<div class="formelement">';
$html .= '<input type="checkbox" name="show_query" value="1" '
. 'id="checkbox_show_query" tabindex="132" checked="checked" />'
. '<label for="checkbox_show_query">' . __('Show this query here again')
. '</label>';
$html .= '</div>';
$html .= '<div class="formelement">';
$html .= '<input type="checkbox" name="retain_query_box" value="1" '
. 'id="retain_query_box" tabindex="133" '
. ($GLOBALS['cfg']['RetainQueryBox'] === false
? '' : ' checked="checked"')
. ' />'
. '<label for="retain_query_box">' . __('Retain query box')
. '</label>';
$html .= '</div>';
$html .= '<div class="formelement">';
$html .= '<input type="checkbox" name="rollback_query" value="1" '
. 'id="rollback_query" tabindex="134" />'
. '<label for="rollback_query">' . __('Rollback when finished')
. '</label>';
$html .= '</div>';
// Disable/Enable foreign key checks
$html .= '<div class="formelement">';
$html .= PhpMyAdmin\Util::getFKCheckbox();
$html .= '</div>';
$html .= '<input type="submit" id="button_submit_query" name="SQL"';
$html .= ' tabindex="200" value="' . __('Go') . '" />' . "\n";
$html .= '<div class="clearfloat"></div>' . "\n";
$html .= '</fieldset>' . "\n";
return $html;
}
/**
* return HTML for sql Query Form Bookmark
*
* @return string|null
*
* @usedby PMA_getHtmlForSqlQueryForm()
*/
function PMA_getHtmlForSqlQueryFormBookmark()
{
$bookmark_list = Bookmark::getList($GLOBALS['db']);
if (empty($bookmark_list) || count($bookmark_list) < 1) {
return null;
}
$html = '<fieldset id="fieldsetBookmarkOptions">';
$html .= '<legend>';
$html .= __('Bookmarked SQL query') . '</legend>' . "\n";
$html .= '<div class="formelement">';
$html .= '<select name="id_bookmark" id="id_bookmark">' . "\n";
$html .= '<option value="">&nbsp;</option>' . "\n";
foreach ($bookmark_list as $bookmark) {
$html .= '<option value="' . htmlspecialchars($bookmark->getId()) . '"'
. ' data-varcount="' . $bookmark->getVariableCount()
. '">'
. htmlspecialchars($bookmark->getLabel())
. (empty($bookmark->getUser()) ? (' (' . __('shared') . ')') : '')
. '</option>' . "\n";
}
// &nbsp; is required for correct display with styles/line height
$html .= '</select>&nbsp;' . "\n";
$html .= '</div>' . "\n";
$html .= '<div class="formelement">' . "\n";
$html .= '<input type="radio" name="action_bookmark" value="0"'
. ' id="radio_bookmark_exe" checked="checked" />'
. '<label for="radio_bookmark_exe">' . __('Submit')
. '</label>' . "\n";
$html .= '<input type="radio" name="action_bookmark" value="1"'
. ' id="radio_bookmark_view" />'
. '<label for="radio_bookmark_view">' . __('View only')
. '</label>' . "\n";
$html .= '<input type="radio" name="action_bookmark" value="2"'
. ' id="radio_bookmark_del" />'
. '<label for="radio_bookmark_del">' . __('Delete')
. '</label>' . "\n";
$html .= '</div>' . "\n";
$html .= '<div class="clearfloat"></div>' . "\n";
$html .= '<div class="formelement hide">' . "\n";
$html .= __('Variables');
$html .= PhpMyAdmin\Util::showDocu('faq', 'faqbookmark');
$html .= '<div id="bookmark_variables"></div>';
$html .= '</div>' . "\n";
$html .= '</fieldset>' . "\n";
$html .= '<fieldset id="fieldsetBookmarkOptionsFooter" class="tblFooters">';
$html .= '<input type="submit" name="SQL" id="button_submit_bookmark" value="'
. __('Go') . '" />';
$html .= '<div class="clearfloat"></div>' . "\n";
$html .= '</fieldset>' . "\n";
return $html;
}

View File

@ -22,8 +22,6 @@ require_once 'libraries/common.inc.php';
*/
$cfgRelation = Relation::getRelationsParam();
require_once 'libraries/pmd_common.php';
if (! isset($_REQUEST['export_type'])) {
PhpMyAdmin\Util::checkParameters(array('export_type'));
}

View File

@ -5,6 +5,8 @@
*
* @package PhpMyAdmin
*/
use PhpMyAdmin\ReplicationGui;
use PhpMyAdmin\Response;
use PhpMyAdmin\Server\Common;
@ -13,9 +15,7 @@ use PhpMyAdmin\Server\Common;
*/
require_once 'libraries/common.inc.php';
require_once 'libraries/server_common.inc.php';
require_once 'libraries/replication.inc.php';
require_once 'libraries/replication_gui.lib.php';
/**
* Does the common work
@ -46,7 +46,7 @@ if (isset($_REQUEST['url_params']) && is_array($_REQUEST['url_params'])) {
/**
* Handling control requests
*/
PMA_handleControlRequest();
ReplicationGui::handleControlRequest();
/**
* start output
@ -55,19 +55,19 @@ $response->addHTML('<div id="replication">');
$response->addHTML(Common::getHtmlForSubPageHeader('replication'));
// Display error messages
$response->addHTML(PMA_getHtmlForErrorMessage());
$response->addHTML(ReplicationGui::getHtmlForErrorMessage());
if ($GLOBALS['replication_info']['master']['status']) {
$response->addHTML(PMA_getHtmlForMasterReplication());
$response->addHTML(ReplicationGui::getHtmlForMasterReplication());
} elseif (! isset($_REQUEST['mr_configure'])
&& ! isset($_REQUEST['repl_clear_scr'])
) {
$response->addHTML(PMA_getHtmlForNotServerReplication());
$response->addHTML(ReplicationGui::getHtmlForNotServerReplication());
}
if (isset($_REQUEST['mr_configure'])) {
// Render the 'Master configuration' section
$response->addHTML(PMA_getHtmlForMasterConfiguration());
$response->addHTML(ReplicationGui::getHtmlForMasterConfiguration());
exit;
}
@ -76,12 +76,12 @@ $response->addHTML('</div>');
if (! isset($_REQUEST['repl_clear_scr'])) {
// Render the 'Slave configuration' section
$response->addHTML(
PMA_getHtmlForSlaveConfiguration(
ReplicationGui::getHtmlForSlaveConfiguration(
$GLOBALS['replication_info']['slave']['status'],
$server_slave_replication
)
);
}
if (isset($_REQUEST['sl_configure'])) {
$response->addHTML(PMA_getHtmlForReplicationChangeMaster("slave_changemaster"));
$response->addHTML(ReplicationGui::getHtmlForReplicationChangeMaster("slave_changemaster"));
}

View File

@ -7,6 +7,7 @@
*/
use PhpMyAdmin\Config\PageSettings;
use PhpMyAdmin\Response;
use PhpMyAdmin\SqlQueryForm;
/**
*
@ -26,9 +27,8 @@ $scripts->addFile('vendor/jquery/jquery.uitablefilter.js');
$scripts->addFile('sql.js');
require_once 'libraries/server_common.inc.php';
require_once 'libraries/sql_query_form.lib.php';
/**
* Query box, bookmark, insert data from textfile
*/
$response->addHTML(PMA_getHtmlForSqlQueryForm());
$response->addHTML(SqlQueryForm::getHtml());

View File

@ -18,7 +18,6 @@ require_once 'libraries/server_common.inc.php';
* Replication library
*/
require_once 'libraries/replication.inc.php';
require_once 'libraries/replication_gui.lib.php';
/**
* start output

View File

@ -13,7 +13,6 @@ use PhpMyAdmin\Server\Status\Data;
require_once 'libraries/common.inc.php';
require_once 'libraries/replication.inc.php';
require_once 'libraries/replication_gui.lib.php';
$serverStatusData = new Data();

View File

@ -13,7 +13,6 @@ use PhpMyAdmin\Response;
require_once 'libraries/common.inc.php';
require_once 'libraries/server_common.inc.php';
require_once 'libraries/replication.inc.php';
require_once 'libraries/replication_gui.lib.php';
$response = Response::getInstance();

View File

@ -17,7 +17,6 @@ require_once 'libraries/server_common.inc.php';
* Replication library
*/
require_once 'libraries/replication.inc.php';
require_once 'libraries/replication_gui.lib.php';
$serverStatusData = new Data();
$response = Response::getInstance();

View File

@ -15,7 +15,6 @@ use PhpMyAdmin\Server\Status\Queries;
require_once 'libraries/common.inc.php';
require_once 'libraries/server_common.inc.php';
require_once 'libraries/replication.inc.php';
require_once 'libraries/replication_gui.lib.php';
$serverStatusData = new Data();

View File

@ -14,7 +14,6 @@ use PhpMyAdmin\Server\Status\Variables;
require_once 'libraries/common.inc.php';
require_once 'libraries/server_common.inc.php';
require_once 'libraries/replication.inc.php';
require_once 'libraries/replication_gui.lib.php';
/**
* flush status variables if requested

View File

@ -7,6 +7,7 @@
*/
use PhpMyAdmin\Config\PageSettings;
use PhpMyAdmin\Response;
use PhpMyAdmin\SqlQueryForm;
/**
*
@ -28,8 +29,6 @@ $scripts->addFile('sql.js');
require 'libraries/tbl_common.inc.php';
$url_query .= '&amp;goto=tbl_sql.php&amp;back=tbl_sql.php';
require_once 'libraries/sql_query_form.lib.php';
$err_url = 'tbl_sql.php' . $err_url;
// After a syntax error, we return to this script
// with the typed query in the textarea.
@ -40,7 +39,7 @@ $back = 'tbl_sql.php';
* Query box, bookmark, insert data from textfile
*/
$response->addHTML(
PMA_getHtmlForSqlQueryForm(
SqlQueryForm::getHtml(
true, false,
isset($_REQUEST['delimiter'])
? htmlspecialchars($_REQUEST['delimiter'])

View File

@ -1,17 +1,22 @@
<?php
/**
* Tests for libraries/pmd_common.php
* Tests for PhpMyAdmin\PmdCommon
*
* @package PhpMyAdmin-test
*/
namespace PhpMyAdmin\Tests;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\PmdCommon;
use PhpMyAdmin\Relation;
use PHPUnit_Framework_TestCase as TestCase;
/**
* Tests for libraries/pmd_common.php
* Tests for PhpMyAdmin\PmdCommon
*
* @package PhpMyAdmin-test
*/
class PMA_PMD_CommonTest extends PHPUnit_Framework_TestCase
class PmdCommonTest extends TestCase
{
/**
* Setup for test cases
@ -33,13 +38,10 @@ class PMA_PMD_CommonTest extends PHPUnit_Framework_TestCase
)
)
);
include_once 'libraries/pmd_common.php';
}
/**
* Test for PMA_getTablePositions()
* Test for PmdCommon::getTablePositions()
*
* @return void
*/
@ -57,25 +59,25 @@ class PMA_PMD_CommonTest extends PHPUnit_Framework_TestCase
->method('fetchResult')
->with(
"
SELECT CONCAT_WS('.', `db_name`, `table_name`) AS `name`,
`x` AS `X`,
`y` AS `Y`,
1 AS `V`,
1 AS `H`
FROM `pmadb`.`table_coords`
WHERE pdf_page_number = " . $pg,
SELECT CONCAT_WS('.', `db_name`, `table_name`) AS `name`,
`x` AS `X`,
`y` AS `Y`,
1 AS `V`,
1 AS `H`
FROM `pmadb`.`table_coords`
WHERE pdf_page_number = " . $pg,
'name',
null,
2,
PhpMyAdmin\DatabaseInterface::QUERY_STORE
DatabaseInterface::QUERY_STORE
);
$GLOBALS['dbi'] = $dbi;
PMA_getTablePositions($pg);
PmdCommon::getTablePositions($pg);
}
/**
* Test for PMA_getPageName()
* Test for PmdCommon::getPageName()
*
* @return void
*/
@ -98,18 +100,18 @@ class PMA_PMD_CommonTest extends PHPUnit_Framework_TestCase
null,
null,
2,
PhpMyAdmin\DatabaseInterface::QUERY_STORE
DatabaseInterface::QUERY_STORE
)
->will($this->returnValue(array($pageName)));
$GLOBALS['dbi'] = $dbi;
$result = PMA_getPageName($pg);
$result = PmdCommon::getPageName($pg);
$this->assertEquals($pageName, $result);
}
/**
* Test for PMA_deletePage()
* Test for PmdCommon::deletePage()
*
* @return void
*/
@ -132,7 +134,7 @@ class PMA_PMD_CommonTest extends PHPUnit_Framework_TestCase
$GLOBALS['dbi'] = $dbi;
$result = PMA_deletePage($pg);
$result = PmdCommon::deletePage($pg);
$this->assertEquals(true, $result);
}
@ -160,7 +162,7 @@ class PMA_PMD_CommonTest extends PHPUnit_Framework_TestCase
null,
null,
2,
PhpMyAdmin\DatabaseInterface::QUERY_STORE
DatabaseInterface::QUERY_STORE
)
->will($this->returnValue(array($default_pg)));
$dbi->expects($this->any())->method('escapeString')
@ -168,7 +170,7 @@ class PMA_PMD_CommonTest extends PHPUnit_Framework_TestCase
$GLOBALS['dbi'] = $dbi;
$result = PMA_getDefaultPage($db);
$result = PmdCommon::getDefaultPage($db);
$this->assertEquals($default_pg, $result);
}
@ -194,7 +196,7 @@ class PMA_PMD_CommonTest extends PHPUnit_Framework_TestCase
null,
null,
2,
PhpMyAdmin\DatabaseInterface::QUERY_STORE
DatabaseInterface::QUERY_STORE
)
->will($this->returnValue(array()));
$dbi->expects($this->any())->method('escapeString')
@ -202,7 +204,7 @@ class PMA_PMD_CommonTest extends PHPUnit_Framework_TestCase
$GLOBALS['dbi'] = $dbi;
$result = PMA_getDefaultPage($db);
$result = PmdCommon::getDefaultPage($db);
$this->assertEquals(-1, $result);
}
@ -229,7 +231,7 @@ class PMA_PMD_CommonTest extends PHPUnit_Framework_TestCase
null,
null,
2,
PhpMyAdmin\DatabaseInterface::QUERY_STORE
DatabaseInterface::QUERY_STORE
)
->will($this->returnValue(array($default_pg)));
$dbi->expects($this->any())->method('escapeString')
@ -237,7 +239,7 @@ class PMA_PMD_CommonTest extends PHPUnit_Framework_TestCase
$GLOBALS['dbi'] = $dbi;
$result = PMA_getLoadingPage($db);
$result = PmdCommon::getLoadingPage($db);
$this->assertEquals($default_pg, $result);
}
@ -266,7 +268,7 @@ class PMA_PMD_CommonTest extends PHPUnit_Framework_TestCase
$GLOBALS['dbi'] = $dbi;
$result = PMA_getLoadingPage($db);
$result = PmdCommon::getLoadingPage($db);
$this->assertEquals($first_pg, $result);
}
}

View File

@ -1,28 +1,29 @@
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* tests for replication_gui.lib.php
* tests for PhpMyAdmin\ReplicationGui
*
* @package PhpMyAdmin-test
*/
namespace PhpMyAdmin\Tests;
use PhpMyAdmin\ReplicationGui;
use PhpMyAdmin\Theme;
use PHPUnit_Framework_TestCase as TestCase;
/*
* Include to test.
*/
use PhpMyAdmin\Theme;
* Include to test.
*/
require_once 'libraries/replication.inc.php';
require_once 'libraries/replication_gui.lib.php';
/**
* PMA_Serverreplication_Test class
* PhpMyAdmin\Tests\ReplicationGuiTest class
*
* this class is for testing replication_gui.lib.php functions
* this class is for testing PhpMyAdmin\ReplicationGui methods
*
* @package PhpMyAdmin-test
*/
class PMA_ServerReplication_Test extends PHPUnit_Framework_TestCase
class ReplicationGuiTest extends TestCase
{
/**
* Prepares environment for the test.
@ -92,7 +93,7 @@ class PMA_ServerReplication_Test extends PHPUnit_Framework_TestCase
}
/**
* Test for PMA_getHtmlForMasterReplication
* Test for ReplicationGui::getHtmlForMasterReplication
*
* @return void
* @group medium
@ -108,7 +109,7 @@ class PMA_ServerReplication_Test extends PHPUnit_Framework_TestCase
$strReplicationStatus_master = null;
//Call the test function
$html = PMA_getHtmlForMasterReplication();
$html = ReplicationGui::getHtmlForMasterReplication();
//validate 1: Master replication
$this->assertContains(
@ -120,7 +121,7 @@ class PMA_ServerReplication_Test extends PHPUnit_Framework_TestCase
$html
);
//validate 2: PMA_getHtmlForReplicationStatusTable
//validate 2: ReplicationGui::getHtmlForReplicationStatusTable
$this->assertContains(
'<div id="replication_master_section"',
$html
@ -140,7 +141,7 @@ class PMA_ServerReplication_Test extends PHPUnit_Framework_TestCase
$html
);
//validate 3: PMA_getHtmlForReplicationSlavesTable
//validate 3: ReplicationGui::getHtmlForReplicationSlavesTable
$this->assertContains(
'replication_slaves_section',
$html
@ -194,14 +195,14 @@ class PMA_ServerReplication_Test extends PHPUnit_Framework_TestCase
}
/**
* Test for PMA_getHtmlForNotServerReplication
* Test for ReplicationGui::getHtmlForNotServerReplication
*
* @return void
*/
public function testPMAGetHtmlForNotServerReplication()
{
//Call the test function
$html = PMA_getHtmlForNotServerReplication();
$html = ReplicationGui::getHtmlForNotServerReplication();
$this->assertContains(
'<legend>Master replication</legend>',
@ -214,7 +215,7 @@ class PMA_ServerReplication_Test extends PHPUnit_Framework_TestCase
}
/**
* Test for PMA_getHtmlForSlaveConfiguration
* Test for ReplicationGui::getHtmlForSlaveConfiguration
*
* @return void
*/
@ -223,7 +224,7 @@ class PMA_ServerReplication_Test extends PHPUnit_Framework_TestCase
global $server_slave_replication;
//Call the test function
$html = PMA_getHtmlForSlaveConfiguration(
$html = ReplicationGui::getHtmlForSlaveConfiguration(
true,
$server_slave_replication
);
@ -267,14 +268,14 @@ class PMA_ServerReplication_Test extends PHPUnit_Framework_TestCase
}
/**
* Test for PMA_getHtmlForReplicationChangeMaster
* Test for ReplicationGui::getHtmlForReplicationChangeMaster
*
* @return void
*/
public function testPMAGetHtmlForReplicationChangeMaster()
{
//Call the test function
$html = PMA_getHtmlForReplicationChangeMaster("slave_changemaster");
$html = ReplicationGui::getHtmlForReplicationChangeMaster("slave_changemaster");
$this->assertContains(
'<form method="post" action="server_replication.php">',

View File

@ -1,32 +1,31 @@
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* tests for sql_query_form.lib.php
* tests for PhpMyAdmin\SqlQueryForm
*
* @package PhpMyAdmin-test
*/
namespace PhpMyAdmin\Tests;
use PhpMyAdmin\Core;
use PhpMyAdmin\Encoding;
use PhpMyAdmin\SqlQueryForm;
use PhpMyAdmin\Theme;
use PhpMyAdmin\Url;
use PhpMyAdmin\Util;
use PHPUnit_Framework_TestCase as TestCase;
//the following definition should be used globally
$GLOBALS['server'] = 0;
/*
* Include to test.
*/
require_once 'libraries/sql_query_form.lib.php';
/**
* class PMA_SqlQueryForm_Test
* PhpMyAdmin\Tests\SqlQueryFormTest class
*
* this class is for testing sql_query_form.lib.php functions
* this class is for testing PhpMyAdmin\SqlQueryForm methods
*
* @package PhpMyAdmin-test
*/
class PMA_SqlQueryForm_Test extends PHPUnit_Framework_TestCase
class SqlQueryFormTest extends TestCase
{
/**
* Test for setUp
@ -98,7 +97,7 @@ class PMA_SqlQueryForm_Test extends PHPUnit_Framework_TestCase
}
/**
* Test for PMA_getHtmlForSqlQueryFormInsert
* Test for SqlQueryForm::getHtmlForInsert
*
* @return void
*/
@ -106,7 +105,7 @@ class PMA_SqlQueryForm_Test extends PHPUnit_Framework_TestCase
{
//Call the test function
$query = "select * from PMA";
$html = PMA_getHtmlForSqlQueryFormInsert($query);
$html = SqlQueryForm::getHtmlForInsert($query);
//validate 1: query
$this->assertContains(
@ -123,7 +122,7 @@ class PMA_SqlQueryForm_Test extends PHPUnit_Framework_TestCase
//validate 3: showMySQLDocu
$this->assertContains(
PhpMyAdmin\Util::showMySQLDocu('SELECT'),
Util::showMySQLDocu('SELECT'),
$html
);
@ -161,7 +160,7 @@ class PMA_SqlQueryForm_Test extends PHPUnit_Framework_TestCase
}
/**
* Test for PMA_getHtmlForSqlQueryForm
* Test for SqlQueryForm::getHtml
*
* @return void
*/
@ -171,7 +170,7 @@ class PMA_SqlQueryForm_Test extends PHPUnit_Framework_TestCase
$GLOBALS['is_upload'] = true;
$GLOBALS['lang'] = 'ja';
$query = "select * from PMA";
$html = PMA_getHtmlForSqlQueryForm($query);
$html = SqlQueryForm::getHtml($query);
//validate 1: query
$this->assertContains(