Update website

This commit is contained in:
Guilhem Lavaux 2025-02-11 21:30:02 +01:00
parent 0a686aeb9a
commit c4ffa0f6ee
4360 changed files with 1727 additions and 718385 deletions

View file

@ -1,169 +0,0 @@
<?php
/**
* Config Authentication plugin for phpMyAdmin
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Auth;
use PhpMyAdmin\Html\Generator;
use PhpMyAdmin\Plugins\AuthenticationPlugin;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Server\Select;
use PhpMyAdmin\Util;
use function __;
use function count;
use function defined;
use function sprintf;
use function trigger_error;
use const E_USER_NOTICE;
use const E_USER_WARNING;
/**
* Handles the config authentication method
*/
class AuthenticationConfig extends AuthenticationPlugin
{
/**
* Displays authentication form
*
* @return bool always true
*/
public function showLoginForm(): bool
{
$response = ResponseRenderer::getInstance();
if ($response->isAjax()) {
$response->setRequestStatus(false);
// reload_flag removes the token parameter from the URL and reloads
$response->addJSON('reload_flag', '1');
if (defined('TESTSUITE')) {
return true;
}
exit;
}
return true;
}
/**
* Gets authentication credentials
*
* @return bool always true
*/
public function readCredentials(): bool
{
if ($GLOBALS['token_provided'] && $GLOBALS['token_mismatch']) {
return false;
}
$this->user = $GLOBALS['cfg']['Server']['user'];
$this->password = $GLOBALS['cfg']['Server']['password'];
return true;
}
/**
* User is not allowed to login to MySQL -> authentication failed
*
* @param string $failure String describing why authentication has failed
*/
public function showFailure($failure): void
{
global $dbi;
parent::showFailure($failure);
$conn_error = $dbi->getError();
if (! $conn_error) {
$conn_error = __('Cannot connect: invalid settings.');
}
/* HTML header */
$response = ResponseRenderer::getInstance();
$response->getFooter()
->setMinimal();
$header = $response->getHeader();
$header->setBodyId('loginform');
$header->setTitle(__('Access denied!'));
$header->disableMenuAndConsole();
echo '<br><br>
<div class="text-center">
<h1>';
echo sprintf(__('Welcome to %s'), ' phpMyAdmin ');
echo '</h1>
</div>
<br>
<table class="table table-borderless text-start w-75 mx-auto">
<tr>
<td>';
if (isset($GLOBALS['allowDeny_forbidden']) && $GLOBALS['allowDeny_forbidden']) {
trigger_error(__('Access denied!'), E_USER_NOTICE);
} else {
// Check whether user has configured something
if ($GLOBALS['config']->sourceMtime == 0) {
echo '<p>' , sprintf(
__(
'You probably did not create a configuration file.'
. ' You might want to use the %1$ssetup script%2$s to'
. ' create one.'
),
'<a href="setup/">',
'</a>'
) , '</p>' , "\n";
} elseif (
! isset($GLOBALS['errno'])
|| (isset($GLOBALS['errno']) && $GLOBALS['errno'] != 2002)
&& $GLOBALS['errno'] != 2003
) {
// if we display the "Server not responding" error, do not confuse
// users by telling them they have a settings problem
// (note: it's true that they could have a badly typed host name,
// but anyway the current message tells that the server
// rejected the connection, which is not really what happened)
// 2002 is the error given by mysqli
// 2003 is the error given by mysql
trigger_error(
__(
'phpMyAdmin tried to connect to the MySQL server, and the'
. ' server rejected the connection. You should check the'
. ' host, username and password in your configuration and'
. ' make sure that they correspond to the information given'
. ' by the administrator of the MySQL server.'
),
E_USER_WARNING
);
}
echo Generator::mysqlDie($conn_error, '', true, '', false);
}
$GLOBALS['errorHandler']->dispUserErrors();
echo '</td>
</tr>
<tr>
<td>' , "\n";
echo '<a href="'
, Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabServer'], 'server')
, '" class="btn btn-primary mt-1 mb-1 disableAjax">'
, __('Retry to connect')
, '</a>' , "\n";
echo '</td>
</tr>' , "\n";
if (count($GLOBALS['cfg']['Servers']) > 1) {
// offer a chance to login to other servers if the current one failed
echo '<tr>' , "\n";
echo ' <td>' , "\n";
echo Select::render(true, true);
echo ' </td>' , "\n";
echo '</tr>' , "\n";
}
echo '</table>' , "\n";
if (! defined('TESTSUITE')) {
exit;
}
}
}

View file

@ -1,702 +0,0 @@
<?php
/**
* Cookie Authentication plugin for phpMyAdmin
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Auth;
use PhpMyAdmin\Config;
use PhpMyAdmin\Core;
use PhpMyAdmin\LanguageManager;
use PhpMyAdmin\Message;
use PhpMyAdmin\Plugins\AuthenticationPlugin;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Server\Select;
use PhpMyAdmin\Session;
use PhpMyAdmin\Url;
use PhpMyAdmin\Util;
use PhpMyAdmin\Utils\SessionCache;
use ReCaptcha;
use Throwable;
use function __;
use function array_keys;
use function base64_decode;
use function base64_encode;
use function count;
use function defined;
use function explode;
use function function_exists;
use function in_array;
use function ini_get;
use function intval;
use function is_array;
use function is_string;
use function json_decode;
use function json_encode;
use function mb_strlen;
use function mb_substr;
use function preg_match;
use function random_bytes;
use function session_id;
use function sodium_crypto_secretbox;
use function sodium_crypto_secretbox_open;
use function strlen;
use function time;
use const SODIUM_CRYPTO_SECRETBOX_KEYBYTES;
use const SODIUM_CRYPTO_SECRETBOX_NONCEBYTES;
/**
* Handles the cookie authentication method
*/
class AuthenticationCookie extends AuthenticationPlugin
{
/**
* Displays authentication form
*
* this function MUST exit/quit the application
*
* @global string $conn_error the last connection error
*/
public function showLoginForm(): bool
{
global $conn_error, $route;
$response = ResponseRenderer::getInstance();
/**
* When sending login modal after session has expired, send the
* new token explicitly with the response to update the token
* in all the forms having a hidden token.
*/
$session_expired = isset($_REQUEST['check_timeout']) || isset($_REQUEST['session_timedout']);
if (! $session_expired && $response->loginPage()) {
if (defined('TESTSUITE')) {
return true;
}
exit;
}
/**
* When sending login modal after session has expired, send the
* new token explicitly with the response to update the token
* in all the forms having a hidden token.
*/
if ($session_expired) {
$response->setRequestStatus(false);
$response->addJSON('new_token', $_SESSION[' PMA_token ']);
}
/**
* logged_in response parameter is used to check if the login,
* using the modal was successful after session expiration.
*/
if (isset($_REQUEST['session_timedout'])) {
$response->addJSON('logged_in', 0);
}
// No recall if blowfish secret is not configured as it would produce
// garbage
if ($GLOBALS['cfg']['LoginCookieRecall'] && ! empty($GLOBALS['cfg']['blowfish_secret'])) {
$default_user = $this->user;
$default_server = $GLOBALS['pma_auth_server'];
$hasAutocomplete = true;
} else {
$default_user = '';
$default_server = '';
$hasAutocomplete = false;
}
// wrap the login form in a div which overlays the whole page.
if ($session_expired) {
$loginHeader = $this->template->render('login/header', [
'add_class' => ' modal_form',
'session_expired' => 1,
]);
} else {
$loginHeader = $this->template->render('login/header', [
'add_class' => '',
'session_expired' => 0,
]);
}
$errorMessages = '';
// Show error message
if (! empty($conn_error)) {
$errorMessages = Message::rawError((string) $conn_error)->getDisplay();
} elseif (isset($_GET['session_expired']) && intval($_GET['session_expired']) == 1) {
$errorMessages = Message::rawError(
__('Your session has expired. Please log in again.')
)->getDisplay();
}
$languageManager = LanguageManager::getInstance();
$availableLanguages = [];
if (empty($GLOBALS['cfg']['Lang']) && $languageManager->hasChoice()) {
$availableLanguages = $languageManager->sortedLanguages();
}
$serversOptions = '';
$hasServers = count($GLOBALS['cfg']['Servers']) > 1;
if ($hasServers) {
$serversOptions = Select::render(false, false);
}
$_form_params = [];
if (isset($route)) {
$_form_params['route'] = $route;
}
if (strlen($GLOBALS['db'])) {
$_form_params['db'] = $GLOBALS['db'];
}
if (strlen($GLOBALS['table'])) {
$_form_params['table'] = $GLOBALS['table'];
}
$errors = '';
if ($GLOBALS['errorHandler']->hasDisplayErrors()) {
$errors = $GLOBALS['errorHandler']->getDispErrors();
}
// close the wrapping div tag, if the request is after session timeout
if ($session_expired) {
$loginFooter = $this->template->render('login/footer', ['session_expired' => 1]);
} else {
$loginFooter = $this->template->render('login/footer', ['session_expired' => 0]);
}
$configFooter = Config::renderFooter();
echo $this->template->render('login/form', [
'login_header' => $loginHeader,
'is_demo' => $GLOBALS['cfg']['DBG']['demo'],
'error_messages' => $errorMessages,
'available_languages' => $availableLanguages,
'is_session_expired' => $session_expired,
'has_autocomplete' => $hasAutocomplete,
'session_id' => session_id(),
'is_arbitrary_server_allowed' => $GLOBALS['cfg']['AllowArbitraryServer'],
'default_server' => $default_server,
'default_user' => $default_user,
'has_servers' => $hasServers,
'server_options' => $serversOptions,
'server' => $GLOBALS['server'],
'lang' => $GLOBALS['lang'],
'has_captcha' => ! empty($GLOBALS['cfg']['CaptchaApi'])
&& ! empty($GLOBALS['cfg']['CaptchaRequestParam'])
&& ! empty($GLOBALS['cfg']['CaptchaResponseParam'])
&& ! empty($GLOBALS['cfg']['CaptchaLoginPrivateKey'])
&& ! empty($GLOBALS['cfg']['CaptchaLoginPublicKey']),
'use_captcha_checkbox' => ($GLOBALS['cfg']['CaptchaMethod'] ?? '') === 'checkbox',
'captcha_api' => $GLOBALS['cfg']['CaptchaApi'],
'captcha_req' => $GLOBALS['cfg']['CaptchaRequestParam'],
'captcha_resp' => $GLOBALS['cfg']['CaptchaResponseParam'],
'captcha_key' => $GLOBALS['cfg']['CaptchaLoginPublicKey'],
'form_params' => $_form_params,
'errors' => $errors,
'login_footer' => $loginFooter,
'config_footer' => $configFooter,
]);
if (! defined('TESTSUITE')) {
exit;
}
return true;
}
/**
* Gets authentication credentials
*
* this function DOES NOT check authentication - it just checks/provides
* authentication credentials required to connect to the MySQL server
* usually with $dbi->connect()
*
* it returns false if something is missing - which usually leads to
* showLoginForm() which displays login form
*
* it returns true if all seems ok which usually leads to auth_set_user()
*
* it directly switches to showFailure() if user inactivity timeout is reached
*/
public function readCredentials(): bool
{
global $conn_error;
// Initialization
/**
* @global $GLOBALS['pma_auth_server'] the user provided server to
* connect to
*/
$GLOBALS['pma_auth_server'] = '';
$this->user = $this->password = '';
$GLOBALS['from_cookie'] = false;
if (isset($_POST['pma_username']) && strlen($_POST['pma_username']) > 0) {
// Verify Captcha if it is required.
if (
! empty($GLOBALS['cfg']['CaptchaApi'])
&& ! empty($GLOBALS['cfg']['CaptchaRequestParam'])
&& ! empty($GLOBALS['cfg']['CaptchaResponseParam'])
&& ! empty($GLOBALS['cfg']['CaptchaLoginPrivateKey'])
&& ! empty($GLOBALS['cfg']['CaptchaLoginPublicKey'])
) {
if (empty($_POST[$GLOBALS['cfg']['CaptchaResponseParam']])) {
$conn_error = __('Missing reCAPTCHA verification, maybe it has been blocked by adblock?');
return false;
}
$captchaSiteVerifyURL = $GLOBALS['cfg']['CaptchaSiteVerifyURL'] ?? '';
$captchaSiteVerifyURL = empty($captchaSiteVerifyURL) ? null : $captchaSiteVerifyURL;
if (function_exists('curl_init')) {
$reCaptcha = new ReCaptcha\ReCaptcha(
$GLOBALS['cfg']['CaptchaLoginPrivateKey'],
new ReCaptcha\RequestMethod\CurlPost(null, $captchaSiteVerifyURL)
);
} elseif (ini_get('allow_url_fopen')) {
$reCaptcha = new ReCaptcha\ReCaptcha(
$GLOBALS['cfg']['CaptchaLoginPrivateKey'],
new ReCaptcha\RequestMethod\Post($captchaSiteVerifyURL)
);
} else {
$reCaptcha = new ReCaptcha\ReCaptcha(
$GLOBALS['cfg']['CaptchaLoginPrivateKey'],
new ReCaptcha\RequestMethod\SocketPost(null, $captchaSiteVerifyURL)
);
}
// verify captcha status.
$resp = $reCaptcha->verify(
$_POST[$GLOBALS['cfg']['CaptchaResponseParam']],
Core::getIp()
);
// Check if the captcha entered is valid, if not stop the login.
if ($resp == null || ! $resp->isSuccess()) {
$codes = $resp->getErrorCodes();
if (in_array('invalid-json', $codes)) {
$conn_error = __('Failed to connect to the reCAPTCHA service!');
} else {
$conn_error = __('Entered captcha is wrong, try again!');
}
return false;
}
}
// The user just logged in
$this->user = Core::sanitizeMySQLUser($_POST['pma_username']);
$password = $_POST['pma_password'] ?? '';
if (strlen($password) >= 1000) {
$conn_error = __('Your password is too long. To prevent denial-of-service attacks, ' .
'phpMyAdmin restricts passwords to less than 1000 characters.');
return false;
}
$this->password = $password;
if ($GLOBALS['cfg']['AllowArbitraryServer'] && isset($_REQUEST['pma_servername'])) {
if ($GLOBALS['cfg']['ArbitraryServerRegexp']) {
$parts = explode(' ', $_REQUEST['pma_servername']);
if (count($parts) === 2) {
$tmp_host = $parts[0];
} else {
$tmp_host = $_REQUEST['pma_servername'];
}
$match = preg_match($GLOBALS['cfg']['ArbitraryServerRegexp'], $tmp_host);
if (! $match) {
$conn_error = __('You are not allowed to log in to this MySQL server!');
return false;
}
}
$GLOBALS['pma_auth_server'] = Core::sanitizeMySQLHost($_REQUEST['pma_servername']);
}
/* Secure current session on login to avoid session fixation */
Session::secure();
return true;
}
// At the end, try to set the $this->user
// and $this->password variables from cookies
// check cookies
$serverCookie = $GLOBALS['config']->getCookie('pmaUser-' . $GLOBALS['server']);
if (empty($serverCookie)) {
return false;
}
$value = $this->cookieDecrypt(
$serverCookie,
$this->getEncryptionSecret()
);
if ($value === null) {
return false;
}
$this->user = $value;
// user was never logged in since session start
if (empty($_SESSION['browser_access_time'])) {
return false;
}
// User inactive too long
$last_access_time = time() - $GLOBALS['cfg']['LoginCookieValidity'];
foreach ($_SESSION['browser_access_time'] as $key => $value) {
if ($value >= $last_access_time) {
continue;
}
unset($_SESSION['browser_access_time'][$key]);
}
// All sessions expired
if (empty($_SESSION['browser_access_time'])) {
SessionCache::remove('is_create_db_priv');
SessionCache::remove('is_reload_priv');
SessionCache::remove('db_to_create');
SessionCache::remove('dbs_where_create_table_allowed');
SessionCache::remove('dbs_to_test');
SessionCache::remove('db_priv');
SessionCache::remove('col_priv');
SessionCache::remove('table_priv');
SessionCache::remove('proc_priv');
$this->showFailure('no-activity');
if (! defined('TESTSUITE')) {
exit;
}
return false;
}
// check password cookie
$serverCookie = $GLOBALS['config']->getCookie('pmaAuth-' . $GLOBALS['server']);
if (empty($serverCookie)) {
return false;
}
$value = $this->cookieDecrypt(
$serverCookie,
$this->getSessionEncryptionSecret()
);
if ($value === null) {
return false;
}
$auth_data = json_decode($value, true);
if (! is_array($auth_data) || ! isset($auth_data['password'])) {
return false;
}
$this->password = $auth_data['password'];
if ($GLOBALS['cfg']['AllowArbitraryServer'] && ! empty($auth_data['server'])) {
$GLOBALS['pma_auth_server'] = $auth_data['server'];
}
$GLOBALS['from_cookie'] = true;
return true;
}
/**
* Set the user and password after last checkings if required
*
* @return bool always true
*/
public function storeCredentials(): bool
{
global $cfg;
if ($GLOBALS['cfg']['AllowArbitraryServer'] && ! empty($GLOBALS['pma_auth_server'])) {
/* Allow to specify 'host port' */
$parts = explode(' ', $GLOBALS['pma_auth_server']);
if (count($parts) === 2) {
$tmp_host = $parts[0];
$tmp_port = $parts[1];
} else {
$tmp_host = $GLOBALS['pma_auth_server'];
$tmp_port = '';
}
if ($cfg['Server']['host'] != $GLOBALS['pma_auth_server']) {
$cfg['Server']['host'] = $tmp_host;
if (! empty($tmp_port)) {
$cfg['Server']['port'] = $tmp_port;
}
}
unset($tmp_host, $tmp_port, $parts);
}
return parent::storeCredentials();
}
/**
* Stores user credentials after successful login.
*/
public function rememberCredentials(): void
{
global $route;
// Name and password cookies need to be refreshed each time
// Duration = one month for username
$this->storeUsernameCookie($this->user);
// Duration = as configured
// Do not store password cookie on password change as we will
// set the cookie again after password has been changed
if (! isset($_POST['change_pw'])) {
$this->storePasswordCookie($this->password);
}
// any parameters to pass?
$url_params = [];
if (isset($route)) {
$url_params['route'] = $route;
}
if (strlen($GLOBALS['db']) > 0) {
$url_params['db'] = $GLOBALS['db'];
}
if (strlen($GLOBALS['table']) > 0) {
$url_params['table'] = $GLOBALS['table'];
}
// user logged in successfully after session expiration
if (isset($_REQUEST['session_timedout'])) {
$response = ResponseRenderer::getInstance();
$response->addJSON('logged_in', 1);
$response->addJSON('success', 1);
$response->addJSON('new_token', $_SESSION[' PMA_token ']);
if (! defined('TESTSUITE')) {
exit;
}
return;
}
// Set server cookies if required (once per session) and, in this case,
// force reload to ensure the client accepts cookies
if ($GLOBALS['from_cookie']) {
return;
}
/**
* Clear user cache.
*/
Util::clearUserCache();
ResponseRenderer::getInstance()->disable();
Core::sendHeaderLocation(
'./index.php?route=/' . Url::getCommonRaw($url_params, '&'),
true
);
if (! defined('TESTSUITE')) {
exit;
}
}
/**
* Stores username in a cookie.
*
* @param string $username User name
*/
public function storeUsernameCookie($username): void
{
// Name and password cookies need to be refreshed each time
// Duration = one month for username
$GLOBALS['config']->setCookie(
'pmaUser-' . $GLOBALS['server'],
$this->cookieEncrypt(
$username,
$this->getEncryptionSecret()
)
);
}
/**
* Stores password in a cookie.
*
* @param string $password Password
*/
public function storePasswordCookie($password): void
{
$payload = ['password' => $password];
if ($GLOBALS['cfg']['AllowArbitraryServer'] && ! empty($GLOBALS['pma_auth_server'])) {
$payload['server'] = $GLOBALS['pma_auth_server'];
}
// Duration = as configured
$GLOBALS['config']->setCookie(
'pmaAuth-' . $GLOBALS['server'],
$this->cookieEncrypt(
(string) json_encode($payload),
$this->getSessionEncryptionSecret()
),
null,
(int) $GLOBALS['cfg']['LoginCookieStore']
);
}
/**
* User is not allowed to login to MySQL -> authentication failed
*
* prepares error message and switches to showLoginForm() which display the error
* and the login form
*
* this function MUST exit/quit the application,
* currently done by call to showLoginForm()
*
* @param string $failure String describing why authentication has failed
*/
public function showFailure($failure): void
{
global $conn_error;
parent::showFailure($failure);
// Deletes password cookie and displays the login form
$GLOBALS['config']->removeCookie('pmaAuth-' . $GLOBALS['server']);
$conn_error = $this->getErrorMessage($failure);
$response = ResponseRenderer::getInstance();
// needed for PHP-CGI (not need for FastCGI or mod-php)
$response->header('Cache-Control: no-store, no-cache, must-revalidate');
$response->header('Pragma: no-cache');
$this->showLoginForm();
}
/**
* Returns blowfish secret or generates one if needed.
*/
private function getEncryptionSecret(): string
{
/** @var mixed $key */
$key = $GLOBALS['cfg']['blowfish_secret'] ?? null;
if (! is_string($key)) {
return $this->getSessionEncryptionSecret();
}
$length = mb_strlen($key, '8bit');
if ($length === SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
return $key;
}
if ($length > SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
return mb_substr($key, 0, SODIUM_CRYPTO_SECRETBOX_KEYBYTES, '8bit');
}
return $this->getSessionEncryptionSecret();
}
/**
* Returns blowfish secret or generates one if needed.
*/
private function getSessionEncryptionSecret(): string
{
/** @var mixed $key */
$key = $_SESSION['encryption_key'] ?? null;
if (is_string($key) && mb_strlen($key, '8bit') === SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
return $key;
}
$key = random_bytes(SODIUM_CRYPTO_SECRETBOX_KEYBYTES);
$_SESSION['encryption_key'] = $key;
return $key;
}
public function cookieEncrypt(string $data, string $secret): string
{
try {
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$ciphertext = sodium_crypto_secretbox($data, $nonce, $secret);
} catch (Throwable $throwable) {
return '';
}
return base64_encode($nonce . $ciphertext);
}
public function cookieDecrypt(string $encryptedData, string $secret): ?string
{
$encrypted = base64_decode($encryptedData);
$nonce = mb_substr($encrypted, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, '8bit');
$ciphertext = mb_substr($encrypted, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit');
try {
$decrypted = sodium_crypto_secretbox_open($ciphertext, $nonce, $secret);
} catch (Throwable $throwable) {
return null;
}
if (! is_string($decrypted)) {
return null;
}
return $decrypted;
}
/**
* Callback when user changes password.
*
* @param string $password New password to set
*/
public function handlePasswordChange($password): void
{
$this->storePasswordCookie($password);
}
/**
* Perform logout
*/
public function logOut(): void
{
global $config;
// -> delete password cookie(s)
if ($GLOBALS['cfg']['LoginCookieDeleteAll']) {
foreach (array_keys($GLOBALS['cfg']['Servers']) as $key) {
$config->removeCookie('pmaAuth-' . $key);
if (! $config->issetCookie('pmaAuth-' . $key)) {
continue;
}
$config->removeCookie('pmaAuth-' . $key);
}
} else {
$cookieName = 'pmaAuth-' . $GLOBALS['server'];
$config->removeCookie($cookieName);
if ($config->issetCookie($cookieName)) {
$config->removeCookie($cookieName);
}
}
parent::logOut();
}
}

View file

@ -1,219 +0,0 @@
<?php
/**
* HTTP Authentication plugin for phpMyAdmin.
* NOTE: Requires PHP loaded as a Apache module.
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Auth;
use PhpMyAdmin\Config;
use PhpMyAdmin\Core;
use PhpMyAdmin\Message;
use PhpMyAdmin\Plugins\AuthenticationPlugin;
use PhpMyAdmin\ResponseRenderer;
use function __;
use function base64_decode;
use function defined;
use function hash_equals;
use function preg_replace;
use function sprintf;
use function strcmp;
use function strpos;
use function substr;
/**
* Handles the HTTP authentication methods
*/
class AuthenticationHttp extends AuthenticationPlugin
{
/**
* Displays authentication form and redirect as necessary
*
* @return bool always true (no return indeed)
*/
public function showLoginForm(): bool
{
$response = ResponseRenderer::getInstance();
if ($response->isAjax()) {
$response->setRequestStatus(false);
// reload_flag removes the token parameter from the URL and reloads
$response->addJSON('reload_flag', '1');
if (defined('TESTSUITE')) {
return true;
}
exit;
}
return $this->authForm();
}
/**
* Displays authentication form
*/
public function authForm(): bool
{
if (empty($GLOBALS['cfg']['Server']['auth_http_realm'])) {
if (empty($GLOBALS['cfg']['Server']['verbose'])) {
$server_message = $GLOBALS['cfg']['Server']['host'];
} else {
$server_message = $GLOBALS['cfg']['Server']['verbose'];
}
$realm_message = 'phpMyAdmin ' . $server_message;
} else {
$realm_message = $GLOBALS['cfg']['Server']['auth_http_realm'];
}
$response = ResponseRenderer::getInstance();
// remove non US-ASCII to respect RFC2616
$realm_message = preg_replace('/[^\x20-\x7e]/i', '', $realm_message);
$response->header('WWW-Authenticate: Basic realm="' . $realm_message . '"');
$response->setHttpResponseCode(401);
/* HTML header */
$footer = $response->getFooter();
$footer->setMinimal();
$header = $response->getHeader();
$header->setTitle(__('Access denied!'));
$header->disableMenuAndConsole();
$header->setBodyId('loginform');
$response->addHTML('<h1>');
$response->addHTML(sprintf(__('Welcome to %s'), ' phpMyAdmin'));
$response->addHTML('</h1>');
$response->addHTML('<h3>');
$response->addHTML(
Message::error(
__('Wrong username/password. Access denied.')
)->getDisplay()
);
$response->addHTML('</h3>');
$response->addHTML(Config::renderFooter());
if (! defined('TESTSUITE')) {
exit;
}
return false;
}
/**
* Gets authentication credentials
*/
public function readCredentials(): bool
{
// Grabs the $PHP_AUTH_USER variable
if (isset($GLOBALS['PHP_AUTH_USER'])) {
$this->user = $GLOBALS['PHP_AUTH_USER'];
}
if (empty($this->user)) {
if (Core::getenv('PHP_AUTH_USER')) {
$this->user = Core::getenv('PHP_AUTH_USER');
} elseif (Core::getenv('REMOTE_USER')) {
// CGI, might be encoded, see below
$this->user = Core::getenv('REMOTE_USER');
} elseif (Core::getenv('REDIRECT_REMOTE_USER')) {
// CGI, might be encoded, see below
$this->user = Core::getenv('REDIRECT_REMOTE_USER');
} elseif (Core::getenv('AUTH_USER')) {
// WebSite Professional
$this->user = Core::getenv('AUTH_USER');
} elseif (Core::getenv('HTTP_AUTHORIZATION')) {
// IIS, might be encoded, see below
$this->user = Core::getenv('HTTP_AUTHORIZATION');
} elseif (Core::getenv('Authorization')) {
// FastCGI, might be encoded, see below
$this->user = Core::getenv('Authorization');
}
}
// Grabs the $PHP_AUTH_PW variable
if (isset($GLOBALS['PHP_AUTH_PW'])) {
$this->password = $GLOBALS['PHP_AUTH_PW'];
}
if (empty($this->password)) {
if (Core::getenv('PHP_AUTH_PW')) {
$this->password = Core::getenv('PHP_AUTH_PW');
} elseif (Core::getenv('REMOTE_PASSWORD')) {
// Apache/CGI
$this->password = Core::getenv('REMOTE_PASSWORD');
} elseif (Core::getenv('AUTH_PASSWORD')) {
// WebSite Professional
$this->password = Core::getenv('AUTH_PASSWORD');
}
}
// Sanitize empty password login
if ($this->password === null) {
$this->password = '';
}
// Avoid showing the password in phpinfo()'s output
unset($GLOBALS['PHP_AUTH_PW'], $_SERVER['PHP_AUTH_PW']);
// Decode possibly encoded information (used by IIS/CGI/FastCGI)
// (do not use explode() because a user might have a colon in their password
if (strcmp(substr($this->user, 0, 6), 'Basic ') == 0) {
$usr_pass = base64_decode(substr($this->user, 6));
if (! empty($usr_pass)) {
$colon = strpos($usr_pass, ':');
if ($colon) {
$this->user = substr($usr_pass, 0, $colon);
$this->password = substr($usr_pass, $colon + 1);
}
unset($colon);
}
unset($usr_pass);
}
// sanitize username
$this->user = Core::sanitizeMySQLUser($this->user);
// User logged out -> ensure the new username is not the same
$old_usr = $_REQUEST['old_usr'] ?? '';
if (! empty($old_usr) && (isset($this->user) && hash_equals($old_usr, $this->user))) {
$this->user = '';
}
// Returns whether we get authentication settings or not
return ! empty($this->user);
}
/**
* User is not allowed to login to MySQL -> authentication failed
*
* @param string $failure String describing why authentication has failed
*/
public function showFailure($failure): void
{
global $dbi;
parent::showFailure($failure);
$error = $dbi->getError();
if ($error && $GLOBALS['errno'] != 1045) {
Core::fatalError($error);
} else {
$this->authForm();
}
}
/**
* Returns URL for login form.
*
* @return string
*/
public function getLoginFormURL()
{
return './index.php?route=/&old_usr=' . $this->user;
}
}

View file

@ -1,302 +0,0 @@
<?php
/**
* SignOn Authentication plugin for phpMyAdmin
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Auth;
use PhpMyAdmin\Core;
use PhpMyAdmin\Plugins\AuthenticationPlugin;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Util;
use function __;
use function array_merge;
use function defined;
use function file_exists;
use function in_array;
use function session_get_cookie_params;
use function session_id;
use function session_name;
use function session_set_cookie_params;
use function session_start;
use function session_write_close;
use function version_compare;
use const PHP_VERSION;
/**
* Handles the SignOn authentication method
*/
class AuthenticationSignon extends AuthenticationPlugin
{
/**
* Displays authentication form
*
* @return bool always true (no return indeed)
*/
public function showLoginForm(): bool
{
ResponseRenderer::getInstance()->disable();
unset($_SESSION['LAST_SIGNON_URL']);
if (empty($GLOBALS['cfg']['Server']['SignonURL'])) {
Core::fatalError('You must set SignonURL!');
} else {
Core::sendHeaderLocation($GLOBALS['cfg']['Server']['SignonURL']);
}
if (! defined('TESTSUITE')) {
exit;
}
return false;
}
/**
* Set cookie params
*
* @param array $sessionCookieParams The cookie params
*/
public function setCookieParams(?array $sessionCookieParams = null): void
{
/* Session cookie params from config */
if ($sessionCookieParams === null) {
$sessionCookieParams = (array) $GLOBALS['cfg']['Server']['SignonCookieParams'];
}
/* Sanitize cookie params */
$defaultCookieParams = /** @return mixed */ static function (string $key) {
switch ($key) {
case 'lifetime':
return 0;
case 'path':
return '/';
case 'domain':
return '';
case 'secure':
case 'httponly':
return false;
}
return null;
};
foreach (['lifetime', 'path', 'domain', 'secure', 'httponly'] as $key) {
if (isset($sessionCookieParams[$key])) {
continue;
}
$sessionCookieParams[$key] = $defaultCookieParams($key);
}
if (
isset($sessionCookieParams['samesite'])
&& ! in_array($sessionCookieParams['samesite'], ['Lax', 'Strict'])
) {
// Not a valid value for samesite
unset($sessionCookieParams['samesite']);
}
if (version_compare(PHP_VERSION, '7.3.0', '>=')) {
/** @psalm-suppress InvalidArgument */
session_set_cookie_params($sessionCookieParams);
} else {
session_set_cookie_params(
$sessionCookieParams['lifetime'],
$sessionCookieParams['path'],
$sessionCookieParams['domain'],
$sessionCookieParams['secure'],
$sessionCookieParams['httponly']
);
}
}
/**
* Gets authentication credentials
*/
public function readCredentials(): bool
{
/* Check if we're using same signon server */
$signon_url = $GLOBALS['cfg']['Server']['SignonURL'];
if (isset($_SESSION['LAST_SIGNON_URL']) && $_SESSION['LAST_SIGNON_URL'] != $signon_url) {
return false;
}
/* Script name */
$script_name = $GLOBALS['cfg']['Server']['SignonScript'];
/* Session name */
$session_name = $GLOBALS['cfg']['Server']['SignonSession'];
/* Current host */
$single_signon_host = $GLOBALS['cfg']['Server']['host'];
/* Current port */
$single_signon_port = $GLOBALS['cfg']['Server']['port'];
/* No configuration updates */
$single_signon_cfgupdate = [];
/* Handle script based auth */
if ($script_name !== '') {
if (! @file_exists($script_name)) {
Core::fatalError(
__('Can not find signon authentication script:')
. ' ' . $script_name
);
}
include $script_name;
[$this->user, $this->password] = get_login_credentials($GLOBALS['cfg']['Server']['user']);
} elseif (isset($_COOKIE[$session_name])) { /* Does session exist? */
/* End current session */
$old_session = session_name();
$old_id = session_id();
$oldCookieParams = session_get_cookie_params();
if (! defined('TESTSUITE')) {
session_write_close();
}
/* Load single signon session */
if (! defined('TESTSUITE')) {
$this->setCookieParams();
session_name($session_name);
session_id($_COOKIE[$session_name]);
session_start();
}
/* Clear error message */
unset($_SESSION['PMA_single_signon_error_message']);
/* Grab credentials if they exist */
if (isset($_SESSION['PMA_single_signon_user'])) {
$this->user = $_SESSION['PMA_single_signon_user'];
}
if (isset($_SESSION['PMA_single_signon_password'])) {
$this->password = $_SESSION['PMA_single_signon_password'];
}
if (isset($_SESSION['PMA_single_signon_host'])) {
$single_signon_host = $_SESSION['PMA_single_signon_host'];
}
if (isset($_SESSION['PMA_single_signon_port'])) {
$single_signon_port = $_SESSION['PMA_single_signon_port'];
}
if (isset($_SESSION['PMA_single_signon_cfgupdate'])) {
$single_signon_cfgupdate = $_SESSION['PMA_single_signon_cfgupdate'];
}
/* Also get token as it is needed to access subpages */
if (isset($_SESSION['PMA_single_signon_token'])) {
/* No need to care about token on logout */
$pma_token = $_SESSION['PMA_single_signon_token'];
}
$HMACSecret = Util::generateRandom(16);
if (isset($_SESSION['PMA_single_signon_HMAC_secret'])) {
$HMACSecret = $_SESSION['PMA_single_signon_HMAC_secret'];
}
/* End single signon session */
if (! defined('TESTSUITE')) {
session_write_close();
}
/* Restart phpMyAdmin session */
if (! defined('TESTSUITE')) {
$this->setCookieParams($oldCookieParams);
if ($old_session !== false) {
session_name($old_session);
}
if (! empty($old_id)) {
session_id($old_id);
}
session_start();
}
/* Set the single signon host */
$GLOBALS['cfg']['Server']['host'] = $single_signon_host;
/* Set the single signon port */
$GLOBALS['cfg']['Server']['port'] = $single_signon_port;
/* Configuration update */
$GLOBALS['cfg']['Server'] = array_merge($GLOBALS['cfg']['Server'], $single_signon_cfgupdate);
/* Restore our token */
if (! empty($pma_token)) {
$_SESSION[' PMA_token '] = $pma_token;
$_SESSION[' HMAC_secret '] = $HMACSecret;
}
/**
* Clear user cache.
*/
Util::clearUserCache();
}
// Returns whether we get authentication settings or not
if (empty($this->user)) {
unset($_SESSION['LAST_SIGNON_URL']);
return false;
}
$_SESSION['LAST_SIGNON_URL'] = $GLOBALS['cfg']['Server']['SignonURL'];
return true;
}
/**
* User is not allowed to login to MySQL -> authentication failed
*
* @param string $failure String describing why authentication has failed
*/
public function showFailure($failure): void
{
parent::showFailure($failure);
/* Session name */
$session_name = $GLOBALS['cfg']['Server']['SignonSession'];
/* Does session exist? */
if (isset($_COOKIE[$session_name])) {
if (! defined('TESTSUITE')) {
/* End current session */
session_write_close();
/* Load single signon session */
$this->setCookieParams();
session_name($session_name);
session_id($_COOKIE[$session_name]);
session_start();
}
/* Set error message */
$_SESSION['PMA_single_signon_error_message'] = $this->getErrorMessage($failure);
}
$this->showLoginForm();
}
/**
* Returns URL for login form.
*
* @return string
*/
public function getLoginFormURL()
{
return $GLOBALS['cfg']['Server']['SignonURL'];
}
}

View file

@ -1,360 +0,0 @@
<?php
/**
* Abstract class for the authentication plugins
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins;
use PhpMyAdmin\Config;
use PhpMyAdmin\Core;
use PhpMyAdmin\IpAllowDeny;
use PhpMyAdmin\Logging;
use PhpMyAdmin\Message;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Session;
use PhpMyAdmin\Template;
use PhpMyAdmin\TwoFactor;
use PhpMyAdmin\Url;
use PhpMyAdmin\Util;
use function __;
use function array_keys;
use function defined;
use function htmlspecialchars;
use function intval;
use function max;
use function min;
use function session_destroy;
use function session_unset;
use function sprintf;
use function time;
/**
* Provides a common interface that will have to be implemented by all of the
* authentication plugins.
*/
abstract class AuthenticationPlugin
{
/**
* Username
*
* @var string
*/
public $user = '';
/**
* Password
*
* @var string
*/
public $password = '';
/** @var IpAllowDeny */
protected $ipAllowDeny;
/** @var Template */
public $template;
public function __construct()
{
$this->ipAllowDeny = new IpAllowDeny();
$this->template = new Template();
}
/**
* Displays authentication form
*/
abstract public function showLoginForm(): bool;
/**
* Gets authentication credentials
*/
abstract public function readCredentials(): bool;
/**
* Set the user and password after last checkings if required
*/
public function storeCredentials(): bool
{
global $cfg;
$this->setSessionAccessTime();
$cfg['Server']['user'] = $this->user;
$cfg['Server']['password'] = $this->password;
return true;
}
/**
* Stores user credentials after successful login.
*/
public function rememberCredentials(): void
{
}
/**
* User is not allowed to login to MySQL -> authentication failed
*
* @param string $failure String describing why authentication has failed
*/
public function showFailure($failure): void
{
Logging::logUser($this->user, $failure);
}
/**
* Perform logout
*/
public function logOut(): void
{
global $config;
/* Obtain redirect URL (before doing logout) */
if (! empty($GLOBALS['cfg']['Server']['LogoutURL'])) {
$redirect_url = $GLOBALS['cfg']['Server']['LogoutURL'];
} else {
$redirect_url = $this->getLoginFormURL();
}
/* Clear credentials */
$this->user = '';
$this->password = '';
/*
* Get a logged-in server count in case of LoginCookieDeleteAll is disabled.
*/
$server = 0;
if ($GLOBALS['cfg']['LoginCookieDeleteAll'] === false && $GLOBALS['cfg']['Server']['auth_type'] === 'cookie') {
foreach (array_keys($GLOBALS['cfg']['Servers']) as $key) {
if (! $config->issetCookie('pmaAuth-' . $key)) {
continue;
}
$server = $key;
}
}
if ($server === 0) {
/* delete user's choices that were stored in session */
if (! defined('TESTSUITE')) {
session_unset();
session_destroy();
}
/* Redirect to login form (or configured URL) */
Core::sendHeaderLocation($redirect_url);
} else {
/* Redirect to other authenticated server */
$_SESSION['partial_logout'] = true;
Core::sendHeaderLocation(
'./index.php?route=/' . Url::getCommonRaw(['server' => $server], '&')
);
}
}
/**
* Returns URL for login form.
*
* @return string
*/
public function getLoginFormURL()
{
return './index.php?route=/';
}
/**
* Returns error message for failed authentication.
*
* @param string $failure String describing why authentication has failed
*
* @return string
*/
public function getErrorMessage($failure)
{
global $dbi;
if ($failure === 'empty-denied') {
return __('Login without a password is forbidden by configuration (see AllowNoPassword)');
}
if ($failure === 'root-denied' || $failure === 'allow-denied') {
return __('Access denied!');
}
if ($failure === 'no-activity') {
return sprintf(
__('You have been automatically logged out due to inactivity of %s seconds.'
. ' Once you log in again, you should be able to resume the work where you left off.'),
intval($GLOBALS['cfg']['LoginCookieValidity'])
);
}
$dbi_error = $dbi->getError();
if (! empty($dbi_error)) {
return htmlspecialchars($dbi_error);
}
if (isset($GLOBALS['errno'])) {
return '#' . $GLOBALS['errno'] . ' '
. __('Cannot log in to the MySQL server');
}
return __('Cannot log in to the MySQL server');
}
/**
* Callback when user changes password.
*
* @param string $password New password to set
*/
public function handlePasswordChange($password): void
{
}
/**
* Store session access time in session.
*
* Tries to workaround PHP 5 session garbage collection which
* looks at the session file's last modified time
*/
public function setSessionAccessTime(): void
{
if (isset($_REQUEST['guid'])) {
$guid = (string) $_REQUEST['guid'];
} else {
$guid = 'default';
}
if (isset($_REQUEST['access_time'])) {
// Ensure access_time is in range <0, LoginCookieValidity + 1>
// to avoid excessive extension of validity.
//
// Negative values can cause session expiry extension
// Too big values can cause overflow and lead to same
$time = time() - min(max(0, intval($_REQUEST['access_time'])), $GLOBALS['cfg']['LoginCookieValidity'] + 1);
} else {
$time = time();
}
$_SESSION['browser_access_time'][$guid] = $time;
}
/**
* High level authentication interface
*
* Gets the credentials or shows login form if necessary
*/
public function authenticate(): void
{
$success = $this->readCredentials();
/* Show login form (this exits) */
if (! $success) {
/* Force generating of new session */
Session::secure();
$this->showLoginForm();
}
/* Store credentials (eg. in cookies) */
$this->storeCredentials();
/* Check allow/deny rules */
$this->checkRules();
/* clear user cache */
Util::clearUserCache();
}
/**
* Check configuration defined restrictions for authentication
*/
public function checkRules(): void
{
global $cfg;
// Check IP-based Allow/Deny rules as soon as possible to reject the
// user based on mod_access in Apache
if (isset($cfg['Server']['AllowDeny']['order'])) {
$allowDeny_forbidden = false; // default
if ($cfg['Server']['AllowDeny']['order'] === 'allow,deny') {
$allowDeny_forbidden = true;
if ($this->ipAllowDeny->allow()) {
$allowDeny_forbidden = false;
}
if ($this->ipAllowDeny->deny()) {
$allowDeny_forbidden = true;
}
} elseif ($cfg['Server']['AllowDeny']['order'] === 'deny,allow') {
if ($this->ipAllowDeny->deny()) {
$allowDeny_forbidden = true;
}
if ($this->ipAllowDeny->allow()) {
$allowDeny_forbidden = false;
}
} elseif ($cfg['Server']['AllowDeny']['order'] === 'explicit') {
if ($this->ipAllowDeny->allow() && ! $this->ipAllowDeny->deny()) {
$allowDeny_forbidden = false;
} else {
$allowDeny_forbidden = true;
}
}
// Ejects the user if banished
if ($allowDeny_forbidden) {
$this->showFailure('allow-denied');
}
}
// is root allowed?
if (! $cfg['Server']['AllowRoot'] && $cfg['Server']['user'] === 'root') {
$this->showFailure('root-denied');
}
// is a login without password allowed?
if ($cfg['Server']['AllowNoPassword'] || $cfg['Server']['password'] !== '') {
return;
}
$this->showFailure('empty-denied');
}
/**
* Checks whether two factor authentication is active
* for given user and performs it.
*/
public function checkTwoFactor(): void
{
$twofactor = new TwoFactor($this->user);
/* Do we need to show the form? */
if ($twofactor->check()) {
return;
}
$response = ResponseRenderer::getInstance();
if ($response->loginPage()) {
if (defined('TESTSUITE')) {
return;
}
exit;
}
echo $this->template->render('login/header');
echo Message::rawNotice(
__('You have enabled two factor authentication, please confirm your login.')
)->getDisplay();
echo $this->template->render('login/twofactor', [
'form' => $twofactor->render(),
'show_submit' => $twofactor->showSubmit(),
]);
echo $this->template->render('login/footer');
echo Config::renderFooter();
if (! defined('TESTSUITE')) {
exit;
}
}
}

View file

@ -1,392 +0,0 @@
<?php
/**
* Set of functions used to build NHibernate dumps of tables
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Export;
use PhpMyAdmin\Plugins\Export\Helpers\TableProperty;
use PhpMyAdmin\Plugins\ExportPlugin;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyMainGroup;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyRootGroup;
use PhpMyAdmin\Properties\Options\Items\HiddenPropertyItem;
use PhpMyAdmin\Properties\Options\Items\SelectPropertyItem;
use PhpMyAdmin\Properties\Plugins\ExportPluginProperties;
use PhpMyAdmin\Util;
use function __;
use function implode;
use function preg_match;
use function preg_replace;
use function sprintf;
use function ucfirst;
/**
* Handles the export for the CodeGen class
*/
class ExportCodegen extends ExportPlugin
{
/**
* CodeGen Formats
*
* @var array
*/
private $cgFormats;
private const HANDLER_NHIBERNATE_CS = 0;
private const HANDLER_NHIBERNATE_XML = 1;
/**
* @psalm-return non-empty-lowercase-string
*/
public function getName(): string
{
return 'codegen';
}
/**
* Initialize the local variables that are used for export CodeGen.
*/
protected function init(): void
{
$this->setCgFormats([
self::HANDLER_NHIBERNATE_CS => 'NHibernate C# DO',
self::HANDLER_NHIBERNATE_XML => 'NHibernate XML',
]);
}
protected function setProperties(): ExportPluginProperties
{
$exportPluginProperties = new ExportPluginProperties();
$exportPluginProperties->setText('CodeGen');
$exportPluginProperties->setExtension('cs');
$exportPluginProperties->setMimeType('text/cs');
$exportPluginProperties->setOptionsText(__('Options'));
// create the root group that will be the options field for
// $exportPluginProperties
// this will be shown as "Format specific options"
$exportSpecificOptions = new OptionsPropertyRootGroup('Format Specific Options');
// general options main group
$generalOptions = new OptionsPropertyMainGroup('general_opts');
// create primary items and add them to the group
$leaf = new HiddenPropertyItem('structure_or_data');
$generalOptions->addProperty($leaf);
$leaf = new SelectPropertyItem(
'format',
__('Format:')
);
$leaf->setValues($this->getCgFormats());
$generalOptions->addProperty($leaf);
// add the main group to the root group
$exportSpecificOptions->addProperty($generalOptions);
// set the options for the export plugin property item
$exportPluginProperties->setOptions($exportSpecificOptions);
return $exportPluginProperties;
}
/**
* Outputs export header
*/
public function exportHeader(): bool
{
return true;
}
/**
* Outputs export footer
*/
public function exportFooter(): bool
{
return true;
}
/**
* Outputs database header
*
* @param string $db Database name
* @param string $dbAlias Aliases of db
*/
public function exportDBHeader($db, $dbAlias = ''): bool
{
return true;
}
/**
* Outputs database footer
*
* @param string $db Database name
*/
public function exportDBFooter($db): bool
{
return true;
}
/**
* Outputs CREATE DATABASE statement
*
* @param string $db Database name
* @param string $exportType 'server', 'database', 'table'
* @param string $dbAlias Aliases of db
*/
public function exportDBCreate($db, $exportType, $dbAlias = ''): bool
{
return true;
}
/**
* Outputs the content of a table in NHibernate format
*
* @param string $db database name
* @param string $table table name
* @param string $crlf the end of line sequence
* @param string $errorUrl the url to go back in case of error
* @param string $sqlQuery SQL query for obtaining data
* @param array $aliases Aliases of db/table/columns
*/
public function exportData(
$db,
$table,
$crlf,
$errorUrl,
$sqlQuery,
array $aliases = []
): bool {
$format = (int) $GLOBALS['codegen_format'];
if ($format === self::HANDLER_NHIBERNATE_CS) {
return $this->export->outputHandler($this->handleNHibernateCSBody($db, $table, $crlf, $aliases));
}
if ($format === self::HANDLER_NHIBERNATE_XML) {
return $this->export->outputHandler($this->handleNHibernateXMLBody($db, $table, $crlf, $aliases));
}
return $this->export->outputHandler(sprintf('%s is not supported.', $format));
}
/**
* Used to make identifiers (from table or database names)
*
* @param string $str name to be converted
* @param bool $ucfirst whether to make the first character uppercase
*
* @return string identifier
*/
public static function cgMakeIdentifier($str, $ucfirst = true)
{
// remove unsafe characters
$str = (string) preg_replace('/[^\p{L}\p{Nl}_]/u', '', $str);
// make sure first character is a letter or _
if (! preg_match('/^\pL/u', $str)) {
$str = '_' . $str;
}
if ($ucfirst) {
$str = ucfirst($str);
}
return $str;
}
/**
* C# Handler
*
* @param string $db database name
* @param string $table table name
* @param string $crlf line separator
* @param array $aliases Aliases of db/table/columns
*
* @return string containing C# code lines, separated by "\n"
*/
private function handleNHibernateCSBody($db, $table, $crlf, array $aliases = [])
{
global $dbi;
$db_alias = $db;
$table_alias = $table;
$this->initAlias($aliases, $db_alias, $table_alias);
$result = $dbi->query(
sprintf(
'DESC %s.%s',
Util::backquote($db),
Util::backquote($table)
)
);
/** @var TableProperty[] $tableProperties */
$tableProperties = [];
while ($row = $result->fetchRow()) {
$col_as = $this->getAlias($aliases, $row[0], 'col', $db, $table);
if (! empty($col_as)) {
$row[0] = $col_as;
}
$tableProperties[] = new TableProperty($row);
}
unset($result);
$lines = [];
$lines[] = 'using System;';
$lines[] = 'using System.Collections;';
$lines[] = 'using System.Collections.Generic;';
$lines[] = 'using System.Text;';
$lines[] = 'namespace ' . self::cgMakeIdentifier($db_alias);
$lines[] = '{';
$lines[] = ' #region '
. self::cgMakeIdentifier($table_alias);
$lines[] = ' public class '
. self::cgMakeIdentifier($table_alias);
$lines[] = ' {';
$lines[] = ' #region Member Variables';
foreach ($tableProperties as $tableProperty) {
$lines[] = $tableProperty->formatCs(' protected #dotNetPrimitiveType# _#name#;');
}
$lines[] = ' #endregion';
$lines[] = ' #region Constructors';
$lines[] = ' public '
. self::cgMakeIdentifier($table_alias) . '() { }';
$temp = [];
foreach ($tableProperties as $tableProperty) {
if ($tableProperty->isPK()) {
continue;
}
$temp[] = $tableProperty->formatCs('#dotNetPrimitiveType# #name#');
}
$lines[] = ' public '
. self::cgMakeIdentifier($table_alias)
. '('
. implode(', ', $temp)
. ')';
$lines[] = ' {';
foreach ($tableProperties as $tableProperty) {
if ($tableProperty->isPK()) {
continue;
}
$lines[] = $tableProperty->formatCs(' this._#name#=#name#;');
}
$lines[] = ' }';
$lines[] = ' #endregion';
$lines[] = ' #region Public Properties';
foreach ($tableProperties as $tableProperty) {
$lines[] = $tableProperty->formatCs(
' public virtual #dotNetPrimitiveType# #ucfirstName#'
. "\n"
. ' {' . "\n"
. ' get {return _#name#;}' . "\n"
. ' set {_#name#=value;}' . "\n"
. ' }'
);
}
$lines[] = ' #endregion';
$lines[] = ' }';
$lines[] = ' #endregion';
$lines[] = '}';
return implode($crlf, $lines);
}
/**
* XML Handler
*
* @param string $db database name
* @param string $table table name
* @param string $crlf line separator
* @param array $aliases Aliases of db/table/columns
*
* @return string containing XML code lines, separated by "\n"
*/
private function handleNHibernateXMLBody(
$db,
$table,
$crlf,
array $aliases = []
) {
global $dbi;
$db_alias = $db;
$table_alias = $table;
$this->initAlias($aliases, $db_alias, $table_alias);
$lines = [];
$lines[] = '<?xml version="1.0" encoding="utf-8" ?>';
$lines[] = '<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" '
. 'namespace="' . self::cgMakeIdentifier($db_alias) . '" '
. 'assembly="' . self::cgMakeIdentifier($db_alias) . '">';
$lines[] = ' <class '
. 'name="' . self::cgMakeIdentifier($table_alias) . '" '
. 'table="' . self::cgMakeIdentifier($table_alias) . '">';
$result = $dbi->query(
sprintf(
'DESC %s.%s',
Util::backquote($db),
Util::backquote($table)
)
);
while ($row = $result->fetchRow()) {
$col_as = $this->getAlias($aliases, $row[0], 'col', $db, $table);
if (! empty($col_as)) {
$row[0] = $col_as;
}
$tableProperty = new TableProperty($row);
if ($tableProperty->isPK()) {
$lines[] = $tableProperty->formatXml(
' <id name="#ucfirstName#" type="#dotNetObjectType#"'
. ' unsaved-value="0">' . "\n"
. ' <column name="#name#" sql-type="#type#"'
. ' not-null="#notNull#" unique="#unique#"'
. ' index="PRIMARY"/>' . "\n"
. ' <generator class="native" />' . "\n"
. ' </id>'
);
} else {
$lines[] = $tableProperty->formatXml(
' <property name="#ucfirstName#"'
. ' type="#dotNetObjectType#">' . "\n"
. ' <column name="#name#" sql-type="#type#"'
. ' not-null="#notNull#" #indexName#/>' . "\n"
. ' </property>'
);
}
}
$lines[] = ' </class>';
$lines[] = '</hibernate-mapping>';
return implode($crlf, $lines);
}
/**
* Getter for CodeGen formats
*
* @return array
*/
private function getCgFormats()
{
return $this->cgFormats;
}
/**
* Setter for CodeGen formats
*
* @param array $CG_FORMATS contains CodeGen Formats
*/
private function setCgFormats(array $CG_FORMATS): void
{
$this->cgFormats = $CG_FORMATS;
}
}

View file

@ -1,334 +0,0 @@
<?php
/**
* CSV export code
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Export;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\Plugins\ExportPlugin;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyMainGroup;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyRootGroup;
use PhpMyAdmin\Properties\Options\Items\BoolPropertyItem;
use PhpMyAdmin\Properties\Options\Items\HiddenPropertyItem;
use PhpMyAdmin\Properties\Options\Items\TextPropertyItem;
use PhpMyAdmin\Properties\Plugins\ExportPluginProperties;
use function __;
use function mb_strtolower;
use function mb_substr;
use function preg_replace;
use function str_replace;
use function stripslashes;
use function trim;
/**
* Handles the export for the CSV format
*/
class ExportCsv extends ExportPlugin
{
/**
* @psalm-return non-empty-lowercase-string
*/
public function getName(): string
{
return 'csv';
}
protected function setProperties(): ExportPluginProperties
{
$exportPluginProperties = new ExportPluginProperties();
$exportPluginProperties->setText('CSV');
$exportPluginProperties->setExtension('csv');
$exportPluginProperties->setMimeType('text/comma-separated-values');
$exportPluginProperties->setOptionsText(__('Options'));
// create the root group that will be the options field for
// $exportPluginProperties
// this will be shown as "Format specific options"
$exportSpecificOptions = new OptionsPropertyRootGroup('Format Specific Options');
// general options main group
$generalOptions = new OptionsPropertyMainGroup('general_opts');
// create leaf items and add them to the group
$leaf = new TextPropertyItem(
'separator',
__('Columns separated with:')
);
$generalOptions->addProperty($leaf);
$leaf = new TextPropertyItem(
'enclosed',
__('Columns enclosed with:')
);
$generalOptions->addProperty($leaf);
$leaf = new TextPropertyItem(
'escaped',
__('Columns escaped with:')
);
$generalOptions->addProperty($leaf);
$leaf = new TextPropertyItem(
'terminated',
__('Lines terminated with:')
);
$generalOptions->addProperty($leaf);
$leaf = new TextPropertyItem(
'null',
__('Replace NULL with:')
);
$generalOptions->addProperty($leaf);
$leaf = new BoolPropertyItem(
'removeCRLF',
__('Remove carriage return/line feed characters within columns')
);
$generalOptions->addProperty($leaf);
$leaf = new BoolPropertyItem(
'columns',
__('Put columns names in the first row')
);
$generalOptions->addProperty($leaf);
$leaf = new HiddenPropertyItem('structure_or_data');
$generalOptions->addProperty($leaf);
// add the main group to the root group
$exportSpecificOptions->addProperty($generalOptions);
// set the options for the export plugin property item
$exportPluginProperties->setOptions($exportSpecificOptions);
return $exportPluginProperties;
}
/**
* Outputs export header
*/
public function exportHeader(): bool
{
global $what, $csv_terminated, $csv_separator, $csv_enclosed, $csv_escaped;
// Here we just prepare some values for export
if ($what === 'excel') {
$csv_terminated = "\015\012";
switch ($GLOBALS['excel_edition']) {
case 'win':
// as tested on Windows with Excel 2002 and Excel 2007
$csv_separator = ';';
break;
case 'mac_excel2003':
$csv_separator = ';';
break;
case 'mac_excel2008':
$csv_separator = ',';
break;
}
$csv_enclosed = '"';
$csv_escaped = '"';
if (isset($GLOBALS['excel_columns'])) {
$GLOBALS['csv_columns'] = true;
}
} else {
if (empty($csv_terminated) || mb_strtolower($csv_terminated) === 'auto') {
$csv_terminated = $GLOBALS['crlf'];
} else {
$csv_terminated = str_replace(
[
'\\r',
'\\n',
'\\t',
],
[
"\015",
"\012",
"\011",
],
$csv_terminated
);
}
$csv_separator = str_replace('\\t', "\011", $csv_separator);
}
return true;
}
/**
* Outputs export footer
*/
public function exportFooter(): bool
{
return true;
}
/**
* Outputs database header
*
* @param string $db Database name
* @param string $dbAlias Alias of db
*/
public function exportDBHeader($db, $dbAlias = ''): bool
{
return true;
}
/**
* Outputs database footer
*
* @param string $db Database name
*/
public function exportDBFooter($db): bool
{
return true;
}
/**
* Outputs CREATE DATABASE statement
*
* @param string $db Database name
* @param string $exportType 'server', 'database', 'table'
* @param string $dbAlias Aliases of db
*/
public function exportDBCreate($db, $exportType, $dbAlias = ''): bool
{
return true;
}
/**
* Outputs the content of a table in CSV format
*
* @param string $db database name
* @param string $table table name
* @param string $crlf the end of line sequence
* @param string $errorUrl the url to go back in case of error
* @param string $sqlQuery SQL query for obtaining data
* @param array $aliases Aliases of db/table/columns
*/
public function exportData(
$db,
$table,
$crlf,
$errorUrl,
$sqlQuery,
array $aliases = []
): bool {
global $what, $csv_terminated, $csv_separator, $csv_enclosed, $csv_escaped, $dbi;
$db_alias = $db;
$table_alias = $table;
$this->initAlias($aliases, $db_alias, $table_alias);
// Gets the data from the database
$result = $dbi->query($sqlQuery, DatabaseInterface::CONNECT_USER, DatabaseInterface::QUERY_UNBUFFERED);
$fields_cnt = $result->numFields();
// If required, get fields name at the first line
if (isset($GLOBALS['csv_columns']) && $GLOBALS['csv_columns']) {
$schema_insert = '';
foreach ($result->getFieldNames() as $col_as) {
if (! empty($aliases[$db]['tables'][$table]['columns'][$col_as])) {
$col_as = $aliases[$db]['tables'][$table]['columns'][$col_as];
}
$col_as = stripslashes($col_as);
if ($csv_enclosed == '') {
$schema_insert .= $col_as;
} else {
$schema_insert .= $csv_enclosed
. str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $col_as)
. $csv_enclosed;
}
$schema_insert .= $csv_separator;
}
$schema_insert = trim(mb_substr($schema_insert, 0, -1));
if (! $this->export->outputHandler($schema_insert . $csv_terminated)) {
return false;
}
}
// Format the data
while ($row = $result->fetchRow()) {
$schema_insert = '';
for ($j = 0; $j < $fields_cnt; $j++) {
if (! isset($row[$j])) {
$schema_insert .= $GLOBALS[$what . '_null'];
} elseif ($row[$j] == '0' || $row[$j] != '') {
// always enclose fields
if ($what === 'excel') {
$row[$j] = preg_replace("/\015(\012)?/", "\012", $row[$j]);
}
// remove CRLF characters within field
if (isset($GLOBALS[$what . '_removeCRLF']) && $GLOBALS[$what . '_removeCRLF']) {
$row[$j] = str_replace(
[
"\r",
"\n",
],
'',
$row[$j]
);
}
if ($csv_enclosed == '') {
$schema_insert .= $row[$j];
} else {
// also double the escape string if found in the data
if ($csv_escaped != $csv_enclosed) {
$schema_insert .= $csv_enclosed
. str_replace(
$csv_enclosed,
$csv_escaped . $csv_enclosed,
str_replace(
$csv_escaped,
$csv_escaped . $csv_escaped,
$row[$j]
)
)
. $csv_enclosed;
} else {
// avoid a problem when escape string equals enclose
$schema_insert .= $csv_enclosed
. str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j])
. $csv_enclosed;
}
}
} else {
$schema_insert .= '';
}
if ($j >= $fields_cnt - 1) {
continue;
}
$schema_insert .= $csv_separator;
}
if (! $this->export->outputHandler($schema_insert . $csv_terminated)) {
return false;
}
}
return true;
}
/**
* Outputs result of raw query in CSV format
*
* @param string $errorUrl the url to go back in case of error
* @param string|null $db the database where the query is executed
* @param string $sqlQuery the rawquery to output
* @param string $crlf the end of line sequence
*/
public function exportRawQuery(string $errorUrl, ?string $db, string $sqlQuery, string $crlf): bool
{
global $dbi;
if ($db !== null) {
$dbi->selectDb($db);
}
return $this->exportData($db ?? '', '', $crlf, $errorUrl, $sqlQuery);
}
}

View file

@ -1,86 +0,0 @@
<?php
/**
* Class for exporting CSV dumps of tables for excel
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Export;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyMainGroup;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyRootGroup;
use PhpMyAdmin\Properties\Options\Items\BoolPropertyItem;
use PhpMyAdmin\Properties\Options\Items\HiddenPropertyItem;
use PhpMyAdmin\Properties\Options\Items\SelectPropertyItem;
use PhpMyAdmin\Properties\Options\Items\TextPropertyItem;
use PhpMyAdmin\Properties\Plugins\ExportPluginProperties;
use function __;
/**
* Handles the export for the CSV-Excel format
*/
class ExportExcel extends ExportCsv
{
/**
* @psalm-return non-empty-lowercase-string
*/
public function getName(): string
{
return 'excel';
}
protected function setProperties(): ExportPluginProperties
{
$exportPluginProperties = new ExportPluginProperties();
$exportPluginProperties->setText('CSV for MS Excel');
$exportPluginProperties->setExtension('csv');
$exportPluginProperties->setMimeType('text/comma-separated-values');
$exportPluginProperties->setOptionsText(__('Options'));
// create the root group that will be the options field for
// $exportPluginProperties
// this will be shown as "Format specific options"
$exportSpecificOptions = new OptionsPropertyRootGroup('Format Specific Options');
// general options main group
$generalOptions = new OptionsPropertyMainGroup('general_opts');
// create primary items and add them to the group
$leaf = new TextPropertyItem(
'null',
__('Replace NULL with:')
);
$generalOptions->addProperty($leaf);
$leaf = new BoolPropertyItem(
'removeCRLF',
__('Remove carriage return/line feed characters within columns')
);
$generalOptions->addProperty($leaf);
$leaf = new BoolPropertyItem(
'columns',
__('Put columns names in the first row')
);
$generalOptions->addProperty($leaf);
$leaf = new SelectPropertyItem(
'edition',
__('Excel edition:')
);
$leaf->setValues(
[
'win' => 'Windows',
'mac_excel2003' => 'Excel 2003 / Macintosh',
'mac_excel2008' => 'Excel 2008 / Macintosh',
]
);
$generalOptions->addProperty($leaf);
$leaf = new HiddenPropertyItem('structure_or_data');
$generalOptions->addProperty($leaf);
// add the main group to the root group
$exportSpecificOptions->addProperty($generalOptions);
// set the options for the export plugin property item
$exportPluginProperties->setOptions($exportSpecificOptions);
return $exportPluginProperties;
}
}

View file

@ -1,641 +0,0 @@
<?php
/**
* HTML-Word export code
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Export;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\Plugins\ExportPlugin;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyMainGroup;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyRootGroup;
use PhpMyAdmin\Properties\Options\Items\BoolPropertyItem;
use PhpMyAdmin\Properties\Options\Items\RadioPropertyItem;
use PhpMyAdmin\Properties\Options\Items\TextPropertyItem;
use PhpMyAdmin\Properties\Plugins\ExportPluginProperties;
use PhpMyAdmin\Util;
use function __;
use function htmlspecialchars;
use function in_array;
use function str_replace;
use function stripslashes;
/**
* Handles the export for the HTML-Word format
*/
class ExportHtmlword extends ExportPlugin
{
/**
* @psalm-return non-empty-lowercase-string
*/
public function getName(): string
{
return 'htmlword';
}
protected function setProperties(): ExportPluginProperties
{
$exportPluginProperties = new ExportPluginProperties();
$exportPluginProperties->setText('Microsoft Word 2000');
$exportPluginProperties->setExtension('doc');
$exportPluginProperties->setMimeType('application/vnd.ms-word');
$exportPluginProperties->setForceFile(true);
$exportPluginProperties->setOptionsText(__('Options'));
// create the root group that will be the options field for
// $exportPluginProperties
// this will be shown as "Format specific options"
$exportSpecificOptions = new OptionsPropertyRootGroup('Format Specific Options');
// what to dump (structure/data/both)
$dumpWhat = new OptionsPropertyMainGroup(
'dump_what',
__('Dump table')
);
// create primary items and add them to the group
$leaf = new RadioPropertyItem('structure_or_data');
$leaf->setValues(
[
'structure' => __('structure'),
'data' => __('data'),
'structure_and_data' => __('structure and data'),
]
);
$dumpWhat->addProperty($leaf);
// add the main group to the root group
$exportSpecificOptions->addProperty($dumpWhat);
// data options main group
$dataOptions = new OptionsPropertyMainGroup(
'dump_what',
__('Data dump options')
);
$dataOptions->setForce('structure');
// create primary items and add them to the group
$leaf = new TextPropertyItem(
'null',
__('Replace NULL with:')
);
$dataOptions->addProperty($leaf);
$leaf = new BoolPropertyItem(
'columns',
__('Put columns names in the first row')
);
$dataOptions->addProperty($leaf);
// add the main group to the root group
$exportSpecificOptions->addProperty($dataOptions);
// set the options for the export plugin property item
$exportPluginProperties->setOptions($exportSpecificOptions);
return $exportPluginProperties;
}
/**
* Outputs export header
*/
public function exportHeader(): bool
{
global $charset;
return $this->export->outputHandler(
'<html xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:word"
xmlns="http://www.w3.org/TR/REC-html40">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'
. ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset='
. ($charset ?? 'utf-8') . '" />
</head>
<body>'
);
}
/**
* Outputs export footer
*/
public function exportFooter(): bool
{
return $this->export->outputHandler('</body></html>');
}
/**
* Outputs database header
*
* @param string $db Database name
* @param string $dbAlias Aliases of db
*/
public function exportDBHeader($db, $dbAlias = ''): bool
{
if (empty($dbAlias)) {
$dbAlias = $db;
}
return $this->export->outputHandler(
'<h1>' . __('Database') . ' ' . htmlspecialchars($dbAlias) . '</h1>'
);
}
/**
* Outputs database footer
*
* @param string $db Database name
*/
public function exportDBFooter($db): bool
{
return true;
}
/**
* Outputs CREATE DATABASE statement
*
* @param string $db Database name
* @param string $exportType 'server', 'database', 'table'
* @param string $dbAlias Aliases of db
*/
public function exportDBCreate($db, $exportType, $dbAlias = ''): bool
{
return true;
}
/**
* Outputs the content of a table in HTML-Word format
*
* @param string $db database name
* @param string $table table name
* @param string $crlf the end of line sequence
* @param string $errorUrl the url to go back in case of error
* @param string $sqlQuery SQL query for obtaining data
* @param array $aliases Aliases of db/table/columns
*/
public function exportData(
$db,
$table,
$crlf,
$errorUrl,
$sqlQuery,
array $aliases = []
): bool {
global $what, $dbi;
$db_alias = $db;
$table_alias = $table;
$this->initAlias($aliases, $db_alias, $table_alias);
if (
! $this->export->outputHandler(
'<h2>'
. __('Dumping data for table') . ' ' . htmlspecialchars($table_alias)
. '</h2>'
)
) {
return false;
}
if (! $this->export->outputHandler('<table width="100%" cellspacing="1">')) {
return false;
}
// Gets the data from the database
$result = $dbi->query($sqlQuery, DatabaseInterface::CONNECT_USER, DatabaseInterface::QUERY_UNBUFFERED);
$fields_cnt = $result->numFields();
// If required, get fields name at the first line
if (isset($GLOBALS['htmlword_columns'])) {
$schema_insert = '<tr class="print-category">';
foreach ($result->getFieldNames() as $col_as) {
if (! empty($aliases[$db]['tables'][$table]['columns'][$col_as])) {
$col_as = $aliases[$db]['tables'][$table]['columns'][$col_as];
}
$col_as = stripslashes($col_as);
$schema_insert .= '<td class="print"><strong>'
. htmlspecialchars($col_as)
. '</strong></td>';
}
$schema_insert .= '</tr>';
if (! $this->export->outputHandler($schema_insert)) {
return false;
}
}
// Format the data
while ($row = $result->fetchRow()) {
$schema_insert = '<tr class="print-category">';
for ($j = 0; $j < $fields_cnt; $j++) {
if (! isset($row[$j])) {
$value = $GLOBALS[$what . '_null'];
} elseif ($row[$j] == '0' || $row[$j] != '') {
$value = $row[$j];
} else {
$value = '';
}
$schema_insert .= '<td class="print">'
. htmlspecialchars((string) $value)
. '</td>';
}
$schema_insert .= '</tr>';
if (! $this->export->outputHandler($schema_insert)) {
return false;
}
}
return $this->export->outputHandler('</table>');
}
/**
* Returns a stand-in CREATE definition to resolve view dependencies
*
* @param string $db the database name
* @param string $view the view name
* @param string $crlf the end of line sequence
* @param array $aliases Aliases of db/table/columns
*
* @return string resulting definition
*/
public function getTableDefStandIn($db, $view, $crlf, $aliases = [])
{
global $dbi;
$schema_insert = '<table width="100%" cellspacing="1">'
. '<tr class="print-category">'
. '<th class="print">'
. __('Column')
. '</th>'
. '<td class="print"><strong>'
. __('Type')
. '</strong></td>'
. '<td class="print"><strong>'
. __('Null')
. '</strong></td>'
. '<td class="print"><strong>'
. __('Default')
. '</strong></td>'
. '</tr>';
/**
* Get the unique keys in the view
*/
$unique_keys = [];
$keys = $dbi->getTableIndexes($db, $view);
foreach ($keys as $key) {
if ($key['Non_unique'] != 0) {
continue;
}
$unique_keys[] = $key['Column_name'];
}
$columns = $dbi->getColumns($db, $view);
foreach ($columns as $column) {
$col_as = $column['Field'];
if (! empty($aliases[$db]['tables'][$view]['columns'][$col_as])) {
$col_as = $aliases[$db]['tables'][$view]['columns'][$col_as];
}
$schema_insert .= $this->formatOneColumnDefinition($column, $unique_keys, $col_as);
$schema_insert .= '</tr>';
}
$schema_insert .= '</table>';
return $schema_insert;
}
/**
* Returns $table's CREATE definition
*
* @param string $db the database name
* @param string $table the table name
* @param bool $do_relation whether to include relation comments
* @param bool $do_comments whether to include the pmadb-style column
* comments as comments in the structure;
* this is deprecated but the parameter is
* left here because /export calls
* PMA_exportStructure() also for other
* export types which use this parameter
* @param bool $do_mime whether to include mime comments
* at the end
* @param bool $view whether we're handling a view
* @param array $aliases Aliases of db/table/columns
*
* @return string resulting schema
*/
public function getTableDef(
$db,
$table,
$do_relation,
$do_comments,
$do_mime,
$view = false,
array $aliases = []
) {
global $dbi;
$relationParameters = $this->relation->getRelationParameters();
$schema_insert = '';
/**
* Gets fields properties
*/
$dbi->selectDb($db);
// Check if we can use Relations
[$res_rel, $have_rel] = $this->relation->getRelationsAndStatus(
$do_relation && $relationParameters->relationFeature !== null,
$db,
$table
);
/**
* Displays the table structure
*/
$schema_insert .= '<table width="100%" cellspacing="1">';
$schema_insert .= '<tr class="print-category">';
$schema_insert .= '<th class="print">'
. __('Column')
. '</th>';
$schema_insert .= '<td class="print"><strong>'
. __('Type')
. '</strong></td>';
$schema_insert .= '<td class="print"><strong>'
. __('Null')
. '</strong></td>';
$schema_insert .= '<td class="print"><strong>'
. __('Default')
. '</strong></td>';
if ($do_relation && $have_rel) {
$schema_insert .= '<td class="print"><strong>'
. __('Links to')
. '</strong></td>';
}
if ($do_comments) {
$schema_insert .= '<td class="print"><strong>'
. __('Comments')
. '</strong></td>';
$comments = $this->relation->getComments($db, $table);
}
if ($do_mime && $relationParameters->browserTransformationFeature !== null) {
$schema_insert .= '<td class="print"><strong>'
. __('Media type')
. '</strong></td>';
$mime_map = $this->transformations->getMime($db, $table, true);
}
$schema_insert .= '</tr>';
$columns = $dbi->getColumns($db, $table);
/**
* Get the unique keys in the table
*/
$unique_keys = [];
$keys = $dbi->getTableIndexes($db, $table);
foreach ($keys as $key) {
if ($key['Non_unique'] != 0) {
continue;
}
$unique_keys[] = $key['Column_name'];
}
foreach ($columns as $column) {
$col_as = $column['Field'];
if (! empty($aliases[$db]['tables'][$table]['columns'][$col_as])) {
$col_as = $aliases[$db]['tables'][$table]['columns'][$col_as];
}
$schema_insert .= $this->formatOneColumnDefinition($column, $unique_keys, $col_as);
$field_name = $column['Field'];
if ($do_relation && $have_rel) {
$schema_insert .= '<td class="print">'
. htmlspecialchars(
$this->getRelationString(
$res_rel,
$field_name,
$db,
$aliases
)
)
. '</td>';
}
if ($do_comments && $relationParameters->columnCommentsFeature !== null) {
$schema_insert .= '<td class="print">'
. (isset($comments[$field_name])
? htmlspecialchars($comments[$field_name])
: '') . '</td>';
}
if ($do_mime && $relationParameters->browserTransformationFeature !== null) {
$schema_insert .= '<td class="print">'
. (isset($mime_map[$field_name]) ?
htmlspecialchars(
str_replace('_', '/', $mime_map[$field_name]['mimetype'])
)
: '') . '</td>';
}
$schema_insert .= '</tr>';
}
$schema_insert .= '</table>';
return $schema_insert;
}
/**
* Outputs triggers
*
* @param string $db database name
* @param string $table table name
*
* @return string Formatted triggers list
*/
protected function getTriggers($db, $table)
{
global $dbi;
$dump = '<table width="100%" cellspacing="1">';
$dump .= '<tr class="print-category">';
$dump .= '<th class="print">' . __('Name') . '</th>';
$dump .= '<td class="print"><strong>' . __('Time') . '</strong></td>';
$dump .= '<td class="print"><strong>' . __('Event') . '</strong></td>';
$dump .= '<td class="print"><strong>' . __('Definition') . '</strong></td>';
$dump .= '</tr>';
$triggers = $dbi->getTriggers($db, $table);
foreach ($triggers as $trigger) {
$dump .= '<tr class="print-category">';
$dump .= '<td class="print">'
. htmlspecialchars($trigger['name'])
. '</td>'
. '<td class="print">'
. htmlspecialchars($trigger['action_timing'])
. '</td>'
. '<td class="print">'
. htmlspecialchars($trigger['event_manipulation'])
. '</td>'
. '<td class="print">'
. htmlspecialchars($trigger['definition'])
. '</td>'
. '</tr>';
}
$dump .= '</table>';
return $dump;
}
/**
* Outputs table's structure
*
* @param string $db database name
* @param string $table table name
* @param string $crlf the end of line sequence
* @param string $errorUrl the url to go back in case of error
* @param string $exportMode 'create_table', 'triggers', 'create_view',
* 'stand_in'
* @param string $exportType 'server', 'database', 'table'
* @param bool $do_relation whether to include relation comments
* @param bool $do_comments whether to include the pmadb-style column
* comments as comments in the structure;
* this is deprecated but the parameter is
* left here because /export calls
* PMA_exportStructure() also for other
* export types which use this parameter
* @param bool $do_mime whether to include mime comments
* @param bool $dates whether to include creation/update/check dates
* @param array $aliases Aliases of db/table/columns
*/
public function exportStructure(
$db,
$table,
$crlf,
$errorUrl,
$exportMode,
$exportType,
$do_relation = false,
$do_comments = false,
$do_mime = false,
$dates = false,
array $aliases = []
): bool {
global $dbi;
$db_alias = $db;
$table_alias = $table;
$this->initAlias($aliases, $db_alias, $table_alias);
$dump = '';
switch ($exportMode) {
case 'create_table':
$dump .= '<h2>'
. __('Table structure for table') . ' '
. htmlspecialchars($table_alias)
. '</h2>';
$dump .= $this->getTableDef($db, $table, $do_relation, $do_comments, $do_mime, false, $aliases);
break;
case 'triggers':
$dump = '';
$triggers = $dbi->getTriggers($db, $table);
if ($triggers) {
$dump .= '<h2>'
. __('Triggers') . ' ' . htmlspecialchars($table_alias)
. '</h2>';
$dump .= $this->getTriggers($db, $table);
}
break;
case 'create_view':
$dump .= '<h2>'
. __('Structure for view') . ' ' . htmlspecialchars($table_alias)
. '</h2>';
$dump .= $this->getTableDef($db, $table, $do_relation, $do_comments, $do_mime, true, $aliases);
break;
case 'stand_in':
$dump .= '<h2>'
. __('Stand-in structure for view') . ' '
. htmlspecialchars($table_alias)
. '</h2>';
// export a stand-in definition to resolve view dependencies
$dump .= $this->getTableDefStandIn($db, $table, $crlf, $aliases);
}
return $this->export->outputHandler($dump);
}
/**
* Formats the definition for one column
*
* @param array $column info about this column
* @param array $unique_keys unique keys of the table
* @param string $col_alias Column Alias
*
* @return string Formatted column definition
*/
protected function formatOneColumnDefinition(
array $column,
array $unique_keys,
$col_alias = ''
) {
if (empty($col_alias)) {
$col_alias = $column['Field'];
}
$definition = '<tr class="print-category">';
$extracted_columnspec = Util::extractColumnSpec($column['Type']);
$type = htmlspecialchars($extracted_columnspec['print_type']);
if (empty($type)) {
$type = '&nbsp;';
}
if (! isset($column['Default'])) {
if ($column['Null'] !== 'NO') {
$column['Default'] = 'NULL';
}
}
$fmt_pre = '';
$fmt_post = '';
if (in_array($column['Field'], $unique_keys)) {
$fmt_pre = '<strong>' . $fmt_pre;
$fmt_post .= '</strong>';
}
if ($column['Key'] === 'PRI') {
$fmt_pre = '<em>' . $fmt_pre;
$fmt_post .= '</em>';
}
$definition .= '<td class="print">' . $fmt_pre
. htmlspecialchars($col_alias) . $fmt_post . '</td>';
$definition .= '<td class="print">' . htmlspecialchars($type) . '</td>';
$definition .= '<td class="print">'
. ($column['Null'] == '' || $column['Null'] === 'NO'
? __('No')
: __('Yes'))
. '</td>';
$definition .= '<td class="print">'
. htmlspecialchars($column['Default'] ?? '')
. '</td>';
return $definition;
}
}

View file

@ -1,346 +0,0 @@
<?php
/**
* Set of methods used to build dumps of tables as JSON
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Export;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\FieldMetadata;
use PhpMyAdmin\Plugins\ExportPlugin;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyMainGroup;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyRootGroup;
use PhpMyAdmin\Properties\Options\Items\BoolPropertyItem;
use PhpMyAdmin\Properties\Options\Items\HiddenPropertyItem;
use PhpMyAdmin\Properties\Plugins\ExportPluginProperties;
use PhpMyAdmin\Version;
use function __;
use function bin2hex;
use function explode;
use function json_encode;
use function stripslashes;
use const JSON_PRETTY_PRINT;
use const JSON_UNESCAPED_UNICODE;
/**
* Handles the export for the JSON format
*/
class ExportJson extends ExportPlugin
{
/** @var bool */
private $first = true;
/**
* @psalm-return non-empty-lowercase-string
*/
public function getName(): string
{
return 'json';
}
/**
* Encodes the data into JSON
*
* @param mixed $data Data to encode
*
* @return string|false
*/
public function encode($data)
{
$options = 0;
if (isset($GLOBALS['json_pretty_print']) && $GLOBALS['json_pretty_print']) {
$options |= JSON_PRETTY_PRINT;
}
if (isset($GLOBALS['json_unicode']) && $GLOBALS['json_unicode']) {
$options |= JSON_UNESCAPED_UNICODE;
}
return json_encode($data, $options);
}
protected function setProperties(): ExportPluginProperties
{
$exportPluginProperties = new ExportPluginProperties();
$exportPluginProperties->setText('JSON');
$exportPluginProperties->setExtension('json');
$exportPluginProperties->setMimeType('text/plain');
$exportPluginProperties->setOptionsText(__('Options'));
// create the root group that will be the options field for
// $exportPluginProperties
// this will be shown as "Format specific options"
$exportSpecificOptions = new OptionsPropertyRootGroup('Format Specific Options');
// general options main group
$generalOptions = new OptionsPropertyMainGroup('general_opts');
// create primary items and add them to the group
$leaf = new HiddenPropertyItem('structure_or_data');
$generalOptions->addProperty($leaf);
$leaf = new BoolPropertyItem(
'pretty_print',
__('Output pretty-printed JSON (Use human-readable formatting)')
);
$generalOptions->addProperty($leaf);
$leaf = new BoolPropertyItem(
'unicode',
__('Output unicode characters unescaped')
);
$generalOptions->addProperty($leaf);
// add the main group to the root group
$exportSpecificOptions->addProperty($generalOptions);
// set the options for the export plugin property item
$exportPluginProperties->setOptions($exportSpecificOptions);
return $exportPluginProperties;
}
/**
* Outputs export header
*/
public function exportHeader(): bool
{
global $crlf;
$data = $this->encode([
'type' => 'header',
'version' => Version::VERSION,
'comment' => 'Export to JSON plugin for PHPMyAdmin',
]);
if ($data === false) {
return false;
}
return $this->export->outputHandler('[' . $crlf . $data . ',' . $crlf);
}
/**
* Outputs export footer
*/
public function exportFooter(): bool
{
global $crlf;
return $this->export->outputHandler(']' . $crlf);
}
/**
* Outputs database header
*
* @param string $db Database name
* @param string $dbAlias Aliases of db
*/
public function exportDBHeader($db, $dbAlias = ''): bool
{
global $crlf;
if (empty($dbAlias)) {
$dbAlias = $db;
}
$data = $this->encode(['type' => 'database', 'name' => $dbAlias]);
if ($data === false) {
return false;
}
return $this->export->outputHandler($data . ',' . $crlf);
}
/**
* Outputs database footer
*
* @param string $db Database name
*/
public function exportDBFooter($db): bool
{
return true;
}
/**
* Outputs CREATE DATABASE statement
*
* @param string $db Database name
* @param string $exportType 'server', 'database', 'table'
* @param string $dbAlias Aliases of db
*/
public function exportDBCreate($db, $exportType, $dbAlias = ''): bool
{
return true;
}
/**
* Outputs the content of a table in JSON format
*
* @param string $db database name
* @param string $table table name
* @param string $crlf the end of line sequence
* @param string $errorUrl the url to go back in case of error
* @param string $sqlQuery SQL query for obtaining data
* @param array $aliases Aliases of db/table/columns
*/
public function exportData(
$db,
$table,
$crlf,
$errorUrl,
$sqlQuery,
array $aliases = []
): bool {
global $dbi;
$db_alias = $db;
$table_alias = $table;
$this->initAlias($aliases, $db_alias, $table_alias);
if (! $this->first) {
if (! $this->export->outputHandler(',')) {
return false;
}
} else {
$this->first = false;
}
$buffer = $this->encode([
'type' => 'table',
'name' => $table_alias,
'database' => $db_alias,
'data' => '@@DATA@@',
]);
if ($buffer === false) {
return false;
}
return $this->doExportForQuery($dbi, $sqlQuery, $buffer, $crlf, $aliases, $db, $table);
}
/**
* Export to JSON
*
* @phpstan-param array{
* string: array{
* 'tables': array{
* string: array{
* 'columns': array{string: string}
* }
* }
* }
* }|array|null $aliases
*/
protected function doExportForQuery(
DatabaseInterface $dbi,
string $sqlQuery,
string $buffer,
string $crlf,
?array $aliases,
?string $db,
?string $table
): bool {
[$header, $footer] = explode('"@@DATA@@"', $buffer);
if (! $this->export->outputHandler($header . $crlf . '[' . $crlf)) {
return false;
}
$result = $dbi->query($sqlQuery, DatabaseInterface::CONNECT_USER, DatabaseInterface::QUERY_UNBUFFERED);
$columns_cnt = $result->numFields();
$fieldsMeta = $dbi->getFieldsMeta($result);
$columns = [];
foreach ($fieldsMeta as $i => $field) {
$col_as = $field->name;
if (
$db !== null && $table !== null && $aliases !== null
&& ! empty($aliases[$db]['tables'][$table]['columns'][$col_as])
) {
$col_as = $aliases[$db]['tables'][$table]['columns'][$col_as];
}
$columns[$i] = stripslashes($col_as);
}
$record_cnt = 0;
while ($record = $result->fetchRow()) {
$record_cnt++;
// Output table name as comment if this is the first record of the table
if ($record_cnt > 1) {
if (! $this->export->outputHandler(',' . $crlf)) {
return false;
}
}
$data = [];
for ($i = 0; $i < $columns_cnt; $i++) {
// 63 is the binary charset, see: https://dev.mysql.com/doc/internals/en/charsets.html
$isBlobAndIsBinaryCharset = isset($fieldsMeta[$i])
&& $fieldsMeta[$i]->isType(FieldMetadata::TYPE_BLOB)
&& $fieldsMeta[$i]->charsetnr === 63;
// This can occur for binary fields
$isBinaryString = isset($fieldsMeta[$i])
&& $fieldsMeta[$i]->isType(FieldMetadata::TYPE_STRING)
&& $fieldsMeta[$i]->charsetnr === 63;
if (
isset($fieldsMeta[$i]) &&
(
$fieldsMeta[$i]->isMappedTypeGeometry ||
$isBlobAndIsBinaryCharset ||
$isBinaryString
) &&
$record[$i] !== null
) {
// export GIS and blob types as hex
$record[$i] = '0x' . bin2hex($record[$i]);
}
$data[$columns[$i]] = $record[$i];
}
$encodedData = $this->encode($data);
if (! $encodedData) {
return false;
}
if (! $this->export->outputHandler($encodedData)) {
return false;
}
}
return $this->export->outputHandler($crlf . ']' . $crlf . $footer . $crlf);
}
/**
* Outputs result raw query in JSON format
*
* @param string $errorUrl the url to go back in case of error
* @param string|null $db the database where the query is executed
* @param string $sqlQuery the rawquery to output
* @param string $crlf the end of line sequence
*/
public function exportRawQuery(string $errorUrl, ?string $db, string $sqlQuery, string $crlf): bool
{
global $dbi;
$buffer = $this->encode([
'type' => 'raw',
'data' => '@@DATA@@',
]);
if ($buffer === false) {
return false;
}
if ($db !== null) {
$dbi->selectDb($db);
}
return $this->doExportForQuery($dbi, $sqlQuery, $buffer, $crlf, null, $db, null);
}
}

View file

@ -1,712 +0,0 @@
<?php
/**
* Set of methods used to build dumps of tables as Latex
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Export;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\Plugins\ExportPlugin;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyMainGroup;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyRootGroup;
use PhpMyAdmin\Properties\Options\Items\BoolPropertyItem;
use PhpMyAdmin\Properties\Options\Items\RadioPropertyItem;
use PhpMyAdmin\Properties\Options\Items\TextPropertyItem;
use PhpMyAdmin\Properties\Plugins\ExportPluginProperties;
use PhpMyAdmin\Util;
use PhpMyAdmin\Version;
use function __;
use function count;
use function in_array;
use function mb_strpos;
use function mb_substr;
use function str_replace;
use function stripslashes;
use const PHP_VERSION;
/**
* Handles the export for the Latex format
*/
class ExportLatex extends ExportPlugin
{
/**
* @psalm-return non-empty-lowercase-string
*/
public function getName(): string
{
return 'latex';
}
/**
* Initialize the local variables that are used for export Latex.
*/
protected function init(): void
{
/* Messages used in default captions */
$GLOBALS['strLatexContent'] = __('Content of table @TABLE@');
$GLOBALS['strLatexContinued'] = __('(continued)');
$GLOBALS['strLatexStructure'] = __('Structure of table @TABLE@');
}
protected function setProperties(): ExportPluginProperties
{
global $plugin_param;
$hide_structure = false;
if ($plugin_param['export_type'] === 'table' && ! $plugin_param['single_table']) {
$hide_structure = true;
}
$exportPluginProperties = new ExportPluginProperties();
$exportPluginProperties->setText('LaTeX');
$exportPluginProperties->setExtension('tex');
$exportPluginProperties->setMimeType('application/x-tex');
$exportPluginProperties->setOptionsText(__('Options'));
// create the root group that will be the options field for
// $exportPluginProperties
// this will be shown as "Format specific options"
$exportSpecificOptions = new OptionsPropertyRootGroup('Format Specific Options');
// general options main group
$generalOptions = new OptionsPropertyMainGroup('general_opts');
// create primary items and add them to the group
$leaf = new BoolPropertyItem(
'caption',
__('Include table caption')
);
$generalOptions->addProperty($leaf);
// add the main group to the root group
$exportSpecificOptions->addProperty($generalOptions);
// what to dump (structure/data/both) main group
$dumpWhat = new OptionsPropertyMainGroup(
'dump_what',
__('Dump table')
);
// create primary items and add them to the group
$leaf = new RadioPropertyItem('structure_or_data');
$leaf->setValues(
[
'structure' => __('structure'),
'data' => __('data'),
'structure_and_data' => __('structure and data'),
]
);
$dumpWhat->addProperty($leaf);
// add the main group to the root group
$exportSpecificOptions->addProperty($dumpWhat);
// structure options main group
if (! $hide_structure) {
$structureOptions = new OptionsPropertyMainGroup(
'structure',
__('Object creation options')
);
$structureOptions->setForce('data');
// create primary items and add them to the group
$leaf = new TextPropertyItem(
'structure_caption',
__('Table caption:')
);
$leaf->setDoc('faq6-27');
$structureOptions->addProperty($leaf);
$leaf = new TextPropertyItem(
'structure_continued_caption',
__('Table caption (continued):')
);
$leaf->setDoc('faq6-27');
$structureOptions->addProperty($leaf);
$leaf = new TextPropertyItem(
'structure_label',
__('Label key:')
);
$leaf->setDoc('faq6-27');
$structureOptions->addProperty($leaf);
$relationParameters = $this->relation->getRelationParameters();
if ($relationParameters->relationFeature !== null) {
$leaf = new BoolPropertyItem(
'relation',
__('Display foreign key relationships')
);
$structureOptions->addProperty($leaf);
}
$leaf = new BoolPropertyItem(
'comments',
__('Display comments')
);
$structureOptions->addProperty($leaf);
if ($relationParameters->browserTransformationFeature !== null) {
$leaf = new BoolPropertyItem(
'mime',
__('Display media types')
);
$structureOptions->addProperty($leaf);
}
// add the main group to the root group
$exportSpecificOptions->addProperty($structureOptions);
}
// data options main group
$dataOptions = new OptionsPropertyMainGroup(
'data',
__('Data dump options')
);
$dataOptions->setForce('structure');
// create primary items and add them to the group
$leaf = new BoolPropertyItem(
'columns',
__('Put columns names in the first row:')
);
$dataOptions->addProperty($leaf);
$leaf = new TextPropertyItem(
'data_caption',
__('Table caption:')
);
$leaf->setDoc('faq6-27');
$dataOptions->addProperty($leaf);
$leaf = new TextPropertyItem(
'data_continued_caption',
__('Table caption (continued):')
);
$leaf->setDoc('faq6-27');
$dataOptions->addProperty($leaf);
$leaf = new TextPropertyItem(
'data_label',
__('Label key:')
);
$leaf->setDoc('faq6-27');
$dataOptions->addProperty($leaf);
$leaf = new TextPropertyItem(
'null',
__('Replace NULL with:')
);
$dataOptions->addProperty($leaf);
// add the main group to the root group
$exportSpecificOptions->addProperty($dataOptions);
// set the options for the export plugin property item
$exportPluginProperties->setOptions($exportSpecificOptions);
return $exportPluginProperties;
}
/**
* Outputs export header
*/
public function exportHeader(): bool
{
global $crlf, $cfg, $dbi;
$head = '% phpMyAdmin LaTeX Dump' . $crlf
. '% version ' . Version::VERSION . $crlf
. '% https://www.phpmyadmin.net/' . $crlf
. '%' . $crlf
. '% ' . __('Host:') . ' ' . $cfg['Server']['host'];
if (! empty($cfg['Server']['port'])) {
$head .= ':' . $cfg['Server']['port'];
}
$head .= $crlf
. '% ' . __('Generation Time:') . ' '
. Util::localisedDate() . $crlf
. '% ' . __('Server version:') . ' ' . $dbi->getVersionString() . $crlf
. '% ' . __('PHP Version:') . ' ' . PHP_VERSION . $crlf;
return $this->export->outputHandler($head);
}
/**
* Outputs export footer
*/
public function exportFooter(): bool
{
return true;
}
/**
* Outputs database header
*
* @param string $db Database name
* @param string $dbAlias Aliases of db
*/
public function exportDBHeader($db, $dbAlias = ''): bool
{
if (empty($dbAlias)) {
$dbAlias = $db;
}
global $crlf;
$head = '% ' . $crlf
. '% ' . __('Database:') . ' \'' . $dbAlias . '\'' . $crlf
. '% ' . $crlf;
return $this->export->outputHandler($head);
}
/**
* Outputs database footer
*
* @param string $db Database name
*/
public function exportDBFooter($db): bool
{
return true;
}
/**
* Outputs CREATE DATABASE statement
*
* @param string $db Database name
* @param string $exportType 'server', 'database', 'table'
* @param string $dbAlias Aliases of db
*/
public function exportDBCreate($db, $exportType, $dbAlias = ''): bool
{
return true;
}
/**
* Outputs the content of a table in JSON format
*
* @param string $db database name
* @param string $table table name
* @param string $crlf the end of line sequence
* @param string $errorUrl the url to go back in case of error
* @param string $sqlQuery SQL query for obtaining data
* @param array $aliases Aliases of db/table/columns
*/
public function exportData(
$db,
$table,
$crlf,
$errorUrl,
$sqlQuery,
array $aliases = []
): bool {
global $dbi;
$db_alias = $db;
$table_alias = $table;
$this->initAlias($aliases, $db_alias, $table_alias);
$result = $dbi->tryQuery($sqlQuery, DatabaseInterface::CONNECT_USER, DatabaseInterface::QUERY_UNBUFFERED);
$columns_cnt = $result->numFields();
$columns = [];
$columns_alias = [];
foreach ($result->getFieldNames() as $i => $col_as) {
$columns[$i] = $col_as;
if (! empty($aliases[$db]['tables'][$table]['columns'][$col_as])) {
$col_as = $aliases[$db]['tables'][$table]['columns'][$col_as];
}
$columns_alias[$i] = $col_as;
}
$buffer = $crlf . '%' . $crlf . '% ' . __('Data:') . ' ' . $table_alias
. $crlf . '%' . $crlf . ' \\begin{longtable}{|';
for ($index = 0; $index < $columns_cnt; $index++) {
$buffer .= 'l|';
}
$buffer .= '} ' . $crlf;
$buffer .= ' \\hline \\endhead \\hline \\endfoot \\hline ' . $crlf;
if (isset($GLOBALS['latex_caption'])) {
$buffer .= ' \\caption{'
. Util::expandUserString(
$GLOBALS['latex_data_caption'],
[
'texEscape',
static::class,
],
[
'table' => $table_alias,
'database' => $db_alias,
]
)
. '} \\label{'
. Util::expandUserString(
$GLOBALS['latex_data_label'],
null,
[
'table' => $table_alias,
'database' => $db_alias,
]
)
. '} \\\\';
}
if (! $this->export->outputHandler($buffer)) {
return false;
}
// show column names
if (isset($GLOBALS['latex_columns'])) {
$buffer = '\\hline ';
for ($i = 0; $i < $columns_cnt; $i++) {
$buffer .= '\\multicolumn{1}{|c|}{\\textbf{'
. self::texEscape(stripslashes($columns_alias[$i])) . '}} & ';
}
$buffer = mb_substr($buffer, 0, -2) . '\\\\ \\hline \hline ';
if (! $this->export->outputHandler($buffer . ' \\endfirsthead ' . $crlf)) {
return false;
}
if (isset($GLOBALS['latex_caption'])) {
if (
! $this->export->outputHandler(
'\\caption{'
. Util::expandUserString(
$GLOBALS['latex_data_continued_caption'],
[
'texEscape',
static::class,
],
[
'table' => $table_alias,
'database' => $db_alias,
]
)
. '} \\\\ '
)
) {
return false;
}
}
if (! $this->export->outputHandler($buffer . '\\endhead \\endfoot' . $crlf)) {
return false;
}
} else {
if (! $this->export->outputHandler('\\\\ \hline')) {
return false;
}
}
// print the whole table
while ($record = $result->fetchAssoc()) {
$buffer = '';
// print each row
for ($i = 0; $i < $columns_cnt; $i++) {
if ($record[$columns[$i]] !== null && isset($record[$columns[$i]])) {
$column_value = self::texEscape(
stripslashes($record[$columns[$i]])
);
} else {
$column_value = $GLOBALS['latex_null'];
}
// last column ... no need for & character
if ($i == $columns_cnt - 1) {
$buffer .= $column_value;
} else {
$buffer .= $column_value . ' & ';
}
}
$buffer .= ' \\\\ \\hline ' . $crlf;
if (! $this->export->outputHandler($buffer)) {
return false;
}
}
$buffer = ' \\end{longtable}' . $crlf;
return $this->export->outputHandler($buffer);
}
/**
* Outputs result raw query
*
* @param string $errorUrl the url to go back in case of error
* @param string|null $db the database where the query is executed
* @param string $sqlQuery the rawquery to output
* @param string $crlf the end of line sequence
*/
public function exportRawQuery(string $errorUrl, ?string $db, string $sqlQuery, string $crlf): bool
{
global $dbi;
if ($db !== null) {
$dbi->selectDb($db);
}
return $this->exportData($db ?? '', '', $crlf, $errorUrl, $sqlQuery);
}
/**
* Outputs table's structure
*
* @param string $db database name
* @param string $table table name
* @param string $crlf the end of line sequence
* @param string $errorUrl the url to go back in case of error
* @param string $exportMode 'create_table', 'triggers', 'create_view',
* 'stand_in'
* @param string $exportType 'server', 'database', 'table'
* @param bool $do_relation whether to include relation comments
* @param bool $do_comments whether to include the pmadb-style column
* comments as comments in the structure;
* this is deprecated but the parameter is
* left here because /export calls
* exportStructure() also for other
* export types which use this parameter
* @param bool $do_mime whether to include mime comments
* @param bool $dates whether to include creation/update/check dates
* @param array $aliases Aliases of db/table/columns
*/
public function exportStructure(
$db,
$table,
$crlf,
$errorUrl,
$exportMode,
$exportType,
$do_relation = false,
$do_comments = false,
$do_mime = false,
$dates = false,
array $aliases = []
): bool {
global $dbi;
$db_alias = $db;
$table_alias = $table;
$this->initAlias($aliases, $db_alias, $table_alias);
$relationParameters = $this->relation->getRelationParameters();
/* We do not export triggers */
if ($exportMode === 'triggers') {
return true;
}
/**
* Get the unique keys in the table
*/
$unique_keys = [];
$keys = $dbi->getTableIndexes($db, $table);
foreach ($keys as $key) {
if ($key['Non_unique'] != 0) {
continue;
}
$unique_keys[] = $key['Column_name'];
}
/**
* Gets fields properties
*/
$dbi->selectDb($db);
// Check if we can use Relations
[$res_rel, $have_rel] = $this->relation->getRelationsAndStatus(
$do_relation && $relationParameters->relationFeature !== null,
$db,
$table
);
/**
* Displays the table structure
*/
$buffer = $crlf . '%' . $crlf . '% ' . __('Structure:') . ' '
. $table_alias . $crlf . '%' . $crlf . ' \\begin{longtable}{';
if (! $this->export->outputHandler($buffer)) {
return false;
}
$alignment = '|l|c|c|c|';
if ($do_relation && $have_rel) {
$alignment .= 'l|';
}
if ($do_comments) {
$alignment .= 'l|';
}
if ($do_mime && $relationParameters->browserTransformationFeature !== null) {
$alignment .= 'l|';
}
$buffer = $alignment . '} ' . $crlf;
$header = ' \\hline ';
$header .= '\\multicolumn{1}{|c|}{\\textbf{' . __('Column')
. '}} & \\multicolumn{1}{|c|}{\\textbf{' . __('Type')
. '}} & \\multicolumn{1}{|c|}{\\textbf{' . __('Null')
. '}} & \\multicolumn{1}{|c|}{\\textbf{' . __('Default') . '}}';
if ($do_relation && $have_rel) {
$header .= ' & \\multicolumn{1}{|c|}{\\textbf{' . __('Links to') . '}}';
}
if ($do_comments) {
$header .= ' & \\multicolumn{1}{|c|}{\\textbf{' . __('Comments') . '}}';
$comments = $this->relation->getComments($db, $table);
}
if ($do_mime && $relationParameters->browserTransformationFeature !== null) {
$header .= ' & \\multicolumn{1}{|c|}{\\textbf{MIME}}';
$mime_map = $this->transformations->getMime($db, $table, true);
}
// Table caption for first page and label
if (isset($GLOBALS['latex_caption'])) {
$buffer .= ' \\caption{'
. Util::expandUserString(
$GLOBALS['latex_structure_caption'],
[
'texEscape',
static::class,
],
[
'table' => $table_alias,
'database' => $db_alias,
]
)
. '} \\label{'
. Util::expandUserString(
$GLOBALS['latex_structure_label'],
null,
[
'table' => $table_alias,
'database' => $db_alias,
]
)
. '} \\\\' . $crlf;
}
$buffer .= $header . ' \\\\ \\hline \\hline' . $crlf
. '\\endfirsthead' . $crlf;
// Table caption on next pages
if (isset($GLOBALS['latex_caption'])) {
$buffer .= ' \\caption{'
. Util::expandUserString(
$GLOBALS['latex_structure_continued_caption'],
[
'texEscape',
static::class,
],
[
'table' => $table_alias,
'database' => $db_alias,
]
)
. '} \\\\ ' . $crlf;
}
$buffer .= $header . ' \\\\ \\hline \\hline \\endhead \\endfoot ' . $crlf;
if (! $this->export->outputHandler($buffer)) {
return false;
}
$fields = $dbi->getColumns($db, $table);
foreach ($fields as $row) {
$extracted_columnspec = Util::extractColumnSpec($row['Type']);
$type = $extracted_columnspec['print_type'];
if (empty($type)) {
$type = ' ';
}
if (! isset($row['Default'])) {
if ($row['Null'] !== 'NO') {
$row['Default'] = 'NULL';
}
}
$field_name = $col_as = $row['Field'];
if (! empty($aliases[$db]['tables'][$table]['columns'][$col_as])) {
$col_as = $aliases[$db]['tables'][$table]['columns'][$col_as];
}
$local_buffer = $col_as . "\000" . $type . "\000"
. ($row['Null'] == '' || $row['Null'] === 'NO'
? __('No') : __('Yes'))
. "\000" . ($row['Default'] ?? '');
if ($do_relation && $have_rel) {
$local_buffer .= "\000";
$local_buffer .= $this->getRelationString($res_rel, $field_name, $db, $aliases);
}
if ($do_comments && $relationParameters->columnCommentsFeature !== null) {
$local_buffer .= "\000";
if (isset($comments[$field_name])) {
$local_buffer .= $comments[$field_name];
}
}
if ($do_mime && $relationParameters->browserTransformationFeature !== null) {
$local_buffer .= "\000";
if (isset($mime_map[$field_name])) {
$local_buffer .= str_replace('_', '/', $mime_map[$field_name]['mimetype']);
}
}
$local_buffer = self::texEscape($local_buffer);
if ($row['Key'] === 'PRI') {
$pos = (int) mb_strpos($local_buffer, "\000");
$local_buffer = '\\textit{'
.
mb_substr($local_buffer, 0, $pos)
. '}' .
mb_substr($local_buffer, $pos);
}
if (in_array($field_name, $unique_keys)) {
$pos = (int) mb_strpos($local_buffer, "\000");
$local_buffer = '\\textbf{'
.
mb_substr($local_buffer, 0, $pos)
. '}' .
mb_substr($local_buffer, $pos);
}
$buffer = str_replace("\000", ' & ', $local_buffer);
$buffer .= ' \\\\ \\hline ' . $crlf;
if (! $this->export->outputHandler($buffer)) {
return false;
}
}
$buffer = ' \\end{longtable}' . $crlf;
return $this->export->outputHandler($buffer);
}
/**
* Escapes some special characters for use in TeX/LaTeX
*
* @param string $string the string to convert
*
* @return string the converted string with escape codes
*/
public static function texEscape($string)
{
$escape = [
'$',
'%',
'{',
'}',
'&',
'#',
'_',
'^',
];
$cnt_escape = count($escape);
for ($k = 0; $k < $cnt_escape; $k++) {
$string = str_replace($escape[$k], '\\' . $escape[$k], $string);
}
return $string;
}
}

View file

@ -1,383 +0,0 @@
<?php
/**
* Set of functions used to build MediaWiki dumps of tables
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Export;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\Plugins\ExportPlugin;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyMainGroup;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyRootGroup;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertySubgroup;
use PhpMyAdmin\Properties\Options\Items\BoolPropertyItem;
use PhpMyAdmin\Properties\Options\Items\RadioPropertyItem;
use PhpMyAdmin\Properties\Plugins\ExportPluginProperties;
use PhpMyAdmin\Util;
use function __;
use function array_values;
use function count;
use function htmlspecialchars;
use function str_repeat;
/**
* Handles the export for the MediaWiki class
*/
class ExportMediawiki extends ExportPlugin
{
/**
* @psalm-return non-empty-lowercase-string
*/
public function getName(): string
{
return 'mediawiki';
}
protected function setProperties(): ExportPluginProperties
{
$exportPluginProperties = new ExportPluginProperties();
$exportPluginProperties->setText('MediaWiki Table');
$exportPluginProperties->setExtension('mediawiki');
$exportPluginProperties->setMimeType('text/plain');
$exportPluginProperties->setOptionsText(__('Options'));
// create the root group that will be the options field for
// $exportPluginProperties
// this will be shown as "Format specific options"
$exportSpecificOptions = new OptionsPropertyRootGroup('Format Specific Options');
// general options main group
$generalOptions = new OptionsPropertyMainGroup(
'general_opts',
__('Dump table')
);
// what to dump (structure/data/both)
$subgroup = new OptionsPropertySubgroup(
'dump_table',
__('Dump table')
);
$leaf = new RadioPropertyItem('structure_or_data');
$leaf->setValues(
[
'structure' => __('structure'),
'data' => __('data'),
'structure_and_data' => __('structure and data'),
]
);
$subgroup->setSubgroupHeader($leaf);
$generalOptions->addProperty($subgroup);
// export table name
$leaf = new BoolPropertyItem(
'caption',
__('Export table names')
);
$generalOptions->addProperty($leaf);
// export table headers
$leaf = new BoolPropertyItem(
'headers',
__('Export table headers')
);
$generalOptions->addProperty($leaf);
//add the main group to the root group
$exportSpecificOptions->addProperty($generalOptions);
// set the options for the export plugin property item
$exportPluginProperties->setOptions($exportSpecificOptions);
return $exportPluginProperties;
}
/**
* Outputs export header
*/
public function exportHeader(): bool
{
return true;
}
/**
* Outputs export footer
*/
public function exportFooter(): bool
{
return true;
}
/**
* Outputs database header
*
* @param string $db Database name
* @param string $dbAlias Alias of db
*/
public function exportDBHeader($db, $dbAlias = ''): bool
{
return true;
}
/**
* Outputs database footer
*
* @param string $db Database name
*/
public function exportDBFooter($db): bool
{
return true;
}
/**
* Outputs CREATE DATABASE statement
*
* @param string $db Database name
* @param string $exportType 'server', 'database', 'table'
* @param string $dbAlias Aliases of db
*/
public function exportDBCreate($db, $exportType, $dbAlias = ''): bool
{
return true;
}
/**
* Outputs table's structure
*
* @param string $db database name
* @param string $table table name
* @param string $crlf the end of line sequence
* @param string $errorUrl the url to go back in case of error
* @param string $exportMode 'create_table','triggers','create_view',
* 'stand_in'
* @param string $exportType 'server', 'database', 'table'
* @param bool $do_relation whether to include relation comments
* @param bool $do_comments whether to include the pmadb-style column
* comments as comments in the structure; this is
* deprecated but the parameter is left here
* because /export calls exportStructure()
* also for other export types which use this
* parameter
* @param bool $do_mime whether to include mime comments
* @param bool $dates whether to include creation/update/check dates
* @param array $aliases Aliases of db/table/columns
*/
public function exportStructure(
$db,
$table,
$crlf,
$errorUrl,
$exportMode,
$exportType,
$do_relation = false,
$do_comments = false,
$do_mime = false,
$dates = false,
array $aliases = []
): bool {
global $dbi;
$db_alias = $db;
$table_alias = $table;
$this->initAlias($aliases, $db_alias, $table_alias);
$output = '';
switch ($exportMode) {
case 'create_table':
$columns = $dbi->getColumns($db, $table);
$columns = array_values($columns);
$row_cnt = count($columns);
// Print structure comment
$output = $this->exportComment(
'Table structure for '
. Util::backquote($table_alias)
);
// Begin the table construction
$output .= '{| class="wikitable" style="text-align:center;"'
. $this->exportCRLF();
// Add the table name
if (isset($GLOBALS['mediawiki_caption'])) {
$output .= "|+'''" . $table_alias . "'''" . $this->exportCRLF();
}
// Add the table headers
if (isset($GLOBALS['mediawiki_headers'])) {
$output .= '|- style="background:#ffdead;"' . $this->exportCRLF();
$output .= '! style="background:#ffffff" | '
. $this->exportCRLF();
for ($i = 0; $i < $row_cnt; ++$i) {
$col_as = $columns[$i]['Field'];
if (! empty($aliases[$db]['tables'][$table]['columns'][$col_as])) {
$col_as = $aliases[$db]['tables'][$table]['columns'][$col_as];
}
$output .= ' | ' . $col_as . $this->exportCRLF();
}
}
// Add the table structure
$output .= '|-' . $this->exportCRLF();
$output .= '! Type' . $this->exportCRLF();
for ($i = 0; $i < $row_cnt; ++$i) {
$output .= ' | ' . $columns[$i]['Type'] . $this->exportCRLF();
}
$output .= '|-' . $this->exportCRLF();
$output .= '! Null' . $this->exportCRLF();
for ($i = 0; $i < $row_cnt; ++$i) {
$output .= ' | ' . $columns[$i]['Null'] . $this->exportCRLF();
}
$output .= '|-' . $this->exportCRLF();
$output .= '! Default' . $this->exportCRLF();
for ($i = 0; $i < $row_cnt; ++$i) {
$output .= ' | ' . $columns[$i]['Default'] . $this->exportCRLF();
}
$output .= '|-' . $this->exportCRLF();
$output .= '! Extra' . $this->exportCRLF();
for ($i = 0; $i < $row_cnt; ++$i) {
$output .= ' | ' . $columns[$i]['Extra'] . $this->exportCRLF();
}
$output .= '|}' . str_repeat($this->exportCRLF(), 2);
break;
}
return $this->export->outputHandler($output);
}
/**
* Outputs the content of a table in MediaWiki format
*
* @param string $db database name
* @param string $table table name
* @param string $crlf the end of line sequence
* @param string $errorUrl the url to go back in case of error
* @param string $sqlQuery SQL query for obtaining data
* @param array $aliases Aliases of db/table/columns
*/
public function exportData(
$db,
$table,
$crlf,
$errorUrl,
$sqlQuery,
array $aliases = []
): bool {
global $dbi;
$db_alias = $db;
$table_alias = $table;
$this->initAlias($aliases, $db_alias, $table_alias);
// Print data comment
$output = $this->exportComment(
$table_alias != ''
? 'Table data for ' . Util::backquote($table_alias)
: 'Query results'
);
// Begin the table construction
// Use the "wikitable" class for style
// Use the "sortable" class for allowing tables to be sorted by column
$output .= '{| class="wikitable sortable" style="text-align:center;"'
. $this->exportCRLF();
// Add the table name
if (isset($GLOBALS['mediawiki_caption'])) {
$output .= "|+'''" . $table_alias . "'''" . $this->exportCRLF();
}
// Add the table headers
if (isset($GLOBALS['mediawiki_headers'])) {
// Get column names
$column_names = $dbi->getColumnNames($db, $table);
// Add column names as table headers
if ($column_names !== []) {
// Use '|-' for separating rows
$output .= '|-' . $this->exportCRLF();
// Use '!' for separating table headers
foreach ($column_names as $column) {
if (! empty($aliases[$db]['tables'][$table]['columns'][$column])) {
$column = $aliases[$db]['tables'][$table]['columns'][$column];
}
$output .= ' ! ' . $column . '' . $this->exportCRLF();
}
}
}
// Get the table data from the database
$result = $dbi->query($sqlQuery, DatabaseInterface::CONNECT_USER, DatabaseInterface::QUERY_UNBUFFERED);
$fields_cnt = $result->numFields();
while ($row = $result->fetchRow()) {
$output .= '|-' . $this->exportCRLF();
// Use '|' for separating table columns
for ($i = 0; $i < $fields_cnt; ++$i) {
$output .= ' | ' . $row[$i] . '' . $this->exportCRLF();
}
}
// End table construction
$output .= '|}' . str_repeat($this->exportCRLF(), 2);
return $this->export->outputHandler($output);
}
/**
* Outputs result raw query in MediaWiki format
*
* @param string $errorUrl the url to go back in case of error
* @param string|null $db the database where the query is executed
* @param string $sqlQuery the rawquery to output
* @param string $crlf the end of line sequence
*/
public function exportRawQuery(string $errorUrl, ?string $db, string $sqlQuery, string $crlf): bool
{
global $dbi;
if ($db !== null) {
$dbi->selectDb($db);
}
return $this->exportData($db ?? '', '', $crlf, $errorUrl, $sqlQuery);
}
/**
* Outputs comments containing info about the exported tables
*
* @param string $text Text of comment
*
* @return string The formatted comment
*/
private function exportComment($text = '')
{
// see https://www.mediawiki.org/wiki/Help:Formatting
$comment = $this->exportCRLF();
$comment .= '<!--' . $this->exportCRLF();
$comment .= htmlspecialchars($text) . $this->exportCRLF();
$comment .= '-->' . str_repeat($this->exportCRLF(), 2);
return $comment;
}
/**
* Outputs CRLF
*
* @return string CRLF
*/
private function exportCRLF()
{
// The CRLF expected by the mediawiki format is "\n"
return "\n";
}
}

View file

@ -1,329 +0,0 @@
<?php
/**
* Set of functions used to build OpenDocument Spreadsheet dumps of tables
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Export;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\FieldMetadata;
use PhpMyAdmin\OpenDocument;
use PhpMyAdmin\Plugins\ExportPlugin;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyMainGroup;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyRootGroup;
use PhpMyAdmin\Properties\Options\Items\BoolPropertyItem;
use PhpMyAdmin\Properties\Options\Items\HiddenPropertyItem;
use PhpMyAdmin\Properties\Options\Items\TextPropertyItem;
use PhpMyAdmin\Properties\Plugins\ExportPluginProperties;
use function __;
use function bin2hex;
use function date;
use function htmlspecialchars;
use function stripslashes;
use function strtotime;
/**
* Handles the export for the ODS class
*/
class ExportOds extends ExportPlugin
{
protected function init(): void
{
$GLOBALS['ods_buffer'] = '';
}
/**
* @psalm-return non-empty-lowercase-string
*/
public function getName(): string
{
return 'ods';
}
protected function setProperties(): ExportPluginProperties
{
$exportPluginProperties = new ExportPluginProperties();
$exportPluginProperties->setText('OpenDocument Spreadsheet');
$exportPluginProperties->setExtension('ods');
$exportPluginProperties->setMimeType('application/vnd.oasis.opendocument.spreadsheet');
$exportPluginProperties->setForceFile(true);
$exportPluginProperties->setOptionsText(__('Options'));
// create the root group that will be the options field for
// $exportPluginProperties
// this will be shown as "Format specific options"
$exportSpecificOptions = new OptionsPropertyRootGroup('Format Specific Options');
// general options main group
$generalOptions = new OptionsPropertyMainGroup('general_opts');
// create primary items and add them to the group
$leaf = new TextPropertyItem(
'null',
__('Replace NULL with:')
);
$generalOptions->addProperty($leaf);
$leaf = new BoolPropertyItem(
'columns',
__('Put columns names in the first row')
);
$generalOptions->addProperty($leaf);
$leaf = new HiddenPropertyItem('structure_or_data');
$generalOptions->addProperty($leaf);
// add the main group to the root group
$exportSpecificOptions->addProperty($generalOptions);
// set the options for the export plugin property item
$exportPluginProperties->setOptions($exportSpecificOptions);
return $exportPluginProperties;
}
/**
* Outputs export header
*/
public function exportHeader(): bool
{
$GLOBALS['ods_buffer'] .= '<?xml version="1.0" encoding="utf-8"?' . '>'
. '<office:document-content '
. OpenDocument::NS . ' office:version="1.0">'
. '<office:automatic-styles>'
. '<number:date-style style:name="N37"'
. ' number:automatic-order="true">'
. '<number:month number:style="long"/>'
. '<number:text>/</number:text>'
. '<number:day number:style="long"/>'
. '<number:text>/</number:text>'
. '<number:year/>'
. '</number:date-style>'
. '<number:time-style style:name="N43">'
. '<number:hours number:style="long"/>'
. '<number:text>:</number:text>'
. '<number:minutes number:style="long"/>'
. '<number:text>:</number:text>'
. '<number:seconds number:style="long"/>'
. '<number:text> </number:text>'
. '<number:am-pm/>'
. '</number:time-style>'
. '<number:date-style style:name="N50"'
. ' number:automatic-order="true"'
. ' number:format-source="language">'
. '<number:month/>'
. '<number:text>/</number:text>'
. '<number:day/>'
. '<number:text>/</number:text>'
. '<number:year/>'
. '<number:text> </number:text>'
. '<number:hours number:style="long"/>'
. '<number:text>:</number:text>'
. '<number:minutes number:style="long"/>'
. '<number:text> </number:text>'
. '<number:am-pm/>'
. '</number:date-style>'
. '<style:style style:name="DateCell" style:family="table-cell"'
. ' style:parent-style-name="Default" style:data-style-name="N37"/>'
. '<style:style style:name="TimeCell" style:family="table-cell"'
. ' style:parent-style-name="Default" style:data-style-name="N43"/>'
. '<style:style style:name="DateTimeCell" style:family="table-cell"'
. ' style:parent-style-name="Default" style:data-style-name="N50"/>'
. '</office:automatic-styles>'
. '<office:body>'
. '<office:spreadsheet>';
return true;
}
/**
* Outputs export footer
*/
public function exportFooter(): bool
{
$GLOBALS['ods_buffer'] .= '</office:spreadsheet></office:body></office:document-content>';
return $this->export->outputHandler(
OpenDocument::create(
'application/vnd.oasis.opendocument.spreadsheet',
$GLOBALS['ods_buffer']
)
);
}
/**
* Outputs database header
*
* @param string $db Database name
* @param string $dbAlias Aliases of db
*/
public function exportDBHeader($db, $dbAlias = ''): bool
{
return true;
}
/**
* Outputs database footer
*
* @param string $db Database name
*/
public function exportDBFooter($db): bool
{
return true;
}
/**
* Outputs CREATE DATABASE statement
*
* @param string $db Database name
* @param string $exportType 'server', 'database', 'table'
* @param string $dbAlias Aliases of db
*/
public function exportDBCreate($db, $exportType, $dbAlias = ''): bool
{
return true;
}
/**
* Outputs the content of a table in NHibernate format
*
* @param string $db database name
* @param string $table table name
* @param string $crlf the end of line sequence
* @param string $errorUrl the url to go back in case of error
* @param string $sqlQuery SQL query for obtaining data
* @param array $aliases Aliases of db/table/columns
*/
public function exportData(
$db,
$table,
$crlf,
$errorUrl,
$sqlQuery,
array $aliases = []
): bool {
global $what, $dbi;
$db_alias = $db;
$table_alias = $table;
$this->initAlias($aliases, $db_alias, $table_alias);
// Gets the data from the database
$result = $dbi->query($sqlQuery, DatabaseInterface::CONNECT_USER, DatabaseInterface::QUERY_UNBUFFERED);
$fields_cnt = $result->numFields();
/** @var FieldMetadata[] $fieldsMeta */
$fieldsMeta = $dbi->getFieldsMeta($result);
$GLOBALS['ods_buffer'] .= '<table:table table:name="' . htmlspecialchars($table_alias) . '">';
// If required, get fields name at the first line
if (isset($GLOBALS[$what . '_columns'])) {
$GLOBALS['ods_buffer'] .= '<table:table-row>';
foreach ($fieldsMeta as $field) {
$col_as = $field->name;
if (! empty($aliases[$db]['tables'][$table]['columns'][$col_as])) {
$col_as = $aliases[$db]['tables'][$table]['columns'][$col_as];
}
$GLOBALS['ods_buffer'] .= '<table:table-cell office:value-type="string">'
. '<text:p>'
. htmlspecialchars(
stripslashes($col_as)
)
. '</text:p>'
. '</table:table-cell>';
}
$GLOBALS['ods_buffer'] .= '</table:table-row>';
}
// Format the data
while ($row = $result->fetchRow()) {
$GLOBALS['ods_buffer'] .= '<table:table-row>';
for ($j = 0; $j < $fields_cnt; $j++) {
if ($fieldsMeta[$j]->isMappedTypeGeometry) {
// export GIS types as hex
$row[$j] = '0x' . bin2hex($row[$j]);
}
if (! isset($row[$j])) {
$GLOBALS['ods_buffer'] .= '<table:table-cell office:value-type="string">'
. '<text:p>'
. htmlspecialchars($GLOBALS[$what . '_null'])
. '</text:p>'
. '</table:table-cell>';
} elseif ($fieldsMeta[$j]->isBinary && $fieldsMeta[$j]->isBlob) {
// ignore BLOB
$GLOBALS['ods_buffer'] .= '<table:table-cell office:value-type="string">'
. '<text:p></text:p>'
. '</table:table-cell>';
} elseif ($fieldsMeta[$j]->isType(FieldMetadata::TYPE_DATE)) {
$GLOBALS['ods_buffer'] .= '<table:table-cell office:value-type="date"'
. ' office:date-value="'
. date('Y-m-d', strtotime($row[$j]))
. '" table:style-name="DateCell">'
. '<text:p>'
. htmlspecialchars($row[$j])
. '</text:p>'
. '</table:table-cell>';
} elseif ($fieldsMeta[$j]->isType(FieldMetadata::TYPE_TIME)) {
$GLOBALS['ods_buffer'] .= '<table:table-cell office:value-type="time"'
. ' office:time-value="'
. date('\P\TH\Hi\Ms\S', strtotime($row[$j]))
. '" table:style-name="TimeCell">'
. '<text:p>'
. htmlspecialchars($row[$j])
. '</text:p>'
. '</table:table-cell>';
} elseif ($fieldsMeta[$j]->isType(FieldMetadata::TYPE_DATETIME)) {
$GLOBALS['ods_buffer'] .= '<table:table-cell office:value-type="date"'
. ' office:date-value="'
. date('Y-m-d\TH:i:s', strtotime($row[$j]))
. '" table:style-name="DateTimeCell">'
. '<text:p>'
. htmlspecialchars($row[$j])
. '</text:p>'
. '</table:table-cell>';
} elseif (
$fieldsMeta[$j]->isNumeric
) {
$GLOBALS['ods_buffer'] .= '<table:table-cell office:value-type="float"'
. ' office:value="' . $row[$j] . '" >'
. '<text:p>'
. htmlspecialchars($row[$j])
. '</text:p>'
. '</table:table-cell>';
} else {
$GLOBALS['ods_buffer'] .= '<table:table-cell office:value-type="string">'
. '<text:p>'
. htmlspecialchars($row[$j])
. '</text:p>'
. '</table:table-cell>';
}
}
$GLOBALS['ods_buffer'] .= '</table:table-row>';
}
$GLOBALS['ods_buffer'] .= '</table:table>';
return true;
}
/**
* Outputs result raw query in ODS format
*
* @param string $errorUrl the url to go back in case of error
* @param string|null $db the database where the query is executed
* @param string $sqlQuery the rawquery to output
* @param string $crlf the end of line sequence
*/
public function exportRawQuery(string $errorUrl, ?string $db, string $sqlQuery, string $crlf): bool
{
global $dbi;
if ($db !== null) {
$dbi->selectDb($db);
}
return $this->exportData($db ?? '', '', $crlf, $errorUrl, $sqlQuery);
}
}

View file

@ -1,797 +0,0 @@
<?php
/**
* Set of functions used to build OpenDocument Text dumps of tables
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Export;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\FieldMetadata;
use PhpMyAdmin\OpenDocument;
use PhpMyAdmin\Plugins\ExportPlugin;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyMainGroup;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyRootGroup;
use PhpMyAdmin\Properties\Options\Items\BoolPropertyItem;
use PhpMyAdmin\Properties\Options\Items\RadioPropertyItem;
use PhpMyAdmin\Properties\Options\Items\TextPropertyItem;
use PhpMyAdmin\Properties\Plugins\ExportPluginProperties;
use PhpMyAdmin\Util;
use function __;
use function bin2hex;
use function htmlspecialchars;
use function str_replace;
use function stripslashes;
/**
* Handles the export for the ODT class
*/
class ExportOdt extends ExportPlugin
{
protected function init(): void
{
$GLOBALS['odt_buffer'] = '';
}
/**
* @psalm-return non-empty-lowercase-string
*/
public function getName(): string
{
return 'odt';
}
protected function setProperties(): ExportPluginProperties
{
global $plugin_param;
$hide_structure = false;
if ($plugin_param['export_type'] === 'table' && ! $plugin_param['single_table']) {
$hide_structure = true;
}
$exportPluginProperties = new ExportPluginProperties();
$exportPluginProperties->setText('OpenDocument Text');
$exportPluginProperties->setExtension('odt');
$exportPluginProperties->setMimeType('application/vnd.oasis.opendocument.text');
$exportPluginProperties->setForceFile(true);
$exportPluginProperties->setOptionsText(__('Options'));
// create the root group that will be the options field for
// $exportPluginProperties
// this will be shown as "Format specific options"
$exportSpecificOptions = new OptionsPropertyRootGroup('Format Specific Options');
// what to dump (structure/data/both) main group
$dumpWhat = new OptionsPropertyMainGroup(
'general_opts',
__('Dump table')
);
// create primary items and add them to the group
$leaf = new RadioPropertyItem('structure_or_data');
$leaf->setValues(
[
'structure' => __('structure'),
'data' => __('data'),
'structure_and_data' => __('structure and data'),
]
);
$dumpWhat->addProperty($leaf);
// add the main group to the root group
$exportSpecificOptions->addProperty($dumpWhat);
// structure options main group
if (! $hide_structure) {
$structureOptions = new OptionsPropertyMainGroup(
'structure',
__('Object creation options')
);
$structureOptions->setForce('data');
$relationParameters = $this->relation->getRelationParameters();
// create primary items and add them to the group
if ($relationParameters->relationFeature !== null) {
$leaf = new BoolPropertyItem(
'relation',
__('Display foreign key relationships')
);
$structureOptions->addProperty($leaf);
}
$leaf = new BoolPropertyItem(
'comments',
__('Display comments')
);
$structureOptions->addProperty($leaf);
if ($relationParameters->browserTransformationFeature !== null) {
$leaf = new BoolPropertyItem(
'mime',
__('Display media types')
);
$structureOptions->addProperty($leaf);
}
// add the main group to the root group
$exportSpecificOptions->addProperty($structureOptions);
}
// data options main group
$dataOptions = new OptionsPropertyMainGroup(
'data',
__('Data dump options')
);
$dataOptions->setForce('structure');
// create primary items and add them to the group
$leaf = new BoolPropertyItem(
'columns',
__('Put columns names in the first row')
);
$dataOptions->addProperty($leaf);
$leaf = new TextPropertyItem(
'null',
__('Replace NULL with:')
);
$dataOptions->addProperty($leaf);
// add the main group to the root group
$exportSpecificOptions->addProperty($dataOptions);
// set the options for the export plugin property item
$exportPluginProperties->setOptions($exportSpecificOptions);
return $exportPluginProperties;
}
/**
* Outputs export header
*/
public function exportHeader(): bool
{
$GLOBALS['odt_buffer'] .= '<?xml version="1.0" encoding="utf-8"?' . '>'
. '<office:document-content '
. OpenDocument::NS . ' office:version="1.0">'
. '<office:body>'
. '<office:text>';
return true;
}
/**
* Outputs export footer
*/
public function exportFooter(): bool
{
$GLOBALS['odt_buffer'] .= '</office:text></office:body></office:document-content>';
return $this->export->outputHandler(OpenDocument::create(
'application/vnd.oasis.opendocument.text',
$GLOBALS['odt_buffer']
));
}
/**
* Outputs database header
*
* @param string $db Database name
* @param string $dbAlias Aliases of db
*/
public function exportDBHeader($db, $dbAlias = ''): bool
{
if (empty($dbAlias)) {
$dbAlias = $db;
}
$GLOBALS['odt_buffer'] .= '<text:h text:outline-level="1" text:style-name="Heading_1"'
. ' text:is-list-header="true">'
. __('Database') . ' ' . htmlspecialchars($dbAlias)
. '</text:h>';
return true;
}
/**
* Outputs database footer
*
* @param string $db Database name
*/
public function exportDBFooter($db): bool
{
return true;
}
/**
* Outputs CREATE DATABASE statement
*
* @param string $db Database name
* @param string $exportType 'server', 'database', 'table'
* @param string $dbAlias Aliases of db
*/
public function exportDBCreate($db, $exportType, $dbAlias = ''): bool
{
return true;
}
/**
* Outputs the content of a table in NHibernate format
*
* @param string $db database name
* @param string $table table name
* @param string $crlf the end of line sequence
* @param string $errorUrl the url to go back in case of error
* @param string $sqlQuery SQL query for obtaining data
* @param array $aliases Aliases of db/table/columns
*/
public function exportData(
$db,
$table,
$crlf,
$errorUrl,
$sqlQuery,
array $aliases = []
): bool {
global $what, $dbi;
$db_alias = $db;
$table_alias = $table;
$this->initAlias($aliases, $db_alias, $table_alias);
// Gets the data from the database
$result = $dbi->query($sqlQuery, DatabaseInterface::CONNECT_USER, DatabaseInterface::QUERY_UNBUFFERED);
$fields_cnt = $result->numFields();
/** @var FieldMetadata[] $fieldsMeta */
$fieldsMeta = $dbi->getFieldsMeta($result);
$GLOBALS['odt_buffer'] .= '<text:h text:outline-level="2" text:style-name="Heading_2"'
. ' text:is-list-header="true">';
$table_alias != ''
? $GLOBALS['odt_buffer'] .= __('Dumping data for table') . ' ' . htmlspecialchars($table_alias)
: $GLOBALS['odt_buffer'] .= __('Dumping data for query result');
$GLOBALS['odt_buffer'] .= '</text:h>'
. '<table:table'
. ' table:name="' . htmlspecialchars($table_alias) . '_structure">'
. '<table:table-column'
. ' table:number-columns-repeated="' . $fields_cnt . '"/>';
// If required, get fields name at the first line
if (isset($GLOBALS[$what . '_columns'])) {
$GLOBALS['odt_buffer'] .= '<table:table-row>';
foreach ($fieldsMeta as $field) {
$col_as = $field->name;
if (! empty($aliases[$db]['tables'][$table]['columns'][$col_as])) {
$col_as = $aliases[$db]['tables'][$table]['columns'][$col_as];
}
$GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">'
. '<text:p>'
. htmlspecialchars(
stripslashes($col_as)
)
. '</text:p>'
. '</table:table-cell>';
}
$GLOBALS['odt_buffer'] .= '</table:table-row>';
}
// Format the data
while ($row = $result->fetchRow()) {
$GLOBALS['odt_buffer'] .= '<table:table-row>';
for ($j = 0; $j < $fields_cnt; $j++) {
if ($fieldsMeta[$j]->isMappedTypeGeometry) {
// export GIS types as hex
$row[$j] = '0x' . bin2hex($row[$j]);
}
if (! isset($row[$j])) {
$GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">'
. '<text:p>'
. htmlspecialchars($GLOBALS[$what . '_null'])
. '</text:p>'
. '</table:table-cell>';
} elseif ($fieldsMeta[$j]->isBinary && $fieldsMeta[$j]->isBlob) {
// ignore BLOB
$GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">'
. '<text:p></text:p>'
. '</table:table-cell>';
} elseif (
$fieldsMeta[$j]->isNumeric
) {
$GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="float"'
. ' office:value="' . $row[$j] . '" >'
. '<text:p>'
. htmlspecialchars($row[$j])
. '</text:p>'
. '</table:table-cell>';
} else {
$GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">'
. '<text:p>'
. htmlspecialchars($row[$j])
. '</text:p>'
. '</table:table-cell>';
}
}
$GLOBALS['odt_buffer'] .= '</table:table-row>';
}
$GLOBALS['odt_buffer'] .= '</table:table>';
return true;
}
/**
* Outputs result raw query in ODT format
*
* @param string $errorUrl the url to go back in case of error
* @param string|null $db the database where the query is executed
* @param string $sqlQuery the rawquery to output
* @param string $crlf the end of line sequence
*/
public function exportRawQuery(string $errorUrl, ?string $db, string $sqlQuery, string $crlf): bool
{
global $dbi;
if ($db !== null) {
$dbi->selectDb($db);
}
return $this->exportData($db ?? '', '', $crlf, $errorUrl, $sqlQuery);
}
/**
* Returns a stand-in CREATE definition to resolve view dependencies
*
* @param string $db the database name
* @param string $view the view name
* @param string $crlf the end of line sequence
* @param array $aliases Aliases of db/table/columns
*
* @return string resulting definition
*/
public function getTableDefStandIn($db, $view, $crlf, $aliases = [])
{
global $dbi;
$db_alias = $db;
$view_alias = $view;
$this->initAlias($aliases, $db_alias, $view_alias);
/**
* Gets fields properties
*/
$dbi->selectDb($db);
/**
* Displays the table structure
*/
$GLOBALS['odt_buffer'] .= '<table:table table:name="'
. htmlspecialchars($view_alias) . '_data">';
$columns_cnt = 4;
$GLOBALS['odt_buffer'] .= '<table:table-column'
. ' table:number-columns-repeated="' . $columns_cnt . '"/>';
/* Header */
$GLOBALS['odt_buffer'] .= '<table:table-row>'
. '<table:table-cell office:value-type="string">'
. '<text:p>' . __('Column') . '</text:p>'
. '</table:table-cell>'
. '<table:table-cell office:value-type="string">'
. '<text:p>' . __('Type') . '</text:p>'
. '</table:table-cell>'
. '<table:table-cell office:value-type="string">'
. '<text:p>' . __('Null') . '</text:p>'
. '</table:table-cell>'
. '<table:table-cell office:value-type="string">'
. '<text:p>' . __('Default') . '</text:p>'
. '</table:table-cell>'
. '</table:table-row>';
$columns = $dbi->getColumns($db, $view);
foreach ($columns as $column) {
$col_as = $column['Field'] ?? null;
if (! empty($aliases[$db]['tables'][$view]['columns'][$col_as])) {
$col_as = $aliases[$db]['tables'][$view]['columns'][$col_as];
}
$GLOBALS['odt_buffer'] .= $this->formatOneColumnDefinition($column, $col_as);
$GLOBALS['odt_buffer'] .= '</table:table-row>';
}
$GLOBALS['odt_buffer'] .= '</table:table>';
return '';
}
/**
* Returns $table's CREATE definition
*
* @param string $db the database name
* @param string $table the table name
* @param string $crlf the end of line sequence
* @param string $error_url the url to go back in case of error
* @param bool $do_relation whether to include relation comments
* @param bool $do_comments whether to include the pmadb-style column
* comments as comments in the structure;
* this is deprecated but the parameter is
* left here because /export calls
* PMA_exportStructure() also for other
* @param bool $do_mime whether to include mime comments
* @param bool $show_dates whether to include creation/update/check dates
* @param bool $add_semicolon whether to add semicolon and end-of-line at
* the end
* @param bool $view whether we're handling a view
* @param array $aliases Aliases of db/table/columns
*/
public function getTableDef(
$db,
$table,
$crlf,
$error_url,
$do_relation,
$do_comments,
$do_mime,
$show_dates = false,
$add_semicolon = true,
$view = false,
array $aliases = []
): bool {
global $dbi;
$db_alias = $db;
$table_alias = $table;
$this->initAlias($aliases, $db_alias, $table_alias);
$relationParameters = $this->relation->getRelationParameters();
/**
* Gets fields properties
*/
$dbi->selectDb($db);
// Check if we can use Relations
[$res_rel, $have_rel] = $this->relation->getRelationsAndStatus(
$do_relation && $relationParameters->relationFeature !== null,
$db,
$table
);
/**
* Displays the table structure
*/
$GLOBALS['odt_buffer'] .= '<table:table table:name="'
. htmlspecialchars($table_alias) . '_structure">';
$columns_cnt = 4;
if ($do_relation && $have_rel) {
$columns_cnt++;
}
if ($do_comments) {
$columns_cnt++;
}
if ($do_mime && $relationParameters->browserTransformationFeature !== null) {
$columns_cnt++;
}
$GLOBALS['odt_buffer'] .= '<table:table-column'
. ' table:number-columns-repeated="' . $columns_cnt . '"/>';
/* Header */
$GLOBALS['odt_buffer'] .= '<table:table-row>'
. '<table:table-cell office:value-type="string">'
. '<text:p>' . __('Column') . '</text:p>'
. '</table:table-cell>'
. '<table:table-cell office:value-type="string">'
. '<text:p>' . __('Type') . '</text:p>'
. '</table:table-cell>'
. '<table:table-cell office:value-type="string">'
. '<text:p>' . __('Null') . '</text:p>'
. '</table:table-cell>'
. '<table:table-cell office:value-type="string">'
. '<text:p>' . __('Default') . '</text:p>'
. '</table:table-cell>';
if ($do_relation && $have_rel) {
$GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">'
. '<text:p>' . __('Links to') . '</text:p>'
. '</table:table-cell>';
}
if ($do_comments) {
$GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">'
. '<text:p>' . __('Comments') . '</text:p>'
. '</table:table-cell>';
$comments = $this->relation->getComments($db, $table);
}
if ($do_mime && $relationParameters->browserTransformationFeature !== null) {
$GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">'
. '<text:p>' . __('Media type') . '</text:p>'
. '</table:table-cell>';
$mime_map = $this->transformations->getMime($db, $table, true);
}
$GLOBALS['odt_buffer'] .= '</table:table-row>';
$columns = $dbi->getColumns($db, $table);
foreach ($columns as $column) {
$col_as = $field_name = $column['Field'];
if (! empty($aliases[$db]['tables'][$table]['columns'][$col_as])) {
$col_as = $aliases[$db]['tables'][$table]['columns'][$col_as];
}
$GLOBALS['odt_buffer'] .= $this->formatOneColumnDefinition($column, $col_as);
if ($do_relation && $have_rel) {
$foreigner = $this->relation->searchColumnInForeigners($res_rel, $field_name);
if ($foreigner) {
$rtable = $foreigner['foreign_table'];
$rfield = $foreigner['foreign_field'];
if (! empty($aliases[$db]['tables'][$rtable]['columns'][$rfield])) {
$rfield = $aliases[$db]['tables'][$rtable]['columns'][$rfield];
}
if (! empty($aliases[$db]['tables'][$rtable]['alias'])) {
$rtable = $aliases[$db]['tables'][$rtable]['alias'];
}
$relation = htmlspecialchars($rtable . ' (' . $rfield . ')');
$GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">'
. '<text:p>'
. htmlspecialchars($relation)
. '</text:p>'
. '</table:table-cell>';
}
}
if ($do_comments) {
if (isset($comments[$field_name])) {
$GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">'
. '<text:p>'
. htmlspecialchars($comments[$field_name])
. '</text:p>'
. '</table:table-cell>';
} else {
$GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">'
. '<text:p></text:p>'
. '</table:table-cell>';
}
}
if ($do_mime && $relationParameters->browserTransformationFeature !== null) {
if (isset($mime_map[$field_name])) {
$GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">'
. '<text:p>'
. htmlspecialchars(
str_replace('_', '/', $mime_map[$field_name]['mimetype'])
)
. '</text:p>'
. '</table:table-cell>';
} else {
$GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">'
. '<text:p></text:p>'
. '</table:table-cell>';
}
}
$GLOBALS['odt_buffer'] .= '</table:table-row>';
}
$GLOBALS['odt_buffer'] .= '</table:table>';
return true;
}
/**
* Outputs triggers
*
* @param string $db database name
* @param string $table table name
* @param array $aliases Aliases of db/table/columns
*
* @return string
*/
protected function getTriggers($db, $table, array $aliases = [])
{
global $dbi;
$db_alias = $db;
$table_alias = $table;
$this->initAlias($aliases, $db_alias, $table_alias);
$GLOBALS['odt_buffer'] .= '<table:table'
. ' table:name="' . htmlspecialchars($table_alias) . '_triggers">'
. '<table:table-column'
. ' table:number-columns-repeated="4"/>'
. '<table:table-row>'
. '<table:table-cell office:value-type="string">'
. '<text:p>' . __('Name') . '</text:p>'
. '</table:table-cell>'
. '<table:table-cell office:value-type="string">'
. '<text:p>' . __('Time') . '</text:p>'
. '</table:table-cell>'
. '<table:table-cell office:value-type="string">'
. '<text:p>' . __('Event') . '</text:p>'
. '</table:table-cell>'
. '<table:table-cell office:value-type="string">'
. '<text:p>' . __('Definition') . '</text:p>'
. '</table:table-cell>'
. '</table:table-row>';
$triggers = $dbi->getTriggers($db, $table);
foreach ($triggers as $trigger) {
$GLOBALS['odt_buffer'] .= '<table:table-row>';
$GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">'
. '<text:p>'
. htmlspecialchars($trigger['name'])
. '</text:p>'
. '</table:table-cell>';
$GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">'
. '<text:p>'
. htmlspecialchars($trigger['action_timing'])
. '</text:p>'
. '</table:table-cell>';
$GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">'
. '<text:p>'
. htmlspecialchars($trigger['event_manipulation'])
. '</text:p>'
. '</table:table-cell>';
$GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">'
. '<text:p>'
. htmlspecialchars($trigger['definition'])
. '</text:p>'
. '</table:table-cell>';
$GLOBALS['odt_buffer'] .= '</table:table-row>';
}
$GLOBALS['odt_buffer'] .= '</table:table>';
return $GLOBALS['odt_buffer'];
}
/**
* Outputs table's structure
*
* @param string $db database name
* @param string $table table name
* @param string $crlf the end of line sequence
* @param string $errorUrl the url to go back in case of error
* @param string $exportMode 'create_table', 'triggers', 'create_view',
* 'stand_in'
* @param string $exportType 'server', 'database', 'table'
* @param bool $do_relation whether to include relation comments
* @param bool $do_comments whether to include the pmadb-style column
* comments as comments in the structure;
* this is deprecated but the parameter is
* left here because /export calls
* PMA_exportStructure() also for other
* @param bool $do_mime whether to include mime comments
* @param bool $dates whether to include creation/update/check dates
* @param array $aliases Aliases of db/table/columns
*/
public function exportStructure(
$db,
$table,
$crlf,
$errorUrl,
$exportMode,
$exportType,
$do_relation = false,
$do_comments = false,
$do_mime = false,
$dates = false,
array $aliases = []
): bool {
global $dbi;
$db_alias = $db;
$table_alias = $table;
$this->initAlias($aliases, $db_alias, $table_alias);
switch ($exportMode) {
case 'create_table':
$GLOBALS['odt_buffer'] .= '<text:h text:outline-level="2" text:style-name="Heading_2"'
. ' text:is-list-header="true">'
. __('Table structure for table') . ' ' .
htmlspecialchars($table_alias)
. '</text:h>';
$this->getTableDef(
$db,
$table,
$crlf,
$errorUrl,
$do_relation,
$do_comments,
$do_mime,
$dates,
true,
false,
$aliases
);
break;
case 'triggers':
$triggers = $dbi->getTriggers($db, $table);
if ($triggers) {
$GLOBALS['odt_buffer'] .= '<text:h text:outline-level="2" text:style-name="Heading_2"'
. ' text:is-list-header="true">'
. __('Triggers') . ' '
. htmlspecialchars($table_alias)
. '</text:h>';
$this->getTriggers($db, $table);
}
break;
case 'create_view':
$GLOBALS['odt_buffer'] .= '<text:h text:outline-level="2" text:style-name="Heading_2"'
. ' text:is-list-header="true">'
. __('Structure for view') . ' '
. htmlspecialchars($table_alias)
. '</text:h>';
$this->getTableDef(
$db,
$table,
$crlf,
$errorUrl,
$do_relation,
$do_comments,
$do_mime,
$dates,
true,
true,
$aliases
);
break;
case 'stand_in':
$GLOBALS['odt_buffer'] .= '<text:h text:outline-level="2" text:style-name="Heading_2"'
. ' text:is-list-header="true">'
. __('Stand-in structure for view') . ' '
. htmlspecialchars($table_alias)
. '</text:h>';
// export a stand-in definition to resolve view dependencies
$this->getTableDefStandIn($db, $table, $crlf, $aliases);
}
return true;
}
/**
* Formats the definition for one column
*
* @param array $column info about this column
* @param string $col_as column alias
*
* @return string Formatted column definition
*/
protected function formatOneColumnDefinition($column, $col_as = '')
{
if (empty($col_as)) {
$col_as = $column['Field'];
}
$definition = '<table:table-row>';
$definition .= '<table:table-cell office:value-type="string">'
. '<text:p>' . htmlspecialchars($col_as) . '</text:p>'
. '</table:table-cell>';
$extracted_columnspec = Util::extractColumnSpec($column['Type']);
$type = htmlspecialchars($extracted_columnspec['print_type']);
if (empty($type)) {
$type = '&nbsp;';
}
$definition .= '<table:table-cell office:value-type="string">'
. '<text:p>' . htmlspecialchars($type) . '</text:p>'
. '</table:table-cell>';
if (! isset($column['Default'])) {
if ($column['Null'] !== 'NO') {
$column['Default'] = 'NULL';
} else {
$column['Default'] = '';
}
}
$definition .= '<table:table-cell office:value-type="string">'
. '<text:p>'
. ($column['Null'] == '' || $column['Null'] === 'NO'
? __('No')
: __('Yes'))
. '</text:p>'
. '</table:table-cell>';
$definition .= '<table:table-cell office:value-type="string">'
. '<text:p>' . htmlspecialchars($column['Default']) . '</text:p>'
. '</table:table-cell>';
return $definition;
}
}

View file

@ -1,337 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Export;
use PhpMyAdmin\Plugins\Export\Helpers\Pdf;
use PhpMyAdmin\Plugins\ExportPlugin;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyMainGroup;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyRootGroup;
use PhpMyAdmin\Properties\Options\Items\RadioPropertyItem;
use PhpMyAdmin\Properties\Options\Items\TextPropertyItem;
use PhpMyAdmin\Properties\Plugins\ExportPluginProperties;
use TCPDF;
use function __;
use function class_exists;
/**
* Produce a PDF report (export) from a query
*/
class ExportPdf extends ExportPlugin
{
/**
* PhpMyAdmin\Plugins\Export\Helpers\Pdf instance
*
* @var Pdf
*/
private $pdf;
/**
* PDF Report Title
*
* @var string
*/
private $pdfReportTitle = '';
/**
* @psalm-return non-empty-lowercase-string
*/
public function getName(): string
{
return 'pdf';
}
/**
* Initialize the local variables that are used for export PDF.
*/
protected function init(): void
{
if (! empty($_POST['pdf_report_title'])) {
$this->pdfReportTitle = $_POST['pdf_report_title'];
}
$this->setPdf(new Pdf('L', 'pt', 'A3'));
}
protected function setProperties(): ExportPluginProperties
{
$exportPluginProperties = new ExportPluginProperties();
$exportPluginProperties->setText('PDF');
$exportPluginProperties->setExtension('pdf');
$exportPluginProperties->setMimeType('application/pdf');
$exportPluginProperties->setForceFile(true);
$exportPluginProperties->setOptionsText(__('Options'));
// create the root group that will be the options field for
// $exportPluginProperties
// this will be shown as "Format specific options"
$exportSpecificOptions = new OptionsPropertyRootGroup('Format Specific Options');
// general options main group
$generalOptions = new OptionsPropertyMainGroup('general_opts');
// create primary items and add them to the group
$leaf = new TextPropertyItem(
'report_title',
__('Report title:')
);
$generalOptions->addProperty($leaf);
// add the group to the root group
$exportSpecificOptions->addProperty($generalOptions);
// what to dump (structure/data/both) main group
$dumpWhat = new OptionsPropertyMainGroup(
'dump_what',
__('Dump table')
);
$leaf = new RadioPropertyItem('structure_or_data');
$leaf->setValues(
[
'structure' => __('structure'),
'data' => __('data'),
'structure_and_data' => __('structure and data'),
]
);
$dumpWhat->addProperty($leaf);
// add the group to the root group
$exportSpecificOptions->addProperty($dumpWhat);
// set the options for the export plugin property item
$exportPluginProperties->setOptions($exportSpecificOptions);
return $exportPluginProperties;
}
/**
* Outputs export header
*/
public function exportHeader(): bool
{
$pdf = $this->getPdf();
$pdf->Open();
$pdf->setTitleFontSize(18);
$pdf->setTitleText($this->pdfReportTitle);
$pdf->setTopMargin(30);
return true;
}
/**
* Outputs export footer
*/
public function exportFooter(): bool
{
$pdf = $this->getPdf();
// instead of $pdf->Output():
return $this->export->outputHandler($pdf->getPDFData());
}
/**
* Outputs database header
*
* @param string $db Database name
* @param string $dbAlias Aliases of db
*/
public function exportDBHeader($db, $dbAlias = ''): bool
{
return true;
}
/**
* Outputs database footer
*
* @param string $db Database name
*/
public function exportDBFooter($db): bool
{
return true;
}
/**
* Outputs CREATE DATABASE statement
*
* @param string $db Database name
* @param string $exportType 'server', 'database', 'table'
* @param string $dbAlias Aliases of db
*/
public function exportDBCreate($db, $exportType, $dbAlias = ''): bool
{
return true;
}
/**
* Outputs the content of a table in NHibernate format
*
* @param string $db database name
* @param string $table table name
* @param string $crlf the end of line sequence
* @param string $errorUrl the url to go back in case of error
* @param string $sqlQuery SQL query for obtaining data
* @param array $aliases Aliases of db/table/columns
*/
public function exportData(
$db,
$table,
$crlf,
$errorUrl,
$sqlQuery,
array $aliases = []
): bool {
$db_alias = $db;
$table_alias = $table;
$this->initAlias($aliases, $db_alias, $table_alias);
$pdf = $this->getPdf();
$pdf->setCurrentDb($db);
$pdf->setCurrentTable($table);
$pdf->setDbAlias($db_alias);
$pdf->setTableAlias($table_alias);
$pdf->setAliases($aliases);
$pdf->setPurpose(__('Dumping data'));
$pdf->mysqlReport($sqlQuery);
return true;
}
/**
* Outputs result of raw query in PDF format
*
* @param string $errorUrl the url to go back in case of error
* @param string|null $db the database where the query is executed
* @param string $sqlQuery the rawquery to output
* @param string $crlf the end of line sequence
*/
public function exportRawQuery(string $errorUrl, ?string $db, string $sqlQuery, string $crlf): bool
{
global $dbi;
$pdf = $this->getPdf();
$pdf->setDbAlias('----');
$pdf->setTableAlias('----');
$pdf->setPurpose(__('Query result data'));
if ($db !== null) {
$pdf->setCurrentDb($db);
$dbi->selectDb($db);
}
$pdf->mysqlReport($sqlQuery);
return true;
}
/**
* Outputs table structure
*
* @param string $db database name
* @param string $table table name
* @param string $crlf the end of line sequence
* @param string $errorUrl the url to go back in case of error
* @param string $exportMode 'create_table', 'triggers', 'create_view',
* 'stand_in'
* @param string $exportType 'server', 'database', 'table'
* @param bool $do_relation whether to include relation comments
* @param bool $do_comments whether to include the pmadb-style column
* comments as comments in the structure;
* this is deprecated but the parameter is
* left here because /export calls
* PMA_exportStructure() also for other
* export types which use this parameter
* @param bool $do_mime whether to include mime comments
* @param bool $dates whether to include creation/update/check dates
* @param array $aliases aliases for db/table/columns
*/
public function exportStructure(
$db,
$table,
$crlf,
$errorUrl,
$exportMode,
$exportType,
$do_relation = false,
$do_comments = false,
$do_mime = false,
$dates = false,
array $aliases = []
): bool {
$db_alias = $db;
$table_alias = $table;
$purpose = '';
$this->initAlias($aliases, $db_alias, $table_alias);
$pdf = $this->getPdf();
// getting purpose to show at top
switch ($exportMode) {
case 'create_table':
$purpose = __('Table structure');
break;
case 'triggers':
$purpose = __('Triggers');
break;
case 'create_view':
$purpose = __('View structure');
break;
case 'stand_in':
$purpose = __('Stand in');
}
$pdf->setCurrentDb($db);
$pdf->setCurrentTable($table);
$pdf->setDbAlias($db_alias);
$pdf->setTableAlias($table_alias);
$pdf->setAliases($aliases);
$pdf->setPurpose($purpose);
/**
* comment display set true as presently in pdf
* format, no option is present to take user input.
*/
$do_comments = true;
switch ($exportMode) {
case 'create_table':
$pdf->getTableDef($db, $table, $do_relation, $do_comments, $do_mime, false, $aliases);
break;
case 'triggers':
$pdf->getTriggers($db, $table);
break;
case 'create_view':
$pdf->getTableDef($db, $table, $do_relation, $do_comments, $do_mime, false, $aliases);
break;
case 'stand_in':
/* export a stand-in definition to resolve view dependencies
* Yet to develop this function
* $pdf->getTableDefStandIn($db, $table, $crlf);
*/
}
return true;
}
/* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */
/**
* Gets the PhpMyAdmin\Plugins\Export\Helpers\Pdf instance
*
* @return Pdf
*/
private function getPdf()
{
return $this->pdf;
}
/**
* Instantiates the PhpMyAdmin\Plugins\Export\Helpers\Pdf class
*
* @param Pdf $pdf The instance
*/
private function setPdf($pdf): void
{
$this->pdf = $pdf;
}
public static function isAvailable(): bool
{
return class_exists(TCPDF::class);
}
}

View file

@ -1,256 +0,0 @@
<?php
/**
* Set of functions used to build dumps of tables as PHP Arrays
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Export;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\Plugins\ExportPlugin;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyMainGroup;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyRootGroup;
use PhpMyAdmin\Properties\Options\Items\HiddenPropertyItem;
use PhpMyAdmin\Properties\Plugins\ExportPluginProperties;
use PhpMyAdmin\Util;
use PhpMyAdmin\Version;
use function __;
use function preg_match;
use function preg_replace;
use function stripslashes;
use function strtr;
use function var_export;
/**
* Handles the export for the PHP Array class
*/
class ExportPhparray extends ExportPlugin
{
/**
* @psalm-return non-empty-lowercase-string
*/
public function getName(): string
{
return 'phparray';
}
protected function setProperties(): ExportPluginProperties
{
$exportPluginProperties = new ExportPluginProperties();
$exportPluginProperties->setText('PHP array');
$exportPluginProperties->setExtension('php');
$exportPluginProperties->setMimeType('text/plain');
$exportPluginProperties->setOptionsText(__('Options'));
// create the root group that will be the options field for
// $exportPluginProperties
// this will be shown as "Format specific options"
$exportSpecificOptions = new OptionsPropertyRootGroup('Format Specific Options');
// general options main group
$generalOptions = new OptionsPropertyMainGroup('general_opts');
// create primary items and add them to the group
$leaf = new HiddenPropertyItem('structure_or_data');
$generalOptions->addProperty($leaf);
// add the main group to the root group
$exportSpecificOptions->addProperty($generalOptions);
// set the options for the export plugin property item
$exportPluginProperties->setOptions($exportSpecificOptions);
return $exportPluginProperties;
}
/**
* Removes end of comment from a string
*
* @param string $string String to replace
*
* @return string
*/
public function commentString($string)
{
return strtr($string, '*/', '-');
}
/**
* Outputs export header
*/
public function exportHeader(): bool
{
$this->export->outputHandler(
'<?php' . $GLOBALS['crlf']
. '/**' . $GLOBALS['crlf']
. ' * Export to PHP Array plugin for PHPMyAdmin' . $GLOBALS['crlf']
. ' * @version ' . Version::VERSION . $GLOBALS['crlf']
. ' */' . $GLOBALS['crlf'] . $GLOBALS['crlf']
);
return true;
}
/**
* Outputs export footer
*/
public function exportFooter(): bool
{
return true;
}
/**
* Outputs database header
*
* @param string $db Database name
* @param string $dbAlias Aliases of db
*/
public function exportDBHeader($db, $dbAlias = ''): bool
{
if (empty($dbAlias)) {
$dbAlias = $db;
}
$this->export->outputHandler(
'/**' . $GLOBALS['crlf']
. ' * Database ' . $this->commentString(Util::backquote($dbAlias))
. $GLOBALS['crlf'] . ' */' . $GLOBALS['crlf']
);
return true;
}
/**
* Outputs database footer
*
* @param string $db Database name
*/
public function exportDBFooter($db): bool
{
return true;
}
/**
* Outputs CREATE DATABASE statement
*
* @param string $db Database name
* @param string $exportType 'server', 'database', 'table'
* @param string $dbAlias Aliases of db
*/
public function exportDBCreate($db, $exportType, $dbAlias = ''): bool
{
return true;
}
/**
* Outputs the content of a table in PHP array format
*
* @param string $db database name
* @param string $table table name
* @param string $crlf the end of line sequence
* @param string $errorUrl the url to go back in case of error
* @param string $sqlQuery SQL query for obtaining data
* @param array $aliases Aliases of db/table/columns
*/
public function exportData(
$db,
$table,
$crlf,
$errorUrl,
$sqlQuery,
array $aliases = []
): bool {
global $dbi;
$db_alias = $db;
$table_alias = $table;
$this->initAlias($aliases, $db_alias, $table_alias);
$result = $dbi->query($sqlQuery, DatabaseInterface::CONNECT_USER, DatabaseInterface::QUERY_UNBUFFERED);
$columns_cnt = $result->numFields();
$columns = [];
foreach ($result->getFieldNames() as $i => $col_as) {
if (! empty($aliases[$db]['tables'][$table]['columns'][$col_as])) {
$col_as = $aliases[$db]['tables'][$table]['columns'][$col_as];
}
$columns[$i] = stripslashes($col_as);
}
$tablefixed = $table;
// fix variable names (based on
// https://www.php.net/manual/en/language.variables.basics.php)
if (! preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $table_alias)) {
// fix invalid characters in variable names by replacing them with
// underscores
$tablefixed = preg_replace('/[^a-zA-Z0-9_\x7f-\xff]/', '_', $table_alias);
// variable name must not start with a number or dash...
if (preg_match('/^[a-zA-Z_\x7f-\xff]/', $tablefixed) === 0) {
$tablefixed = '_' . $tablefixed;
}
}
$buffer = '';
$record_cnt = 0;
// Output table name as comment
$buffer .= $crlf . '/* '
. $this->commentString(Util::backquote($db_alias)) . '.'
. $this->commentString(Util::backquote($table_alias)) . ' */' . $crlf;
$buffer .= '$' . $tablefixed . ' = array(';
if (! $this->export->outputHandler($buffer)) {
return false;
}
// Reset the buffer
$buffer = '';
while ($record = $result->fetchRow()) {
$record_cnt++;
if ($record_cnt == 1) {
$buffer .= $crlf . ' array(';
} else {
$buffer .= ',' . $crlf . ' array(';
}
for ($i = 0; $i < $columns_cnt; $i++) {
$buffer .= var_export($columns[$i], true)
. ' => ' . var_export($record[$i], true)
. ($i + 1 >= $columns_cnt ? '' : ',');
}
$buffer .= ')';
if (! $this->export->outputHandler($buffer)) {
return false;
}
// Reset the buffer
$buffer = '';
}
$buffer .= $crlf . ');' . $crlf;
return $this->export->outputHandler($buffer);
}
/**
* Outputs result of raw query as PHP array
*
* @param string $errorUrl the url to go back in case of error
* @param string|null $db the database where the query is executed
* @param string $sqlQuery the rawquery to output
* @param string $crlf the end of line sequence
*/
public function exportRawQuery(string $errorUrl, ?string $db, string $sqlQuery, string $crlf): bool
{
global $dbi;
if ($db !== null) {
$dbi->selectDb($db);
}
return $this->exportData($db ?? '', '', $crlf, $errorUrl, $sqlQuery);
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,632 +0,0 @@
<?php
/**
* Export to Texy! text.
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Export;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\Plugins\ExportPlugin;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyMainGroup;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyRootGroup;
use PhpMyAdmin\Properties\Options\Items\BoolPropertyItem;
use PhpMyAdmin\Properties\Options\Items\RadioPropertyItem;
use PhpMyAdmin\Properties\Options\Items\TextPropertyItem;
use PhpMyAdmin\Properties\Plugins\ExportPluginProperties;
use PhpMyAdmin\Util;
use function __;
use function htmlspecialchars;
use function in_array;
use function str_replace;
use function stripslashes;
/**
* Handles the export for the Texy! text class
*/
class ExportTexytext extends ExportPlugin
{
/**
* @psalm-return non-empty-lowercase-string
*/
public function getName(): string
{
return 'texytext';
}
protected function setProperties(): ExportPluginProperties
{
$exportPluginProperties = new ExportPluginProperties();
$exportPluginProperties->setText('Texy! text');
$exportPluginProperties->setExtension('txt');
$exportPluginProperties->setMimeType('text/plain');
$exportPluginProperties->setOptionsText(__('Options'));
// create the root group that will be the options field for
// $exportPluginProperties
// this will be shown as "Format specific options"
$exportSpecificOptions = new OptionsPropertyRootGroup('Format Specific Options');
// what to dump (structure/data/both) main group
$dumpWhat = new OptionsPropertyMainGroup(
'general_opts',
__('Dump table')
);
// create primary items and add them to the group
$leaf = new RadioPropertyItem('structure_or_data');
$leaf->setValues(
[
'structure' => __('structure'),
'data' => __('data'),
'structure_and_data' => __('structure and data'),
]
);
$dumpWhat->addProperty($leaf);
// add the main group to the root group
$exportSpecificOptions->addProperty($dumpWhat);
// data options main group
$dataOptions = new OptionsPropertyMainGroup(
'data',
__('Data dump options')
);
$dataOptions->setForce('structure');
// create primary items and add them to the group
$leaf = new BoolPropertyItem(
'columns',
__('Put columns names in the first row')
);
$dataOptions->addProperty($leaf);
$leaf = new TextPropertyItem(
'null',
__('Replace NULL with:')
);
$dataOptions->addProperty($leaf);
// add the main group to the root group
$exportSpecificOptions->addProperty($dataOptions);
// set the options for the export plugin property item
$exportPluginProperties->setOptions($exportSpecificOptions);
return $exportPluginProperties;
}
/**
* Outputs export header
*/
public function exportHeader(): bool
{
return true;
}
/**
* Outputs export footer
*/
public function exportFooter(): bool
{
return true;
}
/**
* Outputs database header
*
* @param string $db Database name
* @param string $dbAlias Alias of db
*/
public function exportDBHeader($db, $dbAlias = ''): bool
{
if (empty($dbAlias)) {
$dbAlias = $db;
}
return $this->export->outputHandler(
'===' . __('Database') . ' ' . $dbAlias . "\n\n"
);
}
/**
* Outputs database footer
*
* @param string $db Database name
*/
public function exportDBFooter($db): bool
{
return true;
}
/**
* Outputs CREATE DATABASE statement
*
* @param string $db Database name
* @param string $exportType 'server', 'database', 'table'
* @param string $dbAlias Aliases of db
*/
public function exportDBCreate($db, $exportType, $dbAlias = ''): bool
{
return true;
}
/**
* Outputs the content of a table in NHibernate format
*
* @param string $db database name
* @param string $table table name
* @param string $crlf the end of line sequence
* @param string $errorUrl the url to go back in case of error
* @param string $sqlQuery SQL query for obtaining data
* @param array $aliases Aliases of db/table/columns
*/
public function exportData(
$db,
$table,
$crlf,
$errorUrl,
$sqlQuery,
array $aliases = []
): bool {
global $what, $dbi;
$db_alias = $db;
$table_alias = $table;
$this->initAlias($aliases, $db_alias, $table_alias);
if (
! $this->export->outputHandler(
$table_alias != ''
? '== ' . __('Dumping data for table') . ' ' . $table_alias . "\n\n"
: '==' . __('Dumping data for query result') . "\n\n"
)
) {
return false;
}
// Gets the data from the database
$result = $dbi->query($sqlQuery, DatabaseInterface::CONNECT_USER, DatabaseInterface::QUERY_UNBUFFERED);
$fields_cnt = $result->numFields();
// If required, get fields name at the first line
if (isset($GLOBALS[$what . '_columns'])) {
$text_output = "|------\n";
foreach ($result->getFieldNames() as $col_as) {
if (! empty($aliases[$db]['tables'][$table]['columns'][$col_as])) {
$col_as = $aliases[$db]['tables'][$table]['columns'][$col_as];
}
$text_output .= '|'
. htmlspecialchars(stripslashes($col_as));
}
$text_output .= "\n|------\n";
if (! $this->export->outputHandler($text_output)) {
return false;
}
}
// Format the data
while ($row = $result->fetchRow()) {
$text_output = '';
for ($j = 0; $j < $fields_cnt; $j++) {
if (! isset($row[$j])) {
$value = $GLOBALS[$what . '_null'];
} elseif ($row[$j] == '0' || $row[$j] != '') {
$value = $row[$j];
} else {
$value = ' ';
}
$text_output .= '|'
. str_replace(
'|',
'&#124;',
htmlspecialchars($value)
);
}
$text_output .= "\n";
if (! $this->export->outputHandler($text_output)) {
return false;
}
}
return true;
}
/**
* Outputs result raw query in TexyText format
*
* @param string $errorUrl the url to go back in case of error
* @param string|null $db the database where the query is executed
* @param string $sqlQuery the rawquery to output
* @param string $crlf the end of line sequence
*/
public function exportRawQuery(string $errorUrl, ?string $db, string $sqlQuery, string $crlf): bool
{
global $dbi;
if ($db !== null) {
$dbi->selectDb($db);
}
return $this->exportData($db ?? '', '', $crlf, $errorUrl, $sqlQuery);
}
/**
* Returns a stand-in CREATE definition to resolve view dependencies
*
* @param string $db the database name
* @param string $view the view name
* @param string $crlf the end of line sequence
* @param array $aliases Aliases of db/table/columns
*
* @return string resulting definition
*/
public function getTableDefStandIn($db, $view, $crlf, $aliases = [])
{
global $dbi;
$text_output = '';
/**
* Get the unique keys in the table
*/
$unique_keys = [];
$keys = $dbi->getTableIndexes($db, $view);
foreach ($keys as $key) {
if ($key['Non_unique'] != 0) {
continue;
}
$unique_keys[] = $key['Column_name'];
}
/**
* Gets fields properties
*/
$dbi->selectDb($db);
/**
* Displays the table structure
*/
$text_output .= "|------\n"
. '|' . __('Column')
. '|' . __('Type')
. '|' . __('Null')
. '|' . __('Default')
. "\n|------\n";
$columns = $dbi->getColumns($db, $view);
foreach ($columns as $column) {
$col_as = $column['Field'] ?? null;
if (! empty($aliases[$db]['tables'][$view]['columns'][$col_as])) {
$col_as = $aliases[$db]['tables'][$view]['columns'][$col_as];
}
$text_output .= $this->formatOneColumnDefinition($column, $unique_keys, $col_as);
$text_output .= "\n";
}
return $text_output;
}
/**
* Returns $table's CREATE definition
*
* @param string $db the database name
* @param string $table the table name
* @param string $crlf the end of line sequence
* @param string $error_url the url to go back in case of error
* @param bool $do_relation whether to include relation comments
* @param bool $do_comments whether to include the pmadb-style column
* comments as comments in the structure;
* this is deprecated but the parameter is
* left here because /export calls
* $this->exportStructure() also for other
* export types which use this parameter
* @param bool $do_mime whether to include mime comments
* @param bool $show_dates whether to include creation/update/check dates
* @param bool $add_semicolon whether to add semicolon and end-of-line
* at the end
* @param bool $view whether we're handling a view
* @param array $aliases Aliases of db/table/columns
*
* @return string resulting schema
*/
public function getTableDef(
$db,
$table,
$crlf,
$error_url,
$do_relation,
$do_comments,
$do_mime,
$show_dates = false,
$add_semicolon = true,
$view = false,
array $aliases = []
) {
global $dbi;
$relationParameters = $this->relation->getRelationParameters();
$text_output = '';
/**
* Get the unique keys in the table
*/
$unique_keys = [];
$keys = $dbi->getTableIndexes($db, $table);
foreach ($keys as $key) {
if ($key['Non_unique'] != 0) {
continue;
}
$unique_keys[] = $key['Column_name'];
}
/**
* Gets fields properties
*/
$dbi->selectDb($db);
// Check if we can use Relations
[$res_rel, $have_rel] = $this->relation->getRelationsAndStatus(
$do_relation && $relationParameters->relationFeature !== null,
$db,
$table
);
/**
* Displays the table structure
*/
$text_output .= "|------\n";
$text_output .= '|' . __('Column');
$text_output .= '|' . __('Type');
$text_output .= '|' . __('Null');
$text_output .= '|' . __('Default');
if ($do_relation && $have_rel) {
$text_output .= '|' . __('Links to');
}
if ($do_comments) {
$text_output .= '|' . __('Comments');
$comments = $this->relation->getComments($db, $table);
}
if ($do_mime && $relationParameters->browserTransformationFeature !== null) {
$text_output .= '|' . __('Media type');
$mime_map = $this->transformations->getMime($db, $table, true);
}
$text_output .= "\n|------\n";
$columns = $dbi->getColumns($db, $table);
foreach ($columns as $column) {
$col_as = $column['Field'];
if (! empty($aliases[$db]['tables'][$table]['columns'][$col_as])) {
$col_as = $aliases[$db]['tables'][$table]['columns'][$col_as];
}
$text_output .= $this->formatOneColumnDefinition($column, $unique_keys, $col_as);
$field_name = $column['Field'];
if ($do_relation && $have_rel) {
$text_output .= '|' . htmlspecialchars(
$this->getRelationString(
$res_rel,
$field_name,
$db,
$aliases
)
);
}
if ($do_comments && $relationParameters->columnCommentsFeature !== null) {
$text_output .= '|'
. (isset($comments[$field_name])
? htmlspecialchars($comments[$field_name])
: '');
}
if ($do_mime && $relationParameters->browserTransformationFeature !== null) {
$text_output .= '|'
. (isset($mime_map[$field_name])
? htmlspecialchars(
str_replace('_', '/', $mime_map[$field_name]['mimetype'])
)
: '');
}
$text_output .= "\n";
}
return $text_output;
}
/**
* Outputs triggers
*
* @param string $db database name
* @param string $table table name
*
* @return string Formatted triggers list
*/
public function getTriggers($db, $table)
{
global $dbi;
$dump = "|------\n";
$dump .= '|' . __('Name');
$dump .= '|' . __('Time');
$dump .= '|' . __('Event');
$dump .= '|' . __('Definition');
$dump .= "\n|------\n";
$triggers = $dbi->getTriggers($db, $table);
foreach ($triggers as $trigger) {
$dump .= '|' . $trigger['name'];
$dump .= '|' . $trigger['action_timing'];
$dump .= '|' . $trigger['event_manipulation'];
$dump .= '|' .
str_replace(
'|',
'&#124;',
htmlspecialchars($trigger['definition'])
);
$dump .= "\n";
}
return $dump;
}
/**
* Outputs table's structure
*
* @param string $db database name
* @param string $table table name
* @param string $crlf the end of line sequence
* @param string $errorUrl the url to go back in case of error
* @param string $exportMode 'create_table', 'triggers', 'create_view',
* 'stand_in'
* @param string $exportType 'server', 'database', 'table'
* @param bool $do_relation whether to include relation comments
* @param bool $do_comments whether to include the pmadb-style column
* comments as comments in the structure;
* this is deprecated but the parameter is
* left here because /export calls
* $this->exportStructure() also for other
* export types which use this parameter
* @param bool $do_mime whether to include mime comments
* @param bool $dates whether to include creation/update/check dates
* @param array $aliases Aliases of db/table/columns
*/
public function exportStructure(
$db,
$table,
$crlf,
$errorUrl,
$exportMode,
$exportType,
$do_relation = false,
$do_comments = false,
$do_mime = false,
$dates = false,
array $aliases = []
): bool {
global $dbi;
$db_alias = $db;
$table_alias = $table;
$this->initAlias($aliases, $db_alias, $table_alias);
$dump = '';
switch ($exportMode) {
case 'create_table':
$dump .= '== ' . __('Table structure for table') . ' '
. $table_alias . "\n\n";
$dump .= $this->getTableDef(
$db,
$table,
$crlf,
$errorUrl,
$do_relation,
$do_comments,
$do_mime,
$dates,
true,
false,
$aliases
);
break;
case 'triggers':
$dump = '';
$triggers = $dbi->getTriggers($db, $table);
if ($triggers) {
$dump .= '== ' . __('Triggers') . ' ' . $table_alias . "\n\n";
$dump .= $this->getTriggers($db, $table);
}
break;
case 'create_view':
$dump .= '== ' . __('Structure for view') . ' ' . $table_alias . "\n\n";
$dump .= $this->getTableDef(
$db,
$table,
$crlf,
$errorUrl,
$do_relation,
$do_comments,
$do_mime,
$dates,
true,
true,
$aliases
);
break;
case 'stand_in':
$dump .= '== ' . __('Stand-in structure for view')
. ' ' . $table . "\n\n";
// export a stand-in definition to resolve view dependencies
$dump .= $this->getTableDefStandIn($db, $table, $crlf, $aliases);
}
return $this->export->outputHandler($dump);
}
/**
* Formats the definition for one column
*
* @param array $column info about this column
* @param array $unique_keys unique keys for this table
* @param string $col_alias Column Alias
*
* @return string Formatted column definition
*/
public function formatOneColumnDefinition(
$column,
$unique_keys,
$col_alias = ''
) {
if (empty($col_alias)) {
$col_alias = $column['Field'];
}
$extracted_columnspec = Util::extractColumnSpec($column['Type']);
$type = $extracted_columnspec['print_type'];
if (empty($type)) {
$type = '&nbsp;';
}
if (! isset($column['Default'])) {
if ($column['Null'] !== 'NO') {
$column['Default'] = 'NULL';
}
}
$fmt_pre = '';
$fmt_post = '';
if (in_array($column['Field'], $unique_keys)) {
$fmt_pre = '**' . $fmt_pre;
$fmt_post .= '**';
}
if ($column['Key'] === 'PRI') {
$fmt_pre = '//' . $fmt_pre;
$fmt_post .= '//';
}
$definition = '|'
. $fmt_pre . htmlspecialchars($col_alias) . $fmt_post;
$definition .= '|' . htmlspecialchars($type);
$definition .= '|'
. ($column['Null'] == '' || $column['Null'] === 'NO'
? __('No') : __('Yes'));
$definition .= '|'
. htmlspecialchars($column['Default'] ?? '');
return $definition;
}
}

View file

@ -1,553 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Export;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\Plugins\ExportPlugin;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyMainGroup;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyRootGroup;
use PhpMyAdmin\Properties\Options\Items\BoolPropertyItem;
use PhpMyAdmin\Properties\Options\Items\HiddenPropertyItem;
use PhpMyAdmin\Properties\Plugins\ExportPluginProperties;
use PhpMyAdmin\Util;
use PhpMyAdmin\Version;
use function __;
use function count;
use function htmlspecialchars;
use function is_array;
use function mb_substr;
use function rtrim;
use function str_replace;
use function stripslashes;
use function strlen;
use const PHP_VERSION;
/**
* Used to build XML dumps of tables
*/
class ExportXml extends ExportPlugin
{
/**
* Table name
*
* @var string
*/
private $table;
/**
* Table names
*
* @var array
*/
private $tables = [];
/**
* @psalm-return non-empty-lowercase-string
*/
public function getName(): string
{
return 'xml';
}
/**
* Initialize the local variables that are used for export XML
*/
private function initSpecificVariables(): void
{
global $table, $tables;
$this->setTable($table);
if (! is_array($tables)) {
return;
}
$this->setTables($tables);
}
protected function setProperties(): ExportPluginProperties
{
// create the export plugin property item
$exportPluginProperties = new ExportPluginProperties();
$exportPluginProperties->setText('XML');
$exportPluginProperties->setExtension('xml');
$exportPluginProperties->setMimeType('text/xml');
$exportPluginProperties->setOptionsText(__('Options'));
// create the root group that will be the options field for
// $exportPluginProperties
// this will be shown as "Format specific options"
$exportSpecificOptions = new OptionsPropertyRootGroup('Format Specific Options');
// general options main group
$generalOptions = new OptionsPropertyMainGroup('general_opts');
// create primary items and add them to the group
$leaf = new HiddenPropertyItem('structure_or_data');
$generalOptions->addProperty($leaf);
// add the main group to the root group
$exportSpecificOptions->addProperty($generalOptions);
// export structure main group
$structure = new OptionsPropertyMainGroup(
'structure',
__('Object creation options (all are recommended)')
);
// create primary items and add them to the group
$leaf = new BoolPropertyItem(
'export_events',
__('Events')
);
$structure->addProperty($leaf);
$leaf = new BoolPropertyItem(
'export_functions',
__('Functions')
);
$structure->addProperty($leaf);
$leaf = new BoolPropertyItem(
'export_procedures',
__('Procedures')
);
$structure->addProperty($leaf);
$leaf = new BoolPropertyItem(
'export_tables',
__('Tables')
);
$structure->addProperty($leaf);
$leaf = new BoolPropertyItem(
'export_triggers',
__('Triggers')
);
$structure->addProperty($leaf);
$leaf = new BoolPropertyItem(
'export_views',
__('Views')
);
$structure->addProperty($leaf);
$exportSpecificOptions->addProperty($structure);
// data main group
$data = new OptionsPropertyMainGroup(
'data',
__('Data dump options')
);
// create primary items and add them to the group
$leaf = new BoolPropertyItem(
'export_contents',
__('Export contents')
);
$data->addProperty($leaf);
$exportSpecificOptions->addProperty($data);
// set the options for the export plugin property item
$exportPluginProperties->setOptions($exportSpecificOptions);
return $exportPluginProperties;
}
/**
* Generates output for SQL defintions of routines
*
* @param string $db Database name
* @param string $type Item type to be used in XML output
* @param string $dbitype Item type used in DBI queries
*
* @return string XML with definitions
*/
private function exportRoutinesDefinition($db, $type, $dbitype)
{
global $dbi;
// Export routines
$routines = $dbi->getProceduresOrFunctions($db, $dbitype);
return $this->exportDefinitions($db, $type, $dbitype, $routines);
}
/**
* Generates output for SQL defintions
*
* @param string $db Database name
* @param string $type Item type to be used in XML output
* @param string $dbitype Item type used in DBI queries
* @param array $names Names of items to export
*
* @return string XML with definitions
*/
private function exportDefinitions($db, $type, $dbitype, array $names)
{
global $crlf, $dbi;
$head = '';
if ($names) {
foreach ($names as $name) {
$head .= ' <pma:' . $type . ' name="'
. htmlspecialchars($name) . '">' . $crlf;
// Do some formatting
$sql = $dbi->getDefinition($db, $dbitype, $name);
$sql = htmlspecialchars(rtrim($sql));
$sql = str_replace("\n", "\n ", $sql);
$head .= ' ' . $sql . $crlf;
$head .= ' </pma:' . $type . '>' . $crlf;
}
}
return $head;
}
/**
* Outputs export header. It is the first method to be called, so all
* the required variables are initialized here.
*/
public function exportHeader(): bool
{
$this->initSpecificVariables();
global $crlf, $cfg, $db, $dbi;
$table = $this->getTable();
$tables = $this->getTables();
$export_struct = isset($GLOBALS['xml_export_functions'])
|| isset($GLOBALS['xml_export_procedures'])
|| isset($GLOBALS['xml_export_tables'])
|| isset($GLOBALS['xml_export_triggers'])
|| isset($GLOBALS['xml_export_views']);
$export_data = isset($GLOBALS['xml_export_contents']);
if ($GLOBALS['output_charset_conversion']) {
$charset = $GLOBALS['charset'];
} else {
$charset = 'utf-8';
}
$head = '<?xml version="1.0" encoding="' . $charset . '"?>' . $crlf
. '<!--' . $crlf
. '- phpMyAdmin XML Dump' . $crlf
. '- version ' . Version::VERSION . $crlf
. '- https://www.phpmyadmin.net' . $crlf
. '-' . $crlf
. '- ' . __('Host:') . ' ' . htmlspecialchars($cfg['Server']['host']);
if (! empty($cfg['Server']['port'])) {
$head .= ':' . $cfg['Server']['port'];
}
$head .= $crlf
. '- ' . __('Generation Time:') . ' '
. Util::localisedDate() . $crlf
. '- ' . __('Server version:') . ' ' . $dbi->getVersionString() . $crlf
. '- ' . __('PHP Version:') . ' ' . PHP_VERSION . $crlf
. '-->' . $crlf . $crlf;
$head .= '<pma_xml_export version="1.0"'
. ($export_struct
? ' xmlns:pma="https://www.phpmyadmin.net/some_doc_url/"'
: '')
. '>' . $crlf;
if ($export_struct) {
$result = $dbi->fetchResult(
'SELECT `DEFAULT_CHARACTER_SET_NAME`, `DEFAULT_COLLATION_NAME`'
. ' FROM `information_schema`.`SCHEMATA` WHERE `SCHEMA_NAME`'
. ' = \'' . $dbi->escapeString($db) . '\' LIMIT 1'
);
$db_collation = $result[0]['DEFAULT_COLLATION_NAME'];
$db_charset = $result[0]['DEFAULT_CHARACTER_SET_NAME'];
$head .= ' <!--' . $crlf;
$head .= ' - Structure schemas' . $crlf;
$head .= ' -->' . $crlf;
$head .= ' <pma:structure_schemas>' . $crlf;
$head .= ' <pma:database name="' . htmlspecialchars($db)
. '" collation="' . htmlspecialchars($db_collation) . '" charset="' . htmlspecialchars($db_charset)
. '">' . $crlf;
if (count($tables) === 0) {
$tables[] = $table;
}
foreach ($tables as $table) {
// Export tables and views
$result = $dbi->fetchResult(
'SHOW CREATE TABLE ' . Util::backquote($db) . '.'
. Util::backquote($table),
0
);
$tbl = (string) $result[$table][1];
$is_view = $dbi->getTable($db, $table)
->isView();
if ($is_view) {
$type = 'view';
} else {
$type = 'table';
}
if ($is_view && ! isset($GLOBALS['xml_export_views'])) {
continue;
}
if (! $is_view && ! isset($GLOBALS['xml_export_tables'])) {
continue;
}
$head .= ' <pma:' . $type . ' name="' . htmlspecialchars($table) . '">'
. $crlf;
$tbl = ' ' . htmlspecialchars($tbl);
$tbl = str_replace("\n", "\n ", $tbl);
$head .= $tbl . ';' . $crlf;
$head .= ' </pma:' . $type . '>' . $crlf;
if (! isset($GLOBALS['xml_export_triggers']) || ! $GLOBALS['xml_export_triggers']) {
continue;
}
// Export triggers
$triggers = $dbi->getTriggers($db, $table);
if (! $triggers) {
continue;
}
foreach ($triggers as $trigger) {
$code = $trigger['create'];
$head .= ' <pma:trigger name="'
. htmlspecialchars($trigger['name']) . '">' . $crlf;
// Do some formatting
$code = mb_substr(rtrim($code), 0, -3);
$code = ' ' . htmlspecialchars($code);
$code = str_replace("\n", "\n ", $code);
$head .= $code . $crlf;
$head .= ' </pma:trigger>' . $crlf;
}
unset($trigger, $triggers);
}
if (isset($GLOBALS['xml_export_functions']) && $GLOBALS['xml_export_functions']) {
$head .= $this->exportRoutinesDefinition($db, 'function', 'FUNCTION');
}
if (isset($GLOBALS['xml_export_procedures']) && $GLOBALS['xml_export_procedures']) {
$head .= $this->exportRoutinesDefinition($db, 'procedure', 'PROCEDURE');
}
if (isset($GLOBALS['xml_export_events']) && $GLOBALS['xml_export_events']) {
// Export events
$events = $dbi->fetchResult(
'SELECT EVENT_NAME FROM information_schema.EVENTS '
. "WHERE EVENT_SCHEMA='" . $dbi->escapeString($db)
. "'"
);
$head .= $this->exportDefinitions($db, 'event', 'EVENT', $events);
}
unset($result);
$head .= ' </pma:database>' . $crlf;
$head .= ' </pma:structure_schemas>' . $crlf;
if ($export_data) {
$head .= $crlf;
}
}
return $this->export->outputHandler($head);
}
/**
* Outputs export footer
*/
public function exportFooter(): bool
{
$foot = '</pma_xml_export>';
return $this->export->outputHandler($foot);
}
/**
* Outputs database header
*
* @param string $db Database name
* @param string $dbAlias Aliases of db
*/
public function exportDBHeader($db, $dbAlias = ''): bool
{
global $crlf;
if (empty($dbAlias)) {
$dbAlias = $db;
}
if (isset($GLOBALS['xml_export_contents']) && $GLOBALS['xml_export_contents']) {
$head = ' <!--' . $crlf
. ' - ' . __('Database:') . ' \''
. htmlspecialchars($dbAlias) . '\'' . $crlf
. ' -->' . $crlf . ' <database name="'
. htmlspecialchars($dbAlias) . '">' . $crlf;
return $this->export->outputHandler($head);
}
return true;
}
/**
* Outputs database footer
*
* @param string $db Database name
*/
public function exportDBFooter($db): bool
{
global $crlf;
if (isset($GLOBALS['xml_export_contents']) && $GLOBALS['xml_export_contents']) {
return $this->export->outputHandler(' </database>' . $crlf);
}
return true;
}
/**
* Outputs CREATE DATABASE statement
*
* @param string $db Database name
* @param string $exportType 'server', 'database', 'table'
* @param string $dbAlias Aliases of db
*/
public function exportDBCreate($db, $exportType, $dbAlias = ''): bool
{
return true;
}
/**
* Outputs the content of a table in XML format
*
* @param string $db database name
* @param string $table table name
* @param string $crlf the end of line sequence
* @param string $errorUrl the url to go back in case of error
* @param string $sqlQuery SQL query for obtaining data
* @param array $aliases Aliases of db/table/columns
*/
public function exportData(
$db,
$table,
$crlf,
$errorUrl,
$sqlQuery,
array $aliases = []
): bool {
global $dbi;
// Do not export data for merge tables
if ($dbi->getTable($db, $table)->isMerge()) {
return true;
}
$db_alias = $db;
$table_alias = $table;
$this->initAlias($aliases, $db_alias, $table_alias);
if (isset($GLOBALS['xml_export_contents']) && $GLOBALS['xml_export_contents']) {
$result = $dbi->query($sqlQuery, DatabaseInterface::CONNECT_USER, DatabaseInterface::QUERY_UNBUFFERED);
$columns_cnt = $result->numFields();
$columns = [];
foreach ($result->getFieldNames() as $column) {
$columns[] = stripslashes($column);
}
$buffer = ' <!-- ' . __('Table') . ' '
. htmlspecialchars($table_alias) . ' -->' . $crlf;
if (! $this->export->outputHandler($buffer)) {
return false;
}
while ($record = $result->fetchRow()) {
$buffer = ' <table name="'
. htmlspecialchars($table_alias) . '">' . $crlf;
for ($i = 0; $i < $columns_cnt; $i++) {
$col_as = $columns[$i];
if (! empty($aliases[$db]['tables'][$table]['columns'][$col_as])) {
$col_as = $aliases[$db]['tables'][$table]['columns'][$col_as];
}
// If a cell is NULL, still export it to preserve
// the XML structure
if (! isset($record[$i])) {
$record[$i] = 'NULL';
}
$buffer .= ' <column name="'
. htmlspecialchars($col_as) . '">'
. htmlspecialchars((string) $record[$i])
. '</column>' . $crlf;
}
$buffer .= ' </table>' . $crlf;
if (! $this->export->outputHandler($buffer)) {
return false;
}
}
}
return true;
}
/* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */
/**
* Gets the table name
*
* @return string
*/
private function getTable()
{
return $this->table;
}
/**
* Sets the table name
*
* @param string $table table name
*/
private function setTable($table): void
{
$this->table = $table;
}
/**
* Gets the table names
*
* @return array
*/
private function getTables()
{
return $this->tables;
}
/**
* Sets the table names
*
* @param array $tables table names
*/
private function setTables(array $tables): void
{
$this->tables = $tables;
}
public static function isAvailable(): bool
{
global $db;
// Can't do server export.
return isset($db) && strlen($db) > 0;
}
}

View file

@ -1,228 +0,0 @@
<?php
/**
* Set of functions used to build YAML dumps of tables
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Export;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\FieldMetadata;
use PhpMyAdmin\Plugins\ExportPlugin;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyMainGroup;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyRootGroup;
use PhpMyAdmin\Properties\Options\Items\HiddenPropertyItem;
use PhpMyAdmin\Properties\Plugins\ExportPluginProperties;
use function __;
use function array_key_exists;
use function is_numeric;
use function str_replace;
use function stripslashes;
/**
* Handles the export for the YAML format
*/
class ExportYaml extends ExportPlugin
{
/**
* @psalm-return non-empty-lowercase-string
*/
public function getName(): string
{
return 'yaml';
}
protected function setProperties(): ExportPluginProperties
{
$exportPluginProperties = new ExportPluginProperties();
$exportPluginProperties->setText('YAML');
$exportPluginProperties->setExtension('yml');
$exportPluginProperties->setMimeType('text/yaml');
$exportPluginProperties->setForceFile(true);
$exportPluginProperties->setOptionsText(__('Options'));
// create the root group that will be the options field for
// $exportPluginProperties
// this will be shown as "Format specific options"
$exportSpecificOptions = new OptionsPropertyRootGroup('Format Specific Options');
// general options main group
$generalOptions = new OptionsPropertyMainGroup('general_opts');
// create primary items and add them to the group
$leaf = new HiddenPropertyItem('structure_or_data');
$generalOptions->addProperty($leaf);
// add the main group to the root group
$exportSpecificOptions->addProperty($generalOptions);
// set the options for the export plugin property item
$exportPluginProperties->setOptions($exportSpecificOptions);
return $exportPluginProperties;
}
/**
* Outputs export header
*/
public function exportHeader(): bool
{
$this->export->outputHandler('%YAML 1.1' . $GLOBALS['crlf'] . '---' . $GLOBALS['crlf']);
return true;
}
/**
* Outputs export footer
*/
public function exportFooter(): bool
{
$this->export->outputHandler('...' . $GLOBALS['crlf']);
return true;
}
/**
* Outputs database header
*
* @param string $db Database name
* @param string $dbAlias Aliases of db
*/
public function exportDBHeader($db, $dbAlias = ''): bool
{
return true;
}
/**
* Outputs database footer
*
* @param string $db Database name
*/
public function exportDBFooter($db): bool
{
return true;
}
/**
* Outputs CREATE DATABASE statement
*
* @param string $db Database name
* @param string $exportType 'server', 'database', 'table'
* @param string $dbAlias Aliases of db
*/
public function exportDBCreate($db, $exportType, $dbAlias = ''): bool
{
return true;
}
/**
* Outputs the content of a table in JSON format
*
* @param string $db database name
* @param string $table table name
* @param string $crlf the end of line sequence
* @param string $errorUrl the url to go back in case of error
* @param string $sqlQuery SQL query for obtaining data
* @param array $aliases Aliases of db/table/columns
*/
public function exportData(
$db,
$table,
$crlf,
$errorUrl,
$sqlQuery,
array $aliases = []
): bool {
global $dbi;
$db_alias = $db;
$table_alias = $table;
$this->initAlias($aliases, $db_alias, $table_alias);
$result = $dbi->query($sqlQuery, DatabaseInterface::CONNECT_USER, DatabaseInterface::QUERY_UNBUFFERED);
$columns_cnt = $result->numFields();
$fieldsMeta = $dbi->getFieldsMeta($result);
$columns = [];
foreach ($fieldsMeta as $i => $field) {
$col_as = $field->name;
if (! empty($aliases[$db]['tables'][$table]['columns'][$col_as])) {
$col_as = $aliases[$db]['tables'][$table]['columns'][$col_as];
}
$columns[$i] = stripslashes($col_as);
}
$record_cnt = 0;
while ($record = $result->fetchRow()) {
$record_cnt++;
// Output table name as comment if this is the first record of the table
if ($record_cnt == 1) {
$buffer = '# ' . $db_alias . '.' . $table_alias . $crlf;
$buffer .= '-' . $crlf;
} else {
$buffer = '-' . $crlf;
}
for ($i = 0; $i < $columns_cnt; $i++) {
if (! array_key_exists($i, $record)) {
continue;
}
if ($record[$i] === null) {
$buffer .= ' ' . $columns[$i] . ': null' . $crlf;
continue;
}
$isNotString = isset($fieldsMeta[$i]) && $fieldsMeta[$i]->isNotType(FieldMetadata::TYPE_STRING);
if (is_numeric($record[$i]) && $isNotString) {
$buffer .= ' ' . $columns[$i] . ': ' . $record[$i] . $crlf;
continue;
}
$record[$i] = str_replace(
[
'\\',
'"',
"\n",
"\r",
],
[
'\\\\',
'\"',
'\n',
'\r',
],
$record[$i]
);
$buffer .= ' ' . $columns[$i] . ': "' . $record[$i] . '"' . $crlf;
}
if (! $this->export->outputHandler($buffer)) {
return false;
}
}
return true;
}
/**
* Outputs result raw query in YAML format
*
* @param string $errorUrl the url to go back in case of error
* @param string|null $db the database where the query is executed
* @param string $sqlQuery the rawquery to output
* @param string $crlf the end of line sequence
*/
public function exportRawQuery(string $errorUrl, ?string $db, string $sqlQuery, string $crlf): bool
{
global $dbi;
if ($db !== null) {
$dbi->selectDb($db);
}
return $this->exportData($db ?? '', '', $crlf, $errorUrl, $sqlQuery);
}
}

View file

@ -1,902 +0,0 @@
<?php
/**
* PhpMyAdmin\Plugins\Export\Helpers\Pdf class
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Export\Helpers;
use PhpMyAdmin\ConfigStorage\Relation;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\Dbal\ResultInterface;
use PhpMyAdmin\FieldMetadata;
use PhpMyAdmin\Pdf as PdfLib;
use PhpMyAdmin\Transformations;
use PhpMyAdmin\Util;
use TCPDF_STATIC;
use function __;
use function array_key_exists;
use function count;
use function ksort;
/**
* Adapted from a LGPL script by Philip Clarke
*/
class Pdf extends PdfLib
{
/** @var array */
public $tablewidths;
/** @var array */
public $headerset;
/** @var int|float */
private $dataY;
/** @var int|float */
private $cellFontSize;
/** @var int */
private $titleFontSize;
/** @var string */
private $titleText;
/** @var string */
private $dbAlias;
/** @var string */
private $tableAlias;
/** @var string */
private $purpose;
/** @var array */
private $colTitles;
/** @var ResultInterface */
private $results;
/** @var array */
private $colAlign;
/** @var mixed */
private $titleWidth;
/** @var mixed */
private $colFits;
/** @var array */
private $displayColumn;
/** @var int */
private $numFields;
/** @var FieldMetadata[] */
private $fields;
/** @var int|float */
private $sColWidth;
/** @var string */
private $currentDb;
/** @var string */
private $currentTable;
/** @var array */
private $aliases;
/** @var Relation */
private $relation;
/** @var Transformations */
private $transformations;
/**
* Constructs PDF and configures standard parameters.
*
* @param string $orientation page orientation
* @param string $unit unit
* @param string $format the format used for pages
* @param bool $unicode true means that the input text is unicode
* @param string $encoding charset encoding; default is UTF-8.
* @param bool $diskcache DEPRECATED TCPDF FEATURE
* @param false|int $pdfa If not false, set the document to PDF/A mode and the good version (1 or 3)
*/
public function __construct(
$orientation = 'P',
$unit = 'mm',
$format = 'A4',
$unicode = true,
$encoding = 'UTF-8',
$diskcache = false,
$pdfa = false
) {
global $dbi;
parent::__construct($orientation, $unit, $format, $unicode, $encoding, $diskcache, $pdfa);
$this->relation = new Relation($dbi);
$this->transformations = new Transformations();
}
/**
* Add page if needed.
*
* @param float|int $h cell height. Default value: 0
* @param mixed $y starting y position, leave empty for current
* position
* @param bool $addpage if true add a page, otherwise only return
* the true/false state
*/
public function checkPageBreak($h = 0, $y = '', $addpage = true): bool
{
if (TCPDF_STATIC::empty_string($y)) {
$y = $this->y;
}
$current_page = $this->page;
// phpcs:ignore Squiz.NamingConventions.ValidVariableName.MemberNotCamelCaps
if ($y + $h > $this->PageBreakTrigger && ! $this->InFooter && $this->AcceptPageBreak()) {
if ($addpage) {
//Automatic page break
$x = $this->x;
// phpcs:ignore Squiz.NamingConventions.ValidVariableName.MemberNotCamelCaps
$this->AddPage($this->CurOrientation);
$this->y = $this->dataY;
$oldpage = $this->page - 1;
$this_page_orm = $this->pagedim[$this->page]['orm'];
$old_page_orm = $this->pagedim[$oldpage]['orm'];
$this_page_olm = $this->pagedim[$this->page]['olm'];
$old_page_olm = $this->pagedim[$oldpage]['olm'];
if ($this->rtl) {
if ($this_page_orm != $old_page_orm) {
$this->x = $x - ($this_page_orm - $old_page_orm);
} else {
$this->x = $x;
}
} else {
if ($this_page_olm != $old_page_olm) {
$this->x = $x + $this_page_olm - $old_page_olm;
} else {
$this->x = $x;
}
}
}
return true;
}
// account for columns mode
return $current_page != $this->page;
}
/**
* This method is used to render the page header.
*/
// phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps
public function Header(): void
{
global $maxY;
// We don't want automatic page breaks while generating header
// as this can lead to infinite recursion as auto generated page
// will want header as well causing another page break
// FIXME: Better approach might be to try to compact the content
$this->setAutoPageBreak(false);
// Check if header for this page already exists
// phpcs:disable Squiz.NamingConventions.ValidVariableName.MemberNotCamelCaps
if (! isset($this->headerset[$this->page])) {
$this->setY($this->tMargin - ($this->FontSizePt / $this->k) * 5);
$this->cellFontSize = $this->FontSizePt;
$this->setFont(PdfLib::PMA_PDF_FONT, '', ($this->titleFontSize ?: $this->FontSizePt));
$this->Cell(0, $this->FontSizePt, $this->titleText, 0, 1, 'C');
$this->setFont(PdfLib::PMA_PDF_FONT, '', $this->cellFontSize);
$this->setY($this->tMargin - ($this->FontSizePt / $this->k) * 2.5);
$this->Cell(
0,
$this->FontSizePt,
__('Database:') . ' ' . $this->dbAlias . ', '
. __('Table:') . ' ' . $this->tableAlias . ', '
. __('Purpose:') . ' ' . $this->purpose,
0,
1,
'L'
);
$l = $this->lMargin;
foreach ($this->colTitles as $col => $txt) {
$this->setXY($l, $this->tMargin);
$this->MultiCell($this->tablewidths[$col], $this->FontSizePt, $txt);
$l += $this->tablewidths[$col];
$maxY = $maxY < $this->GetY() ? $this->GetY() : $maxY;
}
$this->setXY($this->lMargin, $this->tMargin);
$this->setFillColor(200, 200, 200);
$l = $this->lMargin;
foreach ($this->colTitles as $col => $txt) {
$this->setXY($l, $this->tMargin);
$this->Cell($this->tablewidths[$col], $maxY - $this->tMargin, '', 1, 0, 'L', true);
$this->setXY($l, $this->tMargin);
$this->MultiCell($this->tablewidths[$col], $this->FontSizePt, $txt, 0, 'C');
$l += $this->tablewidths[$col];
}
$this->setFillColor(255, 255, 255);
// set headerset
$this->headerset[$this->page] = 1;
}
// phpcs:enable
$this->dataY = $maxY;
$this->setAutoPageBreak(true);
}
/**
* Generate table
*
* @param int $lineheight Height of line
*/
public function morepagestable($lineheight = 8): void
{
// some things to set and 'remember'
$l = $this->lMargin;
$startheight = $h = $this->dataY;
$startpage = $currpage = $this->page;
// calculate the whole width
$fullwidth = 0;
foreach ($this->tablewidths as $width) {
$fullwidth += $width;
}
// Now let's start to write the table
$row = 0;
$tmpheight = [];
$maxpage = $this->page;
while ($data = $this->results->fetchRow()) {
$this->page = $currpage;
// write the horizontal borders
$this->Line($l, $h, $fullwidth + $l, $h);
// write the content and remember the height of the highest col
foreach ($data as $col => $txt) {
$this->page = $currpage;
$this->setXY($l, $h);
if ($this->tablewidths[$col] > 0) {
$this->MultiCell($this->tablewidths[$col], $lineheight, $txt, 0, $this->colAlign[$col]);
$l += $this->tablewidths[$col];
}
if (! isset($tmpheight[$row . '-' . $this->page])) {
$tmpheight[$row . '-' . $this->page] = 0;
}
if ($tmpheight[$row . '-' . $this->page] < $this->GetY()) {
$tmpheight[$row . '-' . $this->page] = $this->GetY();
}
if ($this->page > $maxpage) {
$maxpage = $this->page;
}
unset($data[$col]);
}
// get the height we were in the last used page
$h = $tmpheight[$row . '-' . $maxpage];
// set the "pointer" to the left margin
$l = $this->lMargin;
// set the $currpage to the last page
$currpage = $maxpage;
unset($data[$row]);
$row++;
}
// draw the borders
// we start adding a horizontal line on the last page
$this->page = $maxpage;
$this->Line($l, $h, $fullwidth + $l, $h);
// now we start at the top of the document and walk down
for ($i = $startpage; $i <= $maxpage; $i++) {
$this->page = $i;
$l = $this->lMargin;
$t = $i == $startpage ? $startheight : $this->tMargin;
$lh = $i == $maxpage ? $h : $this->h - $this->bMargin;
$this->Line($l, $t, $l, $lh);
foreach ($this->tablewidths as $width) {
$l += $width;
$this->Line($l, $t, $l, $lh);
}
}
// set it to the last page, if not it'll cause some problems
$this->page = $maxpage;
}
/**
* Defines the top margin.
* The method can be called before creating the first page.
*
* @param float $topMargin the margin
*/
public function setTopMargin($topMargin): void
{
$this->tMargin = $topMargin;
}
/**
* Prints triggers
*
* @param string $db database name
* @param string $table table name
*/
public function getTriggers($db, $table): void
{
global $dbi;
$triggers = $dbi->getTriggers($db, $table);
if ($triggers === []) {
return; //prevents printing blank trigger list for any table
}
unset(
$this->tablewidths,
$this->colTitles,
$this->titleWidth,
$this->colFits,
$this->displayColumn,
$this->colAlign
);
/**
* Making table heading
* Keeping column width constant
*/
$this->colTitles[0] = __('Name');
$this->tablewidths[0] = 90;
$this->colTitles[1] = __('Time');
$this->tablewidths[1] = 80;
$this->colTitles[2] = __('Event');
$this->tablewidths[2] = 40;
$this->colTitles[3] = __('Definition');
$this->tablewidths[3] = 240;
for ($columns_cnt = 0; $columns_cnt < 4; $columns_cnt++) {
$this->colAlign[$columns_cnt] = 'L';
$this->displayColumn[$columns_cnt] = true;
}
// Starting to fill table with required info
$this->setY($this->tMargin);
$this->AddPage();
$this->setFont(PdfLib::PMA_PDF_FONT, '', 9);
$l = $this->lMargin;
$startheight = $h = $this->dataY;
$startpage = $currpage = $this->page;
// calculate the whole width
$fullwidth = 0;
foreach ($this->tablewidths as $width) {
$fullwidth += $width;
}
$row = 0;
$tmpheight = [];
$maxpage = $this->page;
$data = [];
foreach ($triggers as $trigger) {
$data[] = $trigger['name'];
$data[] = $trigger['action_timing'];
$data[] = $trigger['event_manipulation'];
$data[] = $trigger['definition'];
$this->page = $currpage;
// write the horizontal borders
$this->Line($l, $h, $fullwidth + $l, $h);
// write the content and remember the height of the highest col
foreach ($data as $col => $txt) {
$this->page = $currpage;
$this->setXY($l, $h);
if ($this->tablewidths[$col] > 0) {
$this->MultiCell(
$this->tablewidths[$col],
// phpcs:ignore Squiz.NamingConventions.ValidVariableName.MemberNotCamelCaps
$this->FontSizePt,
$txt,
0,
$this->colAlign[$col]
);
$l += $this->tablewidths[$col];
}
if (! isset($tmpheight[$row . '-' . $this->page])) {
$tmpheight[$row . '-' . $this->page] = 0;
}
if ($tmpheight[$row . '-' . $this->page] < $this->GetY()) {
$tmpheight[$row . '-' . $this->page] = $this->GetY();
}
if ($this->page <= $maxpage) {
continue;
}
$maxpage = $this->page;
}
// get the height we were in the last used page
$h = $tmpheight[$row . '-' . $maxpage];
// set the "pointer" to the left margin
$l = $this->lMargin;
// set the $currpage to the last page
$currpage = $maxpage;
unset($data);
$row++;
}
// draw the borders
// we start adding a horizontal line on the last page
$this->page = $maxpage;
$this->Line($l, $h, $fullwidth + $l, $h);
// now we start at the top of the document and walk down
for ($i = $startpage; $i <= $maxpage; $i++) {
$this->page = $i;
$l = $this->lMargin;
$t = $i == $startpage ? $startheight : $this->tMargin;
$lh = $i == $maxpage ? $h : $this->h - $this->bMargin;
$this->Line($l, $t, $l, $lh);
foreach ($this->tablewidths as $width) {
$l += $width;
$this->Line($l, $t, $l, $lh);
}
}
// set it to the last page, if not it'll cause some problems
$this->page = $maxpage;
}
/**
* Print $table's CREATE definition
*
* @param string $db the database name
* @param string $table the table name
* @param bool $do_relation whether to include relation comments
* @param bool $do_comments whether to include the pmadb-style column
* comments as comments in the structure;
* this is deprecated but the parameter is
* left here because /export calls
* PMA_exportStructure() also for other
* export types which use this parameter
* @param bool $do_mime whether to include mime comments
* @param bool $view whether we're handling a view
* @param array $aliases aliases of db/table/columns
*/
public function getTableDef(
$db,
$table,
$do_relation,
$do_comments,
$do_mime,
$view = false,
array $aliases = []
): void {
global $dbi;
$relationParameters = $this->relation->getRelationParameters();
unset(
$this->tablewidths,
$this->colTitles,
$this->titleWidth,
$this->colFits,
$this->displayColumn,
$this->colAlign
);
/**
* Gets fields properties
*/
$dbi->selectDb($db);
/**
* All these three checks do_relation, do_comment and do_mime is
* not required. As presently all are set true by default.
* But when, methods to take user input will be developed,
* it will be of use
*/
// Check if we can use Relations
if ($do_relation) {
// Find which tables are related with the current one and write it in
// an array
$res_rel = $this->relation->getForeigners($db, $table);
$have_rel = ! empty($res_rel);
} else {
$have_rel = false;
}
//column count and table heading
$this->colTitles[0] = __('Column');
$this->tablewidths[0] = 90;
$this->colTitles[1] = __('Type');
$this->tablewidths[1] = 80;
$this->colTitles[2] = __('Null');
$this->tablewidths[2] = 40;
$this->colTitles[3] = __('Default');
$this->tablewidths[3] = 120;
for ($columns_cnt = 0; $columns_cnt < 4; $columns_cnt++) {
$this->colAlign[$columns_cnt] = 'L';
$this->displayColumn[$columns_cnt] = true;
}
if ($do_relation && $have_rel) {
$this->colTitles[$columns_cnt] = __('Links to');
$this->displayColumn[$columns_cnt] = true;
$this->colAlign[$columns_cnt] = 'L';
$this->tablewidths[$columns_cnt] = 120;
}
if ($do_comments) {
$columns_cnt++;
$this->colTitles[$columns_cnt] = __('Comments');
$this->displayColumn[$columns_cnt] = true;
$this->colAlign[$columns_cnt] = 'L';
$this->tablewidths[$columns_cnt] = 120;
}
if ($do_mime && $relationParameters->browserTransformationFeature !== null) {
$columns_cnt++;
$this->colTitles[$columns_cnt] = __('Media type');
$this->displayColumn[$columns_cnt] = true;
$this->colAlign[$columns_cnt] = 'L';
$this->tablewidths[$columns_cnt] = 120;
}
// Starting to fill table with required info
$this->setY($this->tMargin);
$this->AddPage();
$this->setFont(PdfLib::PMA_PDF_FONT, '', 9);
// Now let's start to write the table structure
if ($do_comments) {
$comments = $this->relation->getComments($db, $table);
}
if ($do_mime && $relationParameters->browserTransformationFeature !== null) {
$mime_map = $this->transformations->getMime($db, $table, true);
}
$columns = $dbi->getColumns($db, $table);
// some things to set and 'remember'
$l = $this->lMargin;
$startheight = $h = $this->dataY;
$startpage = $currpage = $this->page;
// calculate the whole width
$fullwidth = 0;
foreach ($this->tablewidths as $width) {
$fullwidth += $width;
}
$row = 0;
$tmpheight = [];
$maxpage = $this->page;
$data = [];
// fun begin
foreach ($columns as $column) {
$extracted_columnspec = Util::extractColumnSpec($column['Type']);
$type = $extracted_columnspec['print_type'];
if (empty($type)) {
$type = ' ';
}
if (! isset($column['Default'])) {
if ($column['Null'] !== 'NO') {
$column['Default'] = 'NULL';
}
}
$data[] = $column['Field'];
$data[] = $type;
$data[] = $column['Null'] == '' || $column['Null'] === 'NO'
? 'No'
: 'Yes';
$data[] = $column['Default'] ?? '';
$field_name = $column['Field'];
if ($do_relation && $have_rel) {
$data[] = isset($res_rel[$field_name])
? $res_rel[$field_name]['foreign_table']
. ' (' . $res_rel[$field_name]['foreign_field']
. ')'
: '';
}
if ($do_comments) {
$data[] = $comments[$field_name] ?? '';
}
if ($do_mime) {
$data[] = isset($mime_map[$field_name])
? $mime_map[$field_name]['mimetype']
: '';
}
$this->page = $currpage;
// write the horizontal borders
$this->Line($l, $h, $fullwidth + $l, $h);
// write the content and remember the height of the highest col
foreach ($data as $col => $txt) {
$this->page = $currpage;
$this->setXY($l, $h);
if ($this->tablewidths[$col] > 0) {
$this->MultiCell(
$this->tablewidths[$col],
// phpcs:ignore Squiz.NamingConventions.ValidVariableName.MemberNotCamelCaps
$this->FontSizePt,
$txt,
0,
$this->colAlign[$col]
);
$l += $this->tablewidths[$col];
}
if (! isset($tmpheight[$row . '-' . $this->page])) {
$tmpheight[$row . '-' . $this->page] = 0;
}
if ($tmpheight[$row . '-' . $this->page] < $this->GetY()) {
$tmpheight[$row . '-' . $this->page] = $this->GetY();
}
if ($this->page <= $maxpage) {
continue;
}
$maxpage = $this->page;
}
// get the height we were in the last used page
$h = $tmpheight[$row . '-' . $maxpage];
// set the "pointer" to the left margin
$l = $this->lMargin;
// set the $currpage to the last page
$currpage = $maxpage;
unset($data);
$row++;
}
// draw the borders
// we start adding a horizontal line on the last page
$this->page = $maxpage;
$this->Line($l, $h, $fullwidth + $l, $h);
// now we start at the top of the document and walk down
for ($i = $startpage; $i <= $maxpage; $i++) {
$this->page = $i;
$l = $this->lMargin;
$t = $i == $startpage ? $startheight : $this->tMargin;
$lh = $i == $maxpage ? $h : $this->h - $this->bMargin;
$this->Line($l, $t, $l, $lh);
foreach ($this->tablewidths as $width) {
$l += $width;
$this->Line($l, $t, $l, $lh);
}
}
// set it to the last page, if not it'll cause some problems
$this->page = $maxpage;
}
/**
* MySQL report
*
* @param string $query Query to execute
*/
public function mysqlReport($query): void
{
global $dbi;
unset(
$this->tablewidths,
$this->colTitles,
$this->titleWidth,
$this->colFits,
$this->displayColumn,
$this->colAlign
);
/**
* Pass 1 for column widths
*/
$this->results = $dbi->query($query, DatabaseInterface::CONNECT_USER, DatabaseInterface::QUERY_UNBUFFERED);
$this->numFields = $this->results->numFields();
$this->fields = $dbi->getFieldsMeta($this->results);
// sColWidth = starting col width (an average size width)
$availableWidth = $this->w - $this->lMargin - $this->rMargin;
$this->sColWidth = $availableWidth / $this->numFields;
$totalTitleWidth = 0;
// loop through results header and set initial
// col widths/ titles/ alignment
// if a col title is less than the starting col width,
// reduce that column size
$colFits = [];
$titleWidth = [];
for ($i = 0; $i < $this->numFields; $i++) {
$col_as = $this->fields[$i]->name;
$db = $this->currentDb;
$table = $this->currentTable;
if (! empty($this->aliases[$db]['tables'][$table]['columns'][$col_as])) {
$col_as = $this->aliases[$db]['tables'][$table]['columns'][$col_as];
}
/** @var float $stringWidth */
$stringWidth = $this->GetStringWidth($col_as);
$stringWidth += 6;
// save the real title's width
$titleWidth[$i] = $stringWidth;
$totalTitleWidth += $stringWidth;
// set any column titles less than the start width to
// the column title width
if ($stringWidth < $this->sColWidth) {
$colFits[$i] = $stringWidth;
}
$this->colTitles[$i] = $col_as;
$this->displayColumn[$i] = true;
$this->colAlign[$i] = 'L';
if ($this->fields[$i]->isType(FieldMetadata::TYPE_INT)) {
$this->colAlign[$i] = 'R';
}
if (! $this->fields[$i]->isType(FieldMetadata::TYPE_BLOB)) {
continue;
}
/**
* @todo do not deactivate completely the display
* but show the field's name and [BLOB]
*/
if ($this->fields[$i]->isBinary()) {
$this->displayColumn[$i] = false;
unset($this->colTitles[$i]);
}
$this->colAlign[$i] = 'L';
}
// title width verification
if ($totalTitleWidth > $availableWidth) {
$adjustingMode = true;
} else {
$adjustingMode = false;
// we have enough space for all the titles at their
// original width so use the true title's width
foreach ($titleWidth as $key => $val) {
$colFits[$key] = $val;
}
}
// loop through the data; any column whose contents
// is greater than the column size is resized
/**
* @todo force here a LIMIT to avoid reading all rows
*/
while ($row = $this->results->fetchRow()) {
foreach ($colFits as $key => $val) {
/** @var float $stringWidth */
$stringWidth = $this->GetStringWidth($row[$key]);
$stringWidth += 6;
if ($adjustingMode && ($stringWidth > $this->sColWidth)) {
// any column whose data's width is bigger than
// the start width is now discarded
unset($colFits[$key]);
} else {
// if data's width is bigger than the current column width,
// enlarge the column (but avoid enlarging it if the
// data's width is very big)
if ($stringWidth > $val && $stringWidth < $this->sColWidth * 3) {
$colFits[$key] = $stringWidth;
}
}
}
}
$totAlreadyFitted = 0;
foreach ($colFits as $key => $val) {
// set fitted columns to smallest size
$this->tablewidths[$key] = $val;
// to work out how much (if any) space has been freed up
$totAlreadyFitted += $val;
}
if ($adjustingMode) {
$surplus = (count($colFits) * $this->sColWidth) - $totAlreadyFitted;
$surplusToAdd = $surplus / ($this->numFields - count($colFits));
} else {
$surplusToAdd = 0;
}
for ($i = 0; $i < $this->numFields; $i++) {
if (! array_key_exists($i, $colFits)) {
$this->tablewidths[$i] = $this->sColWidth + $surplusToAdd;
}
if ($this->displayColumn[$i] != false) {
continue;
}
$this->tablewidths[$i] = 0;
}
ksort($this->tablewidths);
// Pass 2
$this->results = $dbi->query($query, DatabaseInterface::CONNECT_USER, DatabaseInterface::QUERY_UNBUFFERED);
$this->setY($this->tMargin);
$this->AddPage();
$this->setFont(PdfLib::PMA_PDF_FONT, '', 9);
// phpcs:ignore Squiz.NamingConventions.ValidVariableName.MemberNotCamelCaps
$this->morepagestable($this->FontSizePt);
}
public function setTitleFontSize(int $titleFontSize): void
{
$this->titleFontSize = $titleFontSize;
}
public function setTitleText(string $titleText): void
{
$this->titleText = $titleText;
}
public function setCurrentDb(?string $currentDb): void
{
$this->currentDb = $currentDb ?? '';
}
public function setCurrentTable(?string $currentTable): void
{
$this->currentTable = $currentTable ?? '';
}
public function setDbAlias(?string $dbAlias): void
{
$this->dbAlias = $dbAlias ?? '';
}
public function setTableAlias(?string $tableAlias): void
{
$this->tableAlias = $tableAlias ?? '';
}
/**
* @param array $aliases
*/
public function setAliases(array $aliases): void
{
$this->aliases = $aliases;
}
public function setPurpose(string $purpose): void
{
$this->purpose = $purpose;
}
}

View file

@ -1,294 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Export\Helpers;
use PhpMyAdmin\Plugins\Export\ExportCodegen;
use function htmlspecialchars;
use function mb_strpos;
use function mb_substr;
use function str_replace;
use function strlen;
use function trim;
use const ENT_COMPAT;
/**
* PhpMyAdmin\Plugins\Export\Helpers\TableProperty class
*/
class TableProperty
{
/**
* Name
*
* @var string
*/
public $name;
/**
* Type
*
* @var string
*/
public $type;
/**
* Whether the key is nullable or not
*
* @var string
*/
public $nullable;
/**
* The key
*
* @var string
*/
public $key;
/**
* Default value
*
* @var mixed
*/
public $defaultValue;
/**
* Extension
*
* @var string
*/
public $ext;
/**
* @param array $row table row
*/
public function __construct(array $row)
{
$this->name = trim((string) $row[0]);
$this->type = trim((string) $row[1]);
$this->nullable = trim((string) $row[2]);
$this->key = trim((string) $row[3]);
$this->defaultValue = trim((string) $row[4]);
$this->ext = trim((string) $row[5]);
}
/**
* Gets the pure type
*
* @return string type
*/
public function getPureType()
{
$pos = (int) mb_strpos($this->type, '(');
if ($pos > 0) {
return mb_substr($this->type, 0, $pos);
}
return $this->type;
}
/**
* Tells whether the key is null or not
*
* @return string true if the key is not null, false otherwise
*/
public function isNotNull()
{
return $this->nullable === 'NO' ? 'true' : 'false';
}
/**
* Tells whether the key is unique or not
*
* @return string "true" if the key is unique, "false" otherwise
*/
public function isUnique(): string
{
return $this->key === 'PRI' || $this->key === 'UNI' ? 'true' : 'false';
}
/**
* Gets the .NET primitive type
*
* @return string type
*/
public function getDotNetPrimitiveType()
{
if (mb_strpos($this->type, 'int') === 0) {
return 'int';
}
if (mb_strpos($this->type, 'longtext') === 0) {
return 'string';
}
if (mb_strpos($this->type, 'long') === 0) {
return 'long';
}
if (mb_strpos($this->type, 'char') === 0) {
return 'string';
}
if (mb_strpos($this->type, 'varchar') === 0) {
return 'string';
}
if (mb_strpos($this->type, 'text') === 0) {
return 'string';
}
if (mb_strpos($this->type, 'tinyint') === 0) {
return 'bool';
}
if (mb_strpos($this->type, 'datetime') === 0) {
return 'DateTime';
}
return 'unknown';
}
/**
* Gets the .NET object type
*
* @return string type
*/
public function getDotNetObjectType()
{
if (mb_strpos($this->type, 'int') === 0) {
return 'Int32';
}
if (mb_strpos($this->type, 'longtext') === 0) {
return 'String';
}
if (mb_strpos($this->type, 'long') === 0) {
return 'Long';
}
if (mb_strpos($this->type, 'char') === 0) {
return 'String';
}
if (mb_strpos($this->type, 'varchar') === 0) {
return 'String';
}
if (mb_strpos($this->type, 'text') === 0) {
return 'String';
}
if (mb_strpos($this->type, 'tinyint') === 0) {
return 'Boolean';
}
if (mb_strpos($this->type, 'datetime') === 0) {
return 'DateTime';
}
return 'Unknown';
}
/**
* Gets the index name
*
* @return string containing the name of the index
*/
public function getIndexName()
{
if (strlen($this->key) > 0) {
return 'index="'
. htmlspecialchars($this->name, ENT_COMPAT, 'UTF-8')
. '"';
}
return '';
}
/**
* Tells whether the key is primary or not
*/
public function isPK(): bool
{
return $this->key === 'PRI';
}
/**
* Formats a string for C#
*
* @param string $text string to be formatted
*
* @return string formatted text
*/
public function formatCs($text)
{
$text = str_replace(
'#name#',
ExportCodegen::cgMakeIdentifier($this->name, false),
$text
);
return $this->format($text);
}
/**
* Formats a string for XML
*
* @param string $text string to be formatted
*
* @return string formatted text
*/
public function formatXml($text)
{
$text = str_replace(
[
'#name#',
'#indexName#',
],
[
htmlspecialchars($this->name, ENT_COMPAT, 'UTF-8'),
$this->getIndexName(),
],
$text
);
return $this->format($text);
}
/**
* Formats a string
*
* @param string $text string to be formatted
*
* @return string formatted text
*/
public function format($text)
{
$text = str_replace(
[
'#ucfirstName#',
'#dotNetPrimitiveType#',
'#dotNetObjectType#',
'#type#',
'#notNull#',
'#unique#',
],
[
ExportCodegen::cgMakeIdentifier($this->name),
$this->getDotNetPrimitiveType(),
$this->getDotNetObjectType(),
$this->getPureType(),
$this->isNotNull(),
$this->isUnique(),
],
$text
);
return $text;
}
}

View file

@ -1,247 +0,0 @@
# Export plugin creation
This directory holds export plugins for phpMyAdmin. Any new plugin should
basically follow the structure presented here. Official plugins need to
have str* messages with their definition in language files, but if you build
some plugins for your use, you can directly use texts in plugin.
```php
<?php
/**
* [Name] export plugin for phpMyAdmin
*/
declare(strict_types=1);
/**
* Handles the export for the [Name] format
*/
class Export[Name] extends PhpMyAdmin\Plugins\ExportPlugin
{
/**
* optional - declare variables and descriptions
*
* @var VariableType
*/
private $myOptionalVariable;
/**
* optional - declare global variables and descriptions
*
* @var VariableType
*/
private $globalVariableName;
/**
* Constructor
*/
public function __construct()
{
$this->setProperties();
}
// optional - declare global variables and use getters later
/**
* Initialize the local variables that are used specific for export SQL
*
* @return void
*
* @global VariableType $global_variable_name
* [..]
*/
protected function initSpecificVariables()
{
global $global_variable_name;
$this->setGlobalVariableName($global_variable_name);
}
/**
* Sets the export plugin properties.
* Called in the constructor.
*
* @return void
*/
protected function setProperties()
{
$exportPluginProperties = new PhpMyAdmin\Properties\Plugins\ExportPluginProperties();
$exportPluginProperties->setText('[name]'); // the name of your plug-in
$exportPluginProperties->setExtension('[ext]'); // extension this plug-in can handle
$exportPluginProperties->setOptionsText(__('Options'));
// create the root group that will be the options field for
// $exportPluginProperties
// this will be shown as "Format specific options"
$exportSpecificOptions = new PhpMyAdmin\Properties\Options\Groups\OptionsPropertyRootGroup(
'Format Specific Options'
);
// general options main group
$generalOptions = new PhpMyAdmin\Properties\Options\Groups\OptionsPropertyMainGroup(
'general_opts'
);
// optional :
// create primary items and add them to the group
// type - one of the classes listed in libraries/properties/options/items/
// name - form element name
// text - description in GUI
// size - size of text element
// len - maximal size of input
// values - possible values of the item
$leaf = new PhpMyAdmin\Properties\Options\Items\RadioPropertyItem(
'structure_or_data'
);
$leaf->setValues(
[
'structure' => __('structure'),
'data' => __('data'),
'structure_and_data' => __('structure and data'),
]
);
$generalOptions->addProperty($leaf);
// add the main group to the root group
$exportSpecificOptions->addProperty($generalOptions);
// set the options for the export plugin property item
$exportPluginProperties->setOptions($exportSpecificOptions);
$this->properties = $exportPluginProperties;
}
/**
* Outputs export header
*
* @return bool Whether it succeeded
*/
public function exportHeader()
{
// implementation
return true;
}
/**
* Outputs export footer
*
* @return bool Whether it succeeded
*/
public function exportFooter()
{
// implementation
return true;
}
/**
* Outputs database header
*
* @param string $db Database name
* @param string $dbAlias Aliases of db
*
* @return bool Whether it succeeded
*/
public function exportDBHeader($db, $dbAlias = '')
{
// implementation
return true;
}
/**
* Outputs database footer
*
* @param string $db Database name
*
* @return bool Whether it succeeded
*/
public function exportDBFooter($db)
{
// implementation
return true;
}
/**
* Outputs CREATE DATABASE statement
*
* @param string $db Database name
* @param string $exportType 'server', 'database', 'table'
* @param string $dbAlias Aliases of db
*
* @return bool Whether it succeeded
*/
public function exportDBCreate($db, $exportType, $dbAlias = '')
{
// implementation
return true;
}
/**
* Outputs the content of a table in [Name] format
*
* @param string $db database name
* @param string $table table name
* @param string $crlf the end of line sequence
* @param string $errorUrl the url to go back in case of error
* @param string $sqlQuery SQL query for obtaining data
* @param array $aliases Aliases of db/table/columns
*
* @return bool Whether it succeeded
*/
public function exportData(
$db,
$table,
$crlf,
$errorUrl,
$sqlQuery,
array $aliases = []
) {
// implementation;
return true;
}
// optional - implement other methods defined in PhpMyAdmin\Plugins\ExportPlugin.php:
// - exportRoutines()
// - exportStructure()
// - getTableDefStandIn()
// - getTriggers()
// optional - implement other private methods in order to avoid
// having huge methods or avoid duplicate code. Make use of them
// as well as of the getters and setters declared both here
// and in the PhpMyAdmin\Plugins\ExportPlugin class
// optional:
/* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */
/**
* Getter description
*/
private function getMyOptionalVariable(): VariableType
{
return $this->myOptionalVariable;
}
/**
* Setter description
*/
private function setMyOptionalVariable(VariableType $my_optional_variable): void
{
$this->myOptionalVariable = $my_optional_variable;
}
/**
* Getter description
*/
private function getGlobalVariableName(): VariableType
{
return $this->globalVariableName;
}
/**
* Setter description
*/
private function setGlobalVariableName(VariableType $global_variable_name): void
{
$this->globalVariableName = $global_variable_name;
}
}
```

View file

@ -1,381 +0,0 @@
<?php
/**
* Abstract class for the export plugins
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins;
use PhpMyAdmin\ConfigStorage\Relation;
use PhpMyAdmin\Export;
use PhpMyAdmin\Properties\Plugins\ExportPluginProperties;
use PhpMyAdmin\Properties\Plugins\PluginPropertyItem;
use PhpMyAdmin\Transformations;
use function stripos;
/**
* Provides a common interface that will have to be implemented by all of the
* export plugins. Some of the plugins will also implement other public
* methods, but those are not declared here, because they are not implemented
* by all export plugins.
*/
abstract class ExportPlugin implements Plugin
{
/**
* Object containing the specific export plugin type properties.
*
* @var ExportPluginProperties
*/
protected $properties;
/** @var Relation */
public $relation;
/** @var Export */
protected $export;
/** @var Transformations */
protected $transformations;
/**
* @psalm-suppress InvalidArrayOffset, MixedAssignment, MixedMethodCall
*/
final public function __construct()
{
$this->relation = $GLOBALS['containerBuilder']->get('relation');
$this->export = $GLOBALS['containerBuilder']->get('export');
$this->transformations = $GLOBALS['containerBuilder']->get('transformations');
$this->init();
$this->properties = $this->setProperties();
}
/**
* Outputs export header
*/
abstract public function exportHeader(): bool;
/**
* Outputs export footer
*/
abstract public function exportFooter(): bool;
/**
* Outputs database header
*
* @param string $db Database name
* @param string $dbAlias Aliases of db
*/
abstract public function exportDBHeader($db, $dbAlias = ''): bool;
/**
* Outputs database footer
*
* @param string $db Database name
*/
abstract public function exportDBFooter($db): bool;
/**
* Outputs CREATE DATABASE statement
*
* @param string $db Database name
* @param string $exportType 'server', 'database', 'table'
* @param string $dbAlias Aliases of db
*/
abstract public function exportDBCreate($db, $exportType, $dbAlias = ''): bool;
/**
* Outputs the content of a table
*
* @param string $db database name
* @param string $table table name
* @param string $crlf the end of line sequence
* @param string $errorUrl the url to go back in case of error
* @param string $sqlQuery SQL query for obtaining data
* @param array $aliases Aliases of db/table/columns
*/
abstract public function exportData(
$db,
$table,
$crlf,
$errorUrl,
$sqlQuery,
array $aliases = []
): bool;
/**
* The following methods are used in /export or in /database/operations,
* but they are not implemented by all export plugins
*/
/**
* Exports routines (procedures and functions)
*
* @param string $db Database
* @param array $aliases Aliases of db/table/columns
*/
public function exportRoutines($db, array $aliases = []): bool
{
return true;
}
/**
* Exports events
*
* @param string $db Database
*/
public function exportEvents($db): bool
{
return true;
}
/**
* Outputs for raw query
*
* @param string $errorUrl the url to go back in case of error
* @param string|null $db the database where the query is executed
* @param string $sqlQuery the rawquery to output
* @param string $crlf the end of line sequence
*/
public function exportRawQuery(
string $errorUrl,
?string $db,
string $sqlQuery,
string $crlf
): bool {
return false;
}
/**
* Outputs table's structure
*
* @param string $db database name
* @param string $table table name
* @param string $crlf the end of line sequence
* @param string $errorUrl the url to go back in case of error
* @param string $exportMode 'create_table','triggers','create_view',
* 'stand_in'
* @param string $exportType 'server', 'database', 'table'
* @param bool $relation whether to include relation comments
* @param bool $comments whether to include the pmadb-style column comments
* as comments in the structure; this is deprecated
* but the parameter is left here because /export
* calls exportStructure() also for other export
* types which use this parameter
* @param bool $mime whether to include mime comments
* @param bool $dates whether to include creation/update/check dates
* @param array $aliases Aliases of db/table/columns
*/
public function exportStructure(
$db,
$table,
$crlf,
$errorUrl,
$exportMode,
$exportType,
$relation = false,
$comments = false,
$mime = false,
$dates = false,
array $aliases = []
): bool {
return true;
}
/**
* Exports metadata from Configuration Storage
*
* @param string $db database being exported
* @param string|array $tables table(s) being exported
* @param array $metadataTypes types of metadata to export
*/
public function exportMetadata(
$db,
$tables,
array $metadataTypes
): bool {
return true;
}
/**
* Returns a stand-in CREATE definition to resolve view dependencies
*
* @param string $db the database name
* @param string $view the view name
* @param string $crlf the end of line sequence
* @param array $aliases Aliases of db/table/columns
*
* @return string resulting definition
*/
public function getTableDefStandIn($db, $view, $crlf, $aliases = [])
{
return '';
}
/**
* Outputs triggers
*
* @param string $db database name
* @param string $table table name
*
* @return string Formatted triggers list
*/
protected function getTriggers($db, $table)
{
return '';
}
/**
* Plugin specific initializations.
*/
protected function init(): void
{
}
/**
* Gets the export specific format plugin properties
*
* @return ExportPluginProperties
*/
public function getProperties(): PluginPropertyItem
{
return $this->properties;
}
/**
* Sets the export plugins properties and is implemented by each export plugin.
*/
abstract protected function setProperties(): ExportPluginProperties;
/**
* The following methods are implemented here so that they
* can be used by all export plugin without overriding it.
* Note: If you are creating a export plugin then don't include
* below methods unless you want to override them.
*/
/**
* Initialize aliases
*
* @param array $aliases Alias information for db/table/column
* @param string $db the database
* @param string $table the table
*/
public function initAlias($aliases, &$db, &$table = null): void
{
if (! empty($aliases[$db]['tables'][$table]['alias'])) {
$table = $aliases[$db]['tables'][$table]['alias'];
}
if (empty($aliases[$db]['alias'])) {
return;
}
$db = $aliases[$db]['alias'];
}
/**
* Search for alias of a identifier.
*
* @param array $aliases Alias information for db/table/column
* @param string $id the identifier to be searched
* @param string $type db/tbl/col or any combination of them
* representing what to be searched
* @param string $db the database in which search is to be done
* @param string $tbl the table in which search is to be done
*
* @return string alias of the identifier if found or ''
*/
public function getAlias(array $aliases, $id, $type = 'dbtblcol', $db = '', $tbl = '')
{
if (! empty($db) && isset($aliases[$db])) {
$aliases = [
$db => $aliases[$db],
];
}
// search each database
foreach ($aliases as $db_key => $db) {
// check if id is database and has alias
if (stripos($type, 'db') !== false && $db_key === $id && ! empty($db['alias'])) {
return $db['alias'];
}
if (empty($db['tables'])) {
continue;
}
if (! empty($tbl) && isset($db['tables'][$tbl])) {
$db['tables'] = [
$tbl => $db['tables'][$tbl],
];
}
// search each of its tables
foreach ($db['tables'] as $table_key => $table) {
// check if id is table and has alias
if (stripos($type, 'tbl') !== false && $table_key === $id && ! empty($table['alias'])) {
return $table['alias'];
}
if (empty($table['columns'])) {
continue;
}
// search each of its columns
foreach ($table['columns'] as $col_key => $col) {
// check if id is column
if (stripos($type, 'col') !== false && $col_key === $id && ! empty($col)) {
return $col;
}
}
}
}
return '';
}
/**
* Gives the relation string and
* also substitutes with alias if required
* in this format:
* [Foreign Table] ([Foreign Field])
*
* @param array $foreigners the foreigners array
* @param string $fieldName the field name
* @param string $db the field name
* @param array $aliases Alias information for db/table/column
*
* @return string the Relation string
*/
public function getRelationString(
array $foreigners,
$fieldName,
$db,
array $aliases = []
) {
$relation = '';
$foreigner = $this->relation->searchColumnInForeigners($foreigners, $fieldName);
if ($foreigner) {
$ftable = $foreigner['foreign_table'];
$ffield = $foreigner['foreign_field'];
if (! empty($aliases[$db]['tables'][$ftable]['columns'][$ffield])) {
$ffield = $aliases[$db]['tables'][$ftable]['columns'][$ffield];
}
if (! empty($aliases[$db]['tables'][$ftable]['alias'])) {
$ftable = $aliases[$db]['tables'][$ftable]['alias'];
}
$relation = $ftable . ' (' . $ffield . ')';
}
return $relation;
}
public static function isAvailable(): bool
{
return true;
}
}

View file

@ -1,97 +0,0 @@
<?php
/**
* Abstract class for the I/O transformations plugins
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins;
/**
* Provides a common interface that will have to be implemented
* by all of the Input/Output transformations plugins.
*/
abstract class IOTransformationsPlugin extends TransformationsPlugin
{
/**
* Specifies whether transformation was successful or not.
*
* @var bool
*/
protected $success = true;
/**
* To store the error message in case of failed transformations.
*
* @var string
*/
protected $error = '';
/**
* Returns the html for input field to override default textarea.
* Note: Return empty string if default textarea is required.
*
* @param array $column column details
* @param int $row_id row number
* @param string $column_name_appendix the name attribute
* @param array $options transformation options
* @param string $value Current field value
* @param string $text_dir text direction
* @param int $tabindex tab index
* @param int $tabindex_for_value offset for the values tabindex
* @param int $idindex id index
*
* @return string the html for input field
*/
public function getInputHtml(
array $column,
$row_id,
$column_name_appendix,
array $options,
$value,
$text_dir,
$tabindex,
$tabindex_for_value,
$idindex
) {
return '';
}
/**
* Returns the array of scripts (filename) required for plugin
* initialization and handling
*
* @return array javascripts to be included
*/
public function getScripts()
{
return [];
}
/**
* Returns the error message
*
* @return string error
*/
public function getError()
{
return $this->error;
}
/**
* Returns the success status
*/
public function isSuccess(): bool
{
return $this->success;
}
/**
* Resets the object properties
*/
public function reset(): void
{
$this->success = true;
$this->error = '';
}
}

View file

@ -1,63 +0,0 @@
<?php
/**
* Super class of CSV import plugins for phpMyAdmin
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Import;
use PhpMyAdmin\Plugins\ImportPlugin;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyMainGroup;
use PhpMyAdmin\Properties\Options\Items\BoolPropertyItem;
use PhpMyAdmin\Properties\Options\Items\TextPropertyItem;
use function __;
/**
* Super class of the import plugins for the CSV format
*/
abstract class AbstractImportCsv extends ImportPlugin
{
final protected function getGeneralOptions(): OptionsPropertyMainGroup
{
$generalOptions = new OptionsPropertyMainGroup('general_opts');
// create common items and add them to the group
$leaf = new BoolPropertyItem(
'replace',
__(
'Update data when duplicate keys found on import (add ON DUPLICATE KEY UPDATE)'
)
);
$generalOptions->addProperty($leaf);
$leaf = new TextPropertyItem(
'terminated',
__('Columns separated with:')
);
$leaf->setSize(2);
$generalOptions->addProperty($leaf);
$leaf = new TextPropertyItem(
'enclosed',
__('Columns enclosed with:')
);
$leaf->setSize(2);
$leaf->setLen(2);
$generalOptions->addProperty($leaf);
$leaf = new TextPropertyItem(
'escaped',
__('Columns escaped with:')
);
$leaf->setSize(2);
$leaf->setLen(2);
$generalOptions->addProperty($leaf);
$leaf = new TextPropertyItem(
'new_line',
__('Lines terminated with:')
);
$leaf->setSize(2);
$generalOptions->addProperty($leaf);
return $generalOptions;
}
}

View file

@ -1,886 +0,0 @@
<?php
/**
* CSV import plugin for phpMyAdmin
*
* @todo add an option for handling NULL values
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Import;
use PhpMyAdmin\File;
use PhpMyAdmin\Html\Generator;
use PhpMyAdmin\Message;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyRootGroup;
use PhpMyAdmin\Properties\Options\Items\BoolPropertyItem;
use PhpMyAdmin\Properties\Options\Items\NumberPropertyItem;
use PhpMyAdmin\Properties\Options\Items\TextPropertyItem;
use PhpMyAdmin\Properties\Plugins\ImportPluginProperties;
use PhpMyAdmin\Util;
use function __;
use function array_shift;
use function array_splice;
use function basename;
use function count;
use function mb_strlen;
use function mb_strtolower;
use function mb_substr;
use function preg_grep;
use function preg_replace;
use function preg_split;
use function rtrim;
use function str_contains;
use function strlen;
use function strtr;
use function trim;
/**
* Handles the import for the CSV format
*/
class ImportCsv extends AbstractImportCsv
{
/**
* Whether to analyze tables
*
* @var bool
*/
private $analyze;
/**
* @psalm-return non-empty-lowercase-string
*/
public function getName(): string
{
return 'csv';
}
protected function setProperties(): ImportPluginProperties
{
$this->setAnalyze(false);
if ($GLOBALS['plugin_param'] !== 'table') {
$this->setAnalyze(true);
}
$importPluginProperties = new ImportPluginProperties();
$importPluginProperties->setText('CSV');
$importPluginProperties->setExtension('csv');
$importPluginProperties->setOptionsText(__('Options'));
// create the root group that will be the options field for
// $importPluginProperties
// this will be shown as "Format specific options"
$importSpecificOptions = new OptionsPropertyRootGroup('Format Specific Options');
$generalOptions = $this->getGeneralOptions();
if ($GLOBALS['plugin_param'] !== 'table') {
$leaf = new TextPropertyItem(
'new_tbl_name',
__(
'Name of the new table (optional):'
)
);
$generalOptions->addProperty($leaf);
if ($GLOBALS['plugin_param'] === 'server') {
$leaf = new TextPropertyItem(
'new_db_name',
__(
'Name of the new database (optional):'
)
);
$generalOptions->addProperty($leaf);
}
$leaf = new NumberPropertyItem(
'partial_import',
__(
'Import these many number of rows (optional):'
)
);
$generalOptions->addProperty($leaf);
$leaf = new BoolPropertyItem(
'col_names',
__(
'The first line of the file contains the table column names'
. ' <i>(if this is unchecked, the first line will become part'
. ' of the data)</i>'
)
);
$generalOptions->addProperty($leaf);
} else {
$leaf = new NumberPropertyItem(
'partial_import',
__(
'Import these many number of rows (optional):'
)
);
$generalOptions->addProperty($leaf);
$hint = new Message(
__(
'If the data in each row of the file is not'
. ' in the same order as in the database, list the corresponding'
. ' column names here. Column names must be separated by commas'
. ' and not enclosed in quotations.'
)
);
$leaf = new TextPropertyItem(
'columns',
__('Column names:') . ' ' . Generator::showHint($hint->getMessage())
);
$generalOptions->addProperty($leaf);
}
$leaf = new BoolPropertyItem(
'ignore',
__('Do not abort on INSERT error')
);
$generalOptions->addProperty($leaf);
// add the main group to the root group
$importSpecificOptions->addProperty($generalOptions);
// set the options for the import plugin property item
$importPluginProperties->setOptions($importSpecificOptions);
return $importPluginProperties;
}
/**
* Handles the whole import logic
*
* @param array $sql_data 2-element array with sql data
*/
public function doImport(?File $importHandle = null, array &$sql_data = []): void
{
global $error, $message, $dbi;
global $db, $table, $csv_terminated, $csv_enclosed, $csv_escaped,
$csv_new_line, $csv_columns, $errorUrl;
// $csv_replace and $csv_ignore should have been here,
// but we use directly from $_POST
global $timeout_passed, $finished;
$replacements = [
'\\n' => "\n",
'\\t' => "\t",
'\\r' => "\r",
];
$csv_terminated = strtr($csv_terminated, $replacements);
$csv_enclosed = strtr($csv_enclosed, $replacements);
$csv_escaped = strtr($csv_escaped, $replacements);
$csv_new_line = strtr($csv_new_line, $replacements);
[$error, $message] = $this->buildErrorsForParams(
$csv_terminated,
$csv_enclosed,
$csv_escaped,
$csv_new_line,
(string) $errorUrl
);
[$sql_template, $required_fields, $fields] = $this->getSqlTemplateAndRequiredFields($db, $table, $csv_columns);
// Defaults for parser
$i = 0;
$len = 0;
$lastlen = null;
$line = 1;
$lasti = -1;
$values = [];
$csv_finish = false;
$max_lines = 0; // defaults to 0 (get all the lines)
/**
* If we get a negative value, probably someone changed min value
* attribute in DOM or there is an integer overflow, whatever be
* the case, get all the lines.
*/
if (isset($_REQUEST['csv_partial_import']) && $_REQUEST['csv_partial_import'] > 0) {
$max_lines = $_REQUEST['csv_partial_import'];
}
$max_lines_constraint = $max_lines + 1;
// if the first row has to be counted as column names, include one more row in the max lines
if (isset($_REQUEST['csv_col_names'])) {
$max_lines_constraint++;
}
$tempRow = [];
$rows = [];
$col_names = [];
$tables = [];
$buffer = '';
$col_count = 0;
$max_cols = 0;
$csv_terminated_len = mb_strlen($csv_terminated);
while (! ($finished && $i >= $len) && ! $error && ! $timeout_passed) {
$data = $this->import->getNextChunk($importHandle);
if ($data === false) {
// subtract data we didn't handle yet and stop processing
$GLOBALS['offset'] -= strlen($buffer);
break;
}
if ($data !== true) {
// Append new data to buffer
$buffer .= $data;
unset($data);
// Force a trailing new line at EOF to prevent parsing problems
if ($finished && $buffer) {
$finalch = mb_substr($buffer, -1);
if ($csv_new_line === 'auto' && $finalch != "\r" && $finalch != "\n") {
$buffer .= "\n";
} elseif ($csv_new_line !== 'auto' && $finalch != $csv_new_line) {
$buffer .= $csv_new_line;
}
}
// Do not parse string when we're not at the end
// and don't have new line inside
if (
($csv_new_line === 'auto'
&& ! str_contains($buffer, "\r")
&& ! str_contains($buffer, "\n"))
|| ($csv_new_line !== 'auto'
&& ! str_contains($buffer, $csv_new_line))
) {
continue;
}
}
// Current length of our buffer
$len = mb_strlen($buffer);
// Currently parsed char
$ch = mb_substr($buffer, $i, 1);
if ($csv_terminated_len > 1 && $ch == $csv_terminated[0]) {
$ch = $this->readCsvTerminatedString($buffer, $ch, $i, $csv_terminated_len);
$i += $csv_terminated_len - 1;
}
while ($i < $len) {
// Deadlock protection
if ($lasti == $i && $lastlen == $len) {
$message = Message::error(
__('Invalid format of CSV input on line %d.')
);
$message->addParam($line);
$error = true;
break;
}
$lasti = $i;
$lastlen = $len;
// This can happen with auto EOL and \r at the end of buffer
if (! $csv_finish) {
// Grab empty field
if ($ch == $csv_terminated) {
if ($i == $len - 1) {
break;
}
$values[] = '';
$i++;
$ch = mb_substr($buffer, $i, 1);
if ($csv_terminated_len > 1 && $ch == $csv_terminated[0]) {
$ch = $this->readCsvTerminatedString($buffer, $ch, $i, $csv_terminated_len);
$i += $csv_terminated_len - 1;
}
continue;
}
// Grab one field
$fallbacki = $i;
if ($ch == $csv_enclosed) {
if ($i == $len - 1) {
break;
}
$need_end = true;
$i++;
$ch = mb_substr($buffer, $i, 1);
if ($csv_terminated_len > 1 && $ch == $csv_terminated[0]) {
$ch = $this->readCsvTerminatedString($buffer, $ch, $i, $csv_terminated_len);
$i += $csv_terminated_len - 1;
}
} else {
$need_end = false;
}
$fail = false;
$value = '';
while (
($need_end
&& ($ch != $csv_enclosed
|| $csv_enclosed == $csv_escaped))
|| (! $need_end
&& ! ($ch == $csv_terminated
|| $ch == $csv_new_line
|| ($csv_new_line === 'auto'
&& ($ch == "\r" || $ch == "\n"))))
) {
if ($ch == $csv_escaped) {
if ($i == $len - 1) {
$fail = true;
break;
}
$i++;
$ch = mb_substr($buffer, $i, 1);
if ($csv_terminated_len > 1 && $ch == $csv_terminated[0]) {
$ch = $this->readCsvTerminatedString($buffer, $ch, $i, $csv_terminated_len);
$i += $csv_terminated_len - 1;
}
if (
$csv_enclosed == $csv_escaped
&& ($ch == $csv_terminated
|| $ch == $csv_new_line
|| ($csv_new_line === 'auto'
&& ($ch == "\r" || $ch == "\n")))
) {
break;
}
}
$value .= $ch;
if ($i == $len - 1) {
if (! $finished) {
$fail = true;
}
break;
}
$i++;
$ch = mb_substr($buffer, $i, 1);
if ($csv_terminated_len <= 1 || $ch != $csv_terminated[0]) {
continue;
}
$ch = $this->readCsvTerminatedString($buffer, $ch, $i, $csv_terminated_len);
$i += $csv_terminated_len - 1;
}
// unquoted NULL string
if ($need_end === false && $value === 'NULL') {
$value = null;
}
if ($fail) {
$i = $fallbacki;
$ch = mb_substr($buffer, $i, 1);
if ($csv_terminated_len > 1 && $ch == $csv_terminated[0]) {
$i += $csv_terminated_len - 1;
}
break;
}
// Need to strip trailing enclosing char?
if ($need_end && $ch == $csv_enclosed) {
if ($finished && $i == $len - 1) {
$ch = null;
} elseif ($i == $len - 1) {
$i = $fallbacki;
$ch = mb_substr($buffer, $i, 1);
if ($csv_terminated_len > 1 && $ch == $csv_terminated[0]) {
$i += $csv_terminated_len - 1;
}
break;
} else {
$i++;
$ch = mb_substr($buffer, $i, 1);
if ($csv_terminated_len > 1 && $ch == $csv_terminated[0]) {
$ch = $this->readCsvTerminatedString($buffer, $ch, $i, $csv_terminated_len);
$i += $csv_terminated_len - 1;
}
}
}
// Are we at the end?
if (
$ch == $csv_new_line
|| ($csv_new_line === 'auto' && ($ch == "\r" || $ch == "\n"))
|| ($finished && $i == $len - 1)
) {
$csv_finish = true;
}
// Go to next char
if ($ch == $csv_terminated) {
if ($i == $len - 1) {
$i = $fallbacki;
$ch = mb_substr($buffer, $i, 1);
if ($csv_terminated_len > 1 && $ch == $csv_terminated[0]) {
$i += $csv_terminated_len - 1;
}
break;
}
$i++;
$ch = mb_substr($buffer, $i, 1);
if ($csv_terminated_len > 1 && $ch == $csv_terminated[0]) {
$ch = $this->readCsvTerminatedString($buffer, $ch, $i, $csv_terminated_len);
$i += $csv_terminated_len - 1;
}
}
// If everything went okay, store value
$values[] = $value;
}
// End of line
if (
! $csv_finish
&& $ch != $csv_new_line
&& ($csv_new_line !== 'auto' || ($ch != "\r" && $ch != "\n"))
) {
continue;
}
if ($csv_new_line === 'auto' && $ch == "\r") { // Handle "\r\n"
if ($i >= ($len - 2) && ! $finished) {
break; // We need more data to decide new line
}
if (mb_substr($buffer, $i + 1, 1) == "\n") {
$i++;
}
}
// We didn't parse value till the end of line, so there was
// empty one
if (! $csv_finish) {
$values[] = '';
}
if ($this->getAnalyze()) {
foreach ($values as $val) {
$tempRow[] = $val;
++$col_count;
}
if ($col_count > $max_cols) {
$max_cols = $col_count;
}
$col_count = 0;
$rows[] = $tempRow;
$tempRow = [];
} else {
// Do we have correct count of values?
if (count($values) != $required_fields) {
// Hack for excel
if ($values[count($values) - 1] !== ';') {
$message = Message::error(
__(
'Invalid column count in CSV input on line %d.'
)
);
$message->addParam($line);
$error = true;
break;
}
unset($values[count($values) - 1]);
}
$first = true;
$sql = $sql_template;
foreach ($values as $val) {
if (! $first) {
$sql .= ', ';
}
if ($val === null) {
$sql .= 'NULL';
} else {
$sql .= '\''
. $dbi->escapeString($val)
. '\'';
}
$first = false;
}
$sql .= ')';
if (isset($_POST['csv_replace'])) {
$sql .= ' ON DUPLICATE KEY UPDATE ';
foreach ($fields as $field) {
$fieldName = Util::backquote($field['Field']);
$sql .= $fieldName . ' = VALUES(' . $fieldName
. '), ';
}
$sql = rtrim($sql, ', ');
}
/**
* @todo maybe we could add original line to verbose
* SQL in comment
*/
$this->import->runQuery($sql, $sql, $sql_data);
}
$line++;
$csv_finish = false;
$values = [];
$buffer = mb_substr($buffer, $i + 1);
$len = mb_strlen($buffer);
$i = 0;
$lasti = -1;
$ch = mb_substr($buffer, 0, 1);
if ($max_lines > 0 && $line == $max_lines_constraint) {
$finished = 1;
break;
}
}
if ($max_lines > 0 && $line == $max_lines_constraint) {
$finished = 1;
break;
}
}
if ($this->getAnalyze()) {
/* Fill out all rows */
$num_rows = count($rows);
for ($i = 0; $i < $num_rows; ++$i) {
for ($j = count($rows[$i]); $j < $max_cols; ++$j) {
$rows[$i][] = 'NULL';
}
}
$col_names = $this->getColumnNames($col_names, $max_cols, $rows);
/* Remove the first row if it contains the column names */
if (isset($_REQUEST['csv_col_names'])) {
array_shift($rows);
}
$tbl_name = $this->getTableNameFromImport((string) $db);
$tables[] = [
$tbl_name,
$col_names,
$rows,
];
/* Obtain the best-fit MySQL types for each column */
$analyses = [];
$analyses[] = $this->import->analyzeTable($tables[0]);
/**
* string $db_name (no backquotes)
*
* array $table = array(table_name, array() column_names, array()() rows)
* array $tables = array of "$table"s
*
* array $analysis = array(array() column_types, array() column_sizes)
* array $analyses = array of "$analysis"s
*
* array $create = array of SQL strings
*
* array $options = an associative array of options
*/
/* Set database name to the currently selected one, if applicable,
* Otherwise, check if user provided the database name in the request,
* if not, set the default name
*/
if (isset($_REQUEST['csv_new_db_name']) && strlen($_REQUEST['csv_new_db_name']) > 0) {
$newDb = $_REQUEST['csv_new_db_name'];
} else {
$result = $dbi->fetchResult('SHOW DATABASES');
$newDb = 'CSV_DB ' . (count($result) + 1);
}
[$db_name, $options] = $this->getDbnameAndOptions($db, $newDb);
/* Non-applicable parameters */
$create = null;
/* Created and execute necessary SQL statements from data */
$this->import->buildSql($db_name, $tables, $analyses, $create, $options, $sql_data);
unset($tables, $analyses);
}
// Commit any possible data in buffers
$this->import->runQuery('', '', $sql_data);
if (count($values) == 0 || $error !== false) {
return;
}
$message = Message::error(
__('Invalid format of CSV input on line %d.')
);
$message->addParam($line);
$error = true;
}
private function buildErrorsForParams(
string $csvTerminated,
string $csvEnclosed,
string $csvEscaped,
string $csvNewLine,
string $errUrl
): array {
global $error, $message;
$param_error = false;
if (strlen($csvTerminated) === 0) {
$message = Message::error(
__('Invalid parameter for CSV import: %s')
);
$message->addParam(__('Columns terminated with'));
$error = true;
$param_error = true;
// The default dialog of MS Excel when generating a CSV produces a
// semi-colon-separated file with no chance of specifying the
// enclosing character. Thus, users who want to import this file
// tend to remove the enclosing character on the Import dialog.
// I could not find a test case where having no enclosing characters
// confuses this script.
// But the parser won't work correctly with strings so we allow just
// one character.
} elseif (mb_strlen($csvEnclosed) > 1) {
$message = Message::error(
__('Invalid parameter for CSV import: %s')
);
$message->addParam(__('Columns enclosed with'));
$error = true;
$param_error = true;
// I could not find a test case where having no escaping characters
// confuses this script.
// But the parser won't work correctly with strings so we allow just
// one character.
} elseif (mb_strlen($csvEscaped) > 1) {
$message = Message::error(
__('Invalid parameter for CSV import: %s')
);
$message->addParam(__('Columns escaped with'));
$error = true;
$param_error = true;
} elseif (mb_strlen($csvNewLine) != 1 && $csvNewLine !== 'auto') {
$message = Message::error(
__('Invalid parameter for CSV import: %s')
);
$message->addParam(__('Lines terminated with'));
$error = true;
$param_error = true;
}
// If there is an error in the parameters entered,
// indicate that immediately.
if ($param_error) {
Generator::mysqlDie(
$message->getMessage(),
'',
false,
$errUrl
);
}
return [$error, $message];
}
private function getTableNameFromImport(string $databaseName): string
{
global $import_file_name, $dbi;
$importFileName = basename($import_file_name, '.csv');
$importFileName = mb_strtolower($importFileName);
$importFileName = (string) preg_replace('/[^a-zA-Z0-9_]/', '_', $importFileName);
// get new table name, if user didn't provide one, set the default name
if (isset($_REQUEST['csv_new_tbl_name']) && strlen($_REQUEST['csv_new_tbl_name']) > 0) {
return $_REQUEST['csv_new_tbl_name'];
}
if (mb_strlen($databaseName)) {
$result = $dbi->fetchResult('SHOW TABLES');
// logic to get table name from filename
// if no table then use filename as table name
if (count($result) === 0) {
return $importFileName;
}
// check to see if {filename} as table exist
$nameArray = preg_grep('/' . $importFileName . '/isU', $result);
// if no use filename as table name
if ($nameArray === false || count($nameArray) === 0) {
return $importFileName;
}
// check if {filename}_ as table exist
$nameArray = preg_grep('/' . $importFileName . '_/isU', $result);
if ($nameArray === false) {
return $importFileName;
}
return $importFileName . '_' . (count($nameArray) + 1);
}
return $importFileName;
}
private function getColumnNames(array $columnNames, int $maxCols, array $rows): array
{
if (isset($_REQUEST['csv_col_names'])) {
$columnNames = array_splice($rows, 0, 1);
$columnNames = $columnNames[0];
// MySQL column names can't end with a space character.
foreach ($columnNames as $key => $col_name) {
$columnNames[$key] = rtrim($col_name);
}
}
if ((isset($columnNames) && count($columnNames) != $maxCols) || ! isset($columnNames)) {
// Fill out column names
for ($i = 0; $i < $maxCols; ++$i) {
$columnNames[] = 'COL ' . ($i + 1);
}
}
return $columnNames;
}
private function getSqlTemplateAndRequiredFields(
?string $db,
?string $table,
?string $csvColumns
): array {
global $dbi, $error, $message;
$requiredFields = 0;
$sqlTemplate = '';
$fields = [];
if (! $this->getAnalyze() && $db !== null && $table !== null) {
$sqlTemplate = 'INSERT';
if (isset($_POST['csv_ignore'])) {
$sqlTemplate .= ' IGNORE';
}
$sqlTemplate .= ' INTO ' . Util::backquote($table);
$tmp_fields = $dbi->getColumns($db, $table);
if (empty($csvColumns)) {
$fields = $tmp_fields;
} else {
$sqlTemplate .= ' (';
$fields = [];
$tmp = preg_split('/,( ?)/', $csvColumns);
if ($tmp === false) {
$tmp = [];
}
foreach ($tmp as $val) {
if (count($fields) > 0) {
$sqlTemplate .= ', ';
}
/* Trim also `, if user already included backquoted fields */
$val = trim($val, " \t\r\n\0\x0B`");
$found = false;
foreach ($tmp_fields as $field) {
if ($field['Field'] == $val) {
$found = true;
break;
}
}
if (! $found) {
$message = Message::error(
__(
'Invalid column (%s) specified! Ensure that columns'
. ' names are spelled correctly, separated by commas'
. ', and not enclosed in quotes.'
)
);
$message->addParam($val);
$error = true;
break;
}
if (isset($field)) {
$fields[] = $field;
}
$sqlTemplate .= Util::backquote($val);
}
$sqlTemplate .= ') ';
}
$requiredFields = count($fields);
$sqlTemplate .= ' VALUES (';
}
return [$sqlTemplate, $requiredFields, $fields];
}
/**
* Read the expected column_separated_with String of length
* $csv_terminated_len from the $buffer
* into variable $ch and return the read string $ch
*
* @param string $buffer The original string buffer read from
* csv file
* @param string $ch Partially read "column Separated with"
* string, also used to return after
* reading length equal $csv_terminated_len
* @param int $i Current read counter of buffer string
* @param int $csv_terminated_len The length of "column separated with"
* String
*
* @return string
*/
public function readCsvTerminatedString($buffer, $ch, $i, $csv_terminated_len)
{
for ($j = 0; $j < $csv_terminated_len - 1; $j++) {
$i++;
$ch .= mb_substr($buffer, $i, 1);
}
return $ch;
}
/* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */
/**
* Returns true if the table should be analyzed, false otherwise
*/
private function getAnalyze(): bool
{
return $this->analyze;
}
/**
* Sets to true if the table should be analyzed, false otherwise
*
* @param bool $analyze status
*/
private function setAnalyze($analyze): void
{
$this->analyze = $analyze;
}
}

View file

@ -1,211 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Import;
use PhpMyAdmin\File;
use PhpMyAdmin\Message;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyRootGroup;
use PhpMyAdmin\Properties\Options\Items\BoolPropertyItem;
use PhpMyAdmin\Properties\Options\Items\TextPropertyItem;
use PhpMyAdmin\Properties\Plugins\ImportPluginProperties;
use PhpMyAdmin\Util;
use function __;
use function count;
use function is_array;
use function preg_split;
use function strlen;
use function trim;
use const PHP_EOL;
/**
* CSV import plugin for phpMyAdmin using LOAD DATA
*/
class ImportLdi extends AbstractImportCsv
{
/**
* @psalm-return non-empty-lowercase-string
*/
public function getName(): string
{
return 'ldi';
}
protected function setProperties(): ImportPluginProperties
{
$importPluginProperties = new ImportPluginProperties();
$importPluginProperties->setText('CSV using LOAD DATA');
$importPluginProperties->setExtension('ldi');
if (! self::isAvailable()) {
return $importPluginProperties;
}
if ($GLOBALS['cfg']['Import']['ldi_local_option'] === 'auto') {
$this->setLdiLocalOptionConfig();
}
$importPluginProperties->setOptionsText(__('Options'));
// create the root group that will be the options field for
// $importPluginProperties
// this will be shown as "Format specific options"
$importSpecificOptions = new OptionsPropertyRootGroup('Format Specific Options');
$generalOptions = $this->getGeneralOptions();
$leaf = new TextPropertyItem(
'columns',
__('Column names: ')
);
$generalOptions->addProperty($leaf);
$leaf = new BoolPropertyItem(
'ignore',
__('Do not abort on INSERT error')
);
$generalOptions->addProperty($leaf);
$leaf = new BoolPropertyItem(
'local_option',
__('Use LOCAL keyword')
);
$generalOptions->addProperty($leaf);
// add the main group to the root group
$importSpecificOptions->addProperty($generalOptions);
// set the options for the import plugin property item
$importPluginProperties->setOptions($importSpecificOptions);
return $importPluginProperties;
}
/**
* Handles the whole import logic
*
* @param array $sql_data 2-element array with sql data
*/
public function doImport(?File $importHandle = null, array &$sql_data = []): void
{
global $finished, $import_file, $charset_conversion, $table, $dbi;
global $ldi_local_option, $ldi_replace, $ldi_ignore, $ldi_terminated,
$ldi_enclosed, $ldi_escaped, $ldi_new_line, $skip_queries, $ldi_columns;
$compression = '';
if ($importHandle !== null) {
$compression = $importHandle->getCompression();
}
if ($import_file === 'none' || $compression !== 'none' || $charset_conversion) {
// We handle only some kind of data!
$GLOBALS['message'] = Message::error(
__('This plugin does not support compressed imports!')
);
$GLOBALS['error'] = true;
return;
}
$sql = 'LOAD DATA';
if (isset($ldi_local_option)) {
$sql .= ' LOCAL';
}
$sql .= ' INFILE \'' . $dbi->escapeString($import_file)
. '\'';
if (isset($ldi_replace)) {
$sql .= ' REPLACE';
} elseif (isset($ldi_ignore)) {
$sql .= ' IGNORE';
}
$sql .= ' INTO TABLE ' . Util::backquote($table);
if (strlen((string) $ldi_terminated) > 0) {
$sql .= ' FIELDS TERMINATED BY \'' . $ldi_terminated . '\'';
}
if (strlen((string) $ldi_enclosed) > 0) {
$sql .= ' ENCLOSED BY \''
. $dbi->escapeString($ldi_enclosed) . '\'';
}
if (strlen((string) $ldi_escaped) > 0) {
$sql .= ' ESCAPED BY \''
. $dbi->escapeString($ldi_escaped) . '\'';
}
if (strlen((string) $ldi_new_line) > 0) {
if ($ldi_new_line === 'auto') {
$ldi_new_line = PHP_EOL == "\n"
? '\n'
: '\r\n';
}
$sql .= ' LINES TERMINATED BY \'' . $ldi_new_line . '\'';
}
if ($skip_queries > 0) {
$sql .= ' IGNORE ' . $skip_queries . ' LINES';
$skip_queries = 0;
}
if (strlen((string) $ldi_columns) > 0) {
$sql .= ' (';
$tmp = preg_split('/,( ?)/', $ldi_columns);
if (! is_array($tmp)) {
$tmp = [];
}
$cnt_tmp = count($tmp);
for ($i = 0; $i < $cnt_tmp; $i++) {
if ($i > 0) {
$sql .= ', ';
}
/* Trim also `, if user already included backquoted fields */
$sql .= Util::backquote(
trim($tmp[$i], " \t\r\n\0\x0B`")
);
}
$sql .= ')';
}
$this->import->runQuery($sql, $sql, $sql_data);
$this->import->runQuery('', '', $sql_data);
$finished = true;
}
public static function isAvailable(): bool
{
global $plugin_param;
// We need relations enabled and we work only on database.
return isset($plugin_param) && $plugin_param === 'table';
}
private function setLdiLocalOptionConfig(): void
{
global $dbi;
$GLOBALS['cfg']['Import']['ldi_local_option'] = false;
$result = $dbi->tryQuery('SELECT @@local_infile;');
if ($result === false || $result->numRows() <= 0) {
return;
}
$tmp = $result->fetchValue();
if ($tmp !== 'ON' && $tmp !== '1') {
return;
}
$GLOBALS['cfg']['Import']['ldi_local_option'] = true;
}
}

View file

@ -1,591 +0,0 @@
<?php
/**
* MediaWiki import plugin for phpMyAdmin
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Import;
use PhpMyAdmin\File;
use PhpMyAdmin\Message;
use PhpMyAdmin\Plugins\ImportPlugin;
use PhpMyAdmin\Properties\Plugins\ImportPluginProperties;
use function __;
use function count;
use function explode;
use function mb_strlen;
use function mb_strpos;
use function mb_substr;
use function preg_match;
use function str_contains;
use function str_replace;
use function strcmp;
use function strlen;
use function trim;
/**
* Handles the import for the MediaWiki format
*/
class ImportMediawiki extends ImportPlugin
{
/**
* Whether to analyze tables
*
* @var bool
*/
private $analyze;
/**
* @psalm-return non-empty-lowercase-string
*/
public function getName(): string
{
return 'mediawiki';
}
protected function setProperties(): ImportPluginProperties
{
$this->setAnalyze(false);
if ($GLOBALS['plugin_param'] !== 'table') {
$this->setAnalyze(true);
}
$importPluginProperties = new ImportPluginProperties();
$importPluginProperties->setText(__('MediaWiki Table'));
$importPluginProperties->setExtension('txt');
$importPluginProperties->setMimeType('text/plain');
$importPluginProperties->setOptionsText(__('Options'));
return $importPluginProperties;
}
/**
* Handles the whole import logic
*
* @param array $sql_data 2-element array with sql data
*/
public function doImport(?File $importHandle = null, array &$sql_data = []): void
{
global $error, $timeout_passed, $finished;
// Defaults for parser
// The buffer that will be used to store chunks read from the imported file
$buffer = '';
// Used as storage for the last part of the current chunk data
// Will be appended to the first line of the next chunk, if there is one
$last_chunk_line = '';
// Remembers whether the current buffer line is part of a comment
$inside_comment = false;
// Remembers whether the current buffer line is part of a data comment
$inside_data_comment = false;
// Remembers whether the current buffer line is part of a structure comment
$inside_structure_comment = false;
// MediaWiki only accepts "\n" as row terminator
$mediawiki_new_line = "\n";
// Initialize the name of the current table
$cur_table_name = '';
$cur_temp_table_headers = [];
$cur_temp_table = [];
$in_table_header = false;
while (! $finished && ! $error && ! $timeout_passed) {
$data = $this->import->getNextChunk($importHandle);
if ($data === false) {
// Subtract data we didn't handle yet and stop processing
$GLOBALS['offset'] -= mb_strlen($buffer);
break;
}
if ($data !== true) {
// Append new data to buffer
$buffer = $data;
unset($data);
// Don't parse string if we're not at the end
// and don't have a new line inside
if (! str_contains($buffer, $mediawiki_new_line)) {
continue;
}
}
// Because of reading chunk by chunk, the first line from the buffer
// contains only a portion of an actual line from the imported file.
// Therefore, we have to append it to the last line from the previous
// chunk. If we are at the first chunk, $last_chunk_line should be empty.
$buffer = $last_chunk_line . $buffer;
// Process the buffer line by line
$buffer_lines = explode($mediawiki_new_line, $buffer);
$full_buffer_lines_count = count($buffer_lines);
// If the reading is not finalized, the final line of the current chunk
// will not be complete
if (! $finished) {
$last_chunk_line = $buffer_lines[--$full_buffer_lines_count];
}
for ($line_nr = 0; $line_nr < $full_buffer_lines_count; ++$line_nr) {
$cur_buffer_line = trim($buffer_lines[$line_nr]);
// If the line is empty, go to the next one
if ($cur_buffer_line === '') {
continue;
}
$first_character = $cur_buffer_line[0];
$matches = [];
// Check beginning of comment
if (! strcmp(mb_substr($cur_buffer_line, 0, 4), '<!--')) {
$inside_comment = true;
continue;
}
if ($inside_comment) {
// Check end of comment
if (! strcmp(mb_substr($cur_buffer_line, 0, 4), '-->')) {
// Only data comments are closed. The structure comments
// will be closed when a data comment begins (in order to
// skip structure tables)
if ($inside_data_comment) {
$inside_data_comment = false;
}
// End comments that are not related to table structure
if (! $inside_structure_comment) {
$inside_comment = false;
}
} else {
// Check table name
$match_table_name = [];
if (preg_match('/^Table data for `(.*)`$/', $cur_buffer_line, $match_table_name)) {
$cur_table_name = $match_table_name[1];
$inside_data_comment = true;
$inside_structure_comment = $this->mngInsideStructComm($inside_structure_comment);
} elseif (preg_match('/^Table structure for `(.*)`$/', $cur_buffer_line, $match_table_name)) {
// The structure comments will be ignored
$inside_structure_comment = true;
}
}
continue;
}
if (preg_match('/^\{\|(.*)$/', $cur_buffer_line, $matches)) {
// Check start of table
// This will store all the column info on all rows from
// the current table read from the buffer
$cur_temp_table = [];
// Will be used as storage for the current row in the buffer
// Once all its columns are read, it will be added to
// $cur_temp_table and then it will be emptied
$cur_temp_line = [];
// Helps us differentiate the header columns
// from the normal columns
$in_table_header = false;
// End processing because the current line does not
// contain any column information
} elseif (
mb_substr($cur_buffer_line, 0, 2) === '|-'
|| mb_substr($cur_buffer_line, 0, 2) === '|+'
|| mb_substr($cur_buffer_line, 0, 2) === '|}'
) {
// Check begin row or end table
// Add current line to the values storage
if (! empty($cur_temp_line)) {
// If the current line contains header cells
// ( marked with '!' ),
// it will be marked as table header
if ($in_table_header) {
// Set the header columns
$cur_temp_table_headers = $cur_temp_line;
} else {
// Normal line, add it to the table
$cur_temp_table[] = $cur_temp_line;
}
}
// Empty the temporary buffer
$cur_temp_line = [];
// No more processing required at the end of the table
if (mb_substr($cur_buffer_line, 0, 2) === '|}') {
$current_table = [
$cur_table_name,
$cur_temp_table_headers,
$cur_temp_table,
];
// Import the current table data into the database
$this->importDataOneTable($current_table, $sql_data);
// Reset table name
$cur_table_name = '';
}
// What's after the row tag is now only attributes
} elseif (($first_character === '|') || ($first_character === '!')) {
// Check cell elements
// Header cells
if ($first_character === '!') {
// Mark as table header, but treat as normal row
$cur_buffer_line = str_replace('!!', '||', $cur_buffer_line);
// Will be used to set $cur_temp_line as table header
$in_table_header = true;
} else {
$in_table_header = false;
}
// Loop through each table cell
$cells = $this->explodeMarkup($cur_buffer_line);
foreach ($cells as $cell) {
$cell = $this->getCellData($cell);
// Delete the beginning of the column, if there is one
$cell = trim($cell);
$col_start_chars = [
'|',
'!',
];
foreach ($col_start_chars as $col_start_char) {
$cell = $this->getCellContent($cell, $col_start_char);
}
// Add the cell to the row
$cur_temp_line[] = $cell;
}
} else {
// If it's none of the above, then the current line has a bad
// format
$message = Message::error(
__('Invalid format of mediawiki input on line: <br>%s.')
);
$message->addParam($cur_buffer_line);
$error = true;
}
}
}
}
/**
* Imports data from a single table
*
* @param array $table containing all table info:
* <code> $table[0] - string
* containing table name
* $table[1] - array[] of
* table headers $table[2] -
* array[][] of table content
* rows </code>
* @param array $sql_data 2-element array with sql data
*
* @global bool $analyze whether to scan for column types
*/
private function importDataOneTable(array $table, array &$sql_data): void
{
$analyze = $this->getAnalyze();
if ($analyze) {
// Set the table name
$this->setTableName($table[0]);
// Set generic names for table headers if they don't exist
$this->setTableHeaders($table[1], $table[2][0]);
// Create the tables array to be used in Import::buildSql()
$tables = [];
$tables[] = [
$table[0],
$table[1],
$table[2],
];
// Obtain the best-fit MySQL types for each column
$analyses = [];
$analyses[] = $this->import->analyzeTable($tables[0]);
$this->executeImportTables($tables, $analyses, $sql_data);
}
// Commit any possible data in buffers
$this->import->runQuery('', '', $sql_data);
}
/**
* Sets the table name
*
* @param string $table_name reference to the name of the table
*/
private function setTableName(&$table_name): void
{
global $dbi;
if (! empty($table_name)) {
return;
}
$result = $dbi->fetchResult('SHOW TABLES');
// todo check if the name below already exists
$table_name = 'TABLE ' . (count($result) + 1);
}
/**
* Set generic names for table headers, if they don't exist
*
* @param array $table_headers reference to the array containing the headers
* of a table
* @param array $table_row array containing the first content row
*/
private function setTableHeaders(array &$table_headers, array $table_row): void
{
if (! empty($table_headers)) {
return;
}
// The first table row should contain the number of columns
// If they are not set, generic names will be given (COL 1, COL 2, etc)
$num_cols = count($table_row);
for ($i = 0; $i < $num_cols; ++$i) {
$table_headers[$i] = 'COL ' . ($i + 1);
}
}
/**
* Sets the database name and additional options and calls Import::buildSql()
* Used in PMA_importDataAllTables() and $this->importDataOneTable()
*
* @param array $tables structure:
* array(
* array(table_name, array() column_names, array()()
* rows)
* )
* @param array $analyses structure:
* $analyses = array(
* array(array() column_types, array() column_sizes)
* )
* @param array $sql_data 2-element array with sql data
*
* @global string $db name of the database to import in
*/
private function executeImportTables(array &$tables, array &$analyses, array &$sql_data): void
{
global $db;
// $db_name : The currently selected database name, if applicable
// No backquotes
// $options : An associative array of options
[$db_name, $options] = $this->getDbnameAndOptions($db, 'mediawiki_DB');
// Array of SQL strings
// Non-applicable parameters
$create = null;
// Create and execute necessary SQL statements from data
$this->import->buildSql($db_name, $tables, $analyses, $create, $options, $sql_data);
}
/**
* Replaces all instances of the '||' separator between delimiters
* in a given string
*
* @param string $replace the string to be replaced with
* @param string $subject the text to be replaced
*
* @return string with replacements
*/
private function delimiterReplace($replace, $subject)
{
// String that will be returned
$cleaned = '';
// Possible states of current character
$inside_tag = false;
$inside_attribute = false;
// Attributes can be declared with either " or '
$start_attribute_character = false;
// The full separator is "||";
// This remembers if the previous character was '|'
$partial_separator = false;
// Parse text char by char
for ($i = 0, $iMax = strlen($subject); $i < $iMax; $i++) {
$cur_char = $subject[$i];
// Check for separators
if ($cur_char === '|') {
// If we're not inside a tag, then this is part of a real separator,
// so we append it to the current segment
if (! $inside_attribute) {
$cleaned .= $cur_char;
if ($partial_separator) {
$inside_tag = false;
$inside_attribute = false;
}
} elseif ($partial_separator) {
// If we are inside a tag, we replace the current char with
// the placeholder and append that to the current segment
$cleaned .= $replace;
}
// If the previous character was also '|', then this ends a
// full separator. If not, this may be the beginning of one
$partial_separator = ! $partial_separator;
} else {
// If we're inside a tag attribute and the current character is
// not '|', but the previous one was, it means that the single '|'
// was not appended, so we append it now
if ($partial_separator && $inside_attribute) {
$cleaned .= '|';
}
// If the char is different from "|", no separator can be formed
$partial_separator = false;
// any other character should be appended to the current segment
$cleaned .= $cur_char;
if ($cur_char === '<' && ! $inside_attribute) {
// start of a tag
$inside_tag = true;
} elseif ($cur_char === '>' && ! $inside_attribute) {
// end of a tag
$inside_tag = false;
} elseif (($cur_char === '"' || $cur_char == "'") && $inside_tag) {
// start or end of an attribute
if (! $inside_attribute) {
$inside_attribute = true;
// remember the attribute`s declaration character (" or ')
$start_attribute_character = $cur_char;
} else {
if ($cur_char == $start_attribute_character) {
$inside_attribute = false;
// unset attribute declaration character
$start_attribute_character = false;
}
}
}
}
}
return $cleaned;
}
/**
* Separates a string into items, similarly to explode
* Uses the '||' separator (which is standard in the mediawiki format)
* and ignores any instances of it inside markup tags
* Used in parsing buffer lines containing data cells
*
* @param string $text text to be split
*
* @return array
*/
private function explodeMarkup($text)
{
$separator = '||';
$placeholder = "\x00";
// Remove placeholder instances
$text = str_replace($placeholder, '', $text);
// Replace instances of the separator inside HTML-like
// tags with the placeholder
$cleaned = $this->delimiterReplace($placeholder, $text);
// Explode, then put the replaced separators back in
$items = explode($separator, $cleaned);
foreach ($items as $i => $str) {
$items[$i] = str_replace($placeholder, $separator, $str);
}
return $items;
}
/* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */
/**
* Returns true if the table should be analyzed, false otherwise
*/
private function getAnalyze(): bool
{
return $this->analyze;
}
/**
* Sets to true if the table should be analyzed, false otherwise
*
* @param bool $analyze status
*/
private function setAnalyze($analyze): void
{
$this->analyze = $analyze;
}
/**
* Get cell
*
* @param string $cell Cell
*
* @return mixed
*/
private function getCellData($cell)
{
// A cell could contain both parameters and data
$cell_data = explode('|', $cell, 2);
// A '|' inside an invalid link should not
// be mistaken as delimiting cell parameters
if (! str_contains($cell_data[0], '[[')) {
return $cell;
}
if (count($cell_data) === 1) {
return $cell_data[0];
}
return $cell_data[1];
}
/**
* Manage $inside_structure_comment
*
* @param bool $inside_structure_comment Value to test
*/
private function mngInsideStructComm($inside_structure_comment): bool
{
// End ignoring structure rows
if ($inside_structure_comment) {
$inside_structure_comment = false;
}
return $inside_structure_comment;
}
/**
* Get cell content
*
* @param string $cell Cell
* @param string $col_start_char Start char
*
* @return string
*/
private function getCellContent($cell, $col_start_char)
{
if (mb_strpos($cell, $col_start_char) === 0) {
$cell = trim(mb_substr($cell, 1));
}
return $cell;
}
}

View file

@ -1,467 +0,0 @@
<?php
/**
* OpenDocument Spreadsheet import plugin for phpMyAdmin
*
* @todo Pretty much everything
* @todo Importing of accented characters seems to fail
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Import;
use PhpMyAdmin\File;
use PhpMyAdmin\Import;
use PhpMyAdmin\Message;
use PhpMyAdmin\Plugins\ImportPlugin;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyMainGroup;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyRootGroup;
use PhpMyAdmin\Properties\Options\Items\BoolPropertyItem;
use PhpMyAdmin\Properties\Plugins\ImportPluginProperties;
use SimpleXMLElement;
use function __;
use function count;
use function implode;
use function libxml_disable_entity_loader;
use function rtrim;
use function simplexml_load_string;
use function strcmp;
use function strlen;
use const LIBXML_COMPACT;
use const PHP_VERSION_ID;
/**
* Handles the import for the ODS format
*/
class ImportOds extends ImportPlugin
{
/**
* @psalm-return non-empty-lowercase-string
*/
public function getName(): string
{
return 'ods';
}
protected function setProperties(): ImportPluginProperties
{
$importPluginProperties = new ImportPluginProperties();
$importPluginProperties->setText('OpenDocument Spreadsheet');
$importPluginProperties->setExtension('ods');
$importPluginProperties->setOptionsText(__('Options'));
// create the root group that will be the options field for
// $importPluginProperties
// this will be shown as "Format specific options"
$importSpecificOptions = new OptionsPropertyRootGroup('Format Specific Options');
// general options main group
$generalOptions = new OptionsPropertyMainGroup('general_opts');
// create primary items and add them to the group
$leaf = new BoolPropertyItem(
'col_names',
__(
'The first line of the file contains the table column names'
. ' <i>(if this is unchecked, the first line will become part'
. ' of the data)</i>'
)
);
$generalOptions->addProperty($leaf);
$leaf = new BoolPropertyItem(
'empty_rows',
__('Do not import empty rows')
);
$generalOptions->addProperty($leaf);
$leaf = new BoolPropertyItem(
'recognize_percentages',
__(
'Import percentages as proper decimals <i>(ex. 12.00% to .12)</i>'
)
);
$generalOptions->addProperty($leaf);
$leaf = new BoolPropertyItem(
'recognize_currency',
__('Import currencies <i>(ex. $5.00 to 5.00)</i>')
);
$generalOptions->addProperty($leaf);
// add the main group to the root group
$importSpecificOptions->addProperty($generalOptions);
// set the options for the import plugin property item
$importPluginProperties->setOptions($importSpecificOptions);
return $importPluginProperties;
}
/**
* Handles the whole import logic
*
* @param array $sql_data 2-element array with sql data
*/
public function doImport(?File $importHandle = null, array &$sql_data = []): void
{
global $db, $error, $timeout_passed, $finished;
$buffer = '';
/**
* Read in the file via Import::getNextChunk so that
* it can process compressed files
*/
while (! $finished && ! $error && ! $timeout_passed) {
$data = $this->import->getNextChunk($importHandle);
if ($data === false) {
/* subtract data we didn't handle yet and stop processing */
$GLOBALS['offset'] -= strlen($buffer);
break;
}
if ($data === true) {
continue;
}
/* Append new data to buffer */
$buffer .= $data;
}
/**
* Disable loading of external XML entities for PHP versions below 8.0.
*/
if (PHP_VERSION_ID < 80000) {
// phpcs:ignore Generic.PHP.DeprecatedFunctions.Deprecated
libxml_disable_entity_loader();
}
/**
* Load the XML string
*
* The option LIBXML_COMPACT is specified because it can
* result in increased performance without the need to
* alter the code in any way. It's basically a freebee.
*/
$xml = @simplexml_load_string($buffer, SimpleXMLElement::class, LIBXML_COMPACT);
unset($buffer);
if ($xml === false) {
$sheets = [];
$GLOBALS['message'] = Message::error(
__(
'The XML file specified was either malformed or incomplete. Please correct the issue and try again.'
)
);
$GLOBALS['error'] = true;
} else {
/** @var SimpleXMLElement $root */
$root = $xml->children('office', true)->{'body'}->{'spreadsheet'};
if (empty($root)) {
$sheets = [];
$GLOBALS['message'] = Message::error(
__('Could not parse OpenDocument Spreadsheet!')
);
$GLOBALS['error'] = true;
} else {
$sheets = $root->children('table', true);
}
}
[$tables, $rows] = $this->iterateOverTables($sheets);
/**
* Bring accumulated rows into the corresponding table
*/
$num_tables = count($tables);
for ($i = 0; $i < $num_tables; ++$i) {
$num_rows = count($rows);
for ($j = 0; $j < $num_rows; ++$j) {
if (strcmp($tables[$i][Import::TBL_NAME], $rows[$j][Import::TBL_NAME])) {
continue;
}
if (! isset($tables[$i][Import::COL_NAMES])) {
$tables[$i][] = $rows[$j][Import::COL_NAMES];
}
$tables[$i][Import::ROWS] = $rows[$j][Import::ROWS];
}
}
/* No longer needed */
unset($rows);
/* Obtain the best-fit MySQL types for each column */
$analyses = [];
$len = count($tables);
for ($i = 0; $i < $len; ++$i) {
$analyses[] = $this->import->analyzeTable($tables[$i]);
}
/**
* string $db_name (no backquotes)
*
* array $table = array(table_name, array() column_names, array()() rows)
* array $tables = array of "$table"s
*
* array $analysis = array(array() column_types, array() column_sizes)
* array $analyses = array of "$analysis"s
*
* array $create = array of SQL strings
*
* array $options = an associative array of options
*/
/* Set database name to the currently selected one, if applicable */
[$db_name, $options] = $this->getDbnameAndOptions($db, 'ODS_DB');
/* Non-applicable parameters */
$create = null;
/* Created and execute necessary SQL statements from data */
$this->import->buildSql($db_name, $tables, $analyses, $create, $options, $sql_data);
unset($tables, $analyses);
/* Commit any possible data in buffers */
$this->import->runQuery('', '', $sql_data);
}
/**
* Get value
*
* @param SimpleXMLElement $cell_attrs Cell attributes
* @param SimpleXMLElement $text Texts
*
* @return float|string
*/
protected function getValue($cell_attrs, $text)
{
if (
isset($_REQUEST['ods_recognize_percentages'])
&& $_REQUEST['ods_recognize_percentages']
&& ! strcmp('percentage', (string) $cell_attrs['value-type'])
) {
return (float) $cell_attrs['value'];
}
if (
isset($_REQUEST['ods_recognize_currency'])
&& $_REQUEST['ods_recognize_currency']
&& ! strcmp('currency', (string) $cell_attrs['value-type'])
) {
return (float) $cell_attrs['value'];
}
/* We need to concatenate all paragraphs */
$values = [];
foreach ($text as $paragraph) {
// Maybe a text node has the content ? (email, url, ...)
// Example: <text:a ... xlink:href="mailto:contact@example.org">test@example.fr</text:a>
$paragraphValue = $paragraph->__toString();
if ($paragraphValue === '' && isset($paragraph->{'a'})) {
$values[] = $paragraph->{'a'}->__toString();
continue;
}
$values[] = $paragraphValue;
}
return implode("\n", $values);
}
private function iterateOverColumns(
SimpleXMLElement $row,
bool $col_names_in_first_row,
array $tempRow,
array $col_names,
int $col_count
): array {
$cellCount = $row->count();
$a = 0;
foreach ($row as $cell) {
$a++;
$text = $cell->children('text', true);
$cell_attrs = $cell->attributes('office', true);
if ($text->count() != 0) {
$attr = $cell->attributes('table', true);
$num_repeat = (int) $attr['number-columns-repeated'];
$num_iterations = $num_repeat ?: 1;
for ($k = 0; $k < $num_iterations; $k++) {
$value = $this->getValue($cell_attrs, $text);
if (! $col_names_in_first_row) {
$tempRow[] = $value;
} else {
// MySQL column names can't end with a space
// character.
$col_names[] = rtrim((string) $value);
}
++$col_count;
}
continue;
}
// skip empty repeats in the last row
if ($a == $cellCount) {
continue;
}
$attr = $cell->attributes('table', true);
$num_null = (int) $attr['number-columns-repeated'];
if ($num_null) {
if (! $col_names_in_first_row) {
for ($i = 0; $i < $num_null; ++$i) {
$tempRow[] = 'NULL';
++$col_count;
}
} else {
for ($i = 0; $i < $num_null; ++$i) {
$col_names[] = $this->import->getColumnAlphaName($col_count + 1);
++$col_count;
}
}
} else {
if (! $col_names_in_first_row) {
$tempRow[] = 'NULL';
} else {
$col_names[] = $this->import->getColumnAlphaName($col_count + 1);
}
++$col_count;
}
}
return [$tempRow, $col_names, $col_count];
}
private function iterateOverRows(
SimpleXMLElement $sheet,
bool $col_names_in_first_row,
array $tempRow,
array $col_names,
int $col_count,
int $max_cols,
array $tempRows
): array {
foreach ($sheet as $row) {
$type = $row->getName();
if (strcmp('table-row', $type)) {
continue;
}
[$tempRow, $col_names, $col_count] = $this->iterateOverColumns(
$row,
$col_names_in_first_row,
$tempRow,
$col_names,
$col_count
);
/* Find the widest row */
if ($col_count > $max_cols) {
$max_cols = $col_count;
}
/* Don't include a row that is full of NULL values */
if (! $col_names_in_first_row) {
if ($_REQUEST['ods_empty_rows'] ?? false) {
foreach ($tempRow as $cell) {
if (strcmp('NULL', (string) $cell)) {
$tempRows[] = $tempRow;
break;
}
}
} else {
$tempRows[] = $tempRow;
}
}
$col_count = 0;
$col_names_in_first_row = false;
$tempRow = [];
}
return [$tempRow, $col_names, $max_cols, $tempRows];
}
/**
* @param array|SimpleXMLElement $sheets Sheets of the spreadsheet.
*
* @return array|array[]
*/
private function iterateOverTables($sheets): array
{
$tables = [];
$max_cols = 0;
$col_count = 0;
$col_names = [];
$tempRow = [];
$tempRows = [];
$rows = [];
/** @var SimpleXMLElement $sheet */
foreach ($sheets as $sheet) {
$col_names_in_first_row = isset($_REQUEST['ods_col_names']);
[$tempRow, $col_names, $max_cols, $tempRows] = $this->iterateOverRows(
$sheet,
$col_names_in_first_row,
$tempRow,
$col_names,
$col_count,
$max_cols,
$tempRows
);
/* Skip over empty sheets */
if (count($tempRows) == 0 || count($tempRows[0]) === 0) {
$col_names = [];
$tempRow = [];
$tempRows = [];
continue;
}
/**
* Fill out each row as necessary to make
* every one exactly as wide as the widest
* row. This included column names.
*/
/* Fill out column names */
for ($i = count($col_names); $i < $max_cols; ++$i) {
$col_names[] = $this->import->getColumnAlphaName($i + 1);
}
/* Fill out all rows */
$num_rows = count($tempRows);
for ($i = 0; $i < $num_rows; ++$i) {
for ($j = count($tempRows[$i]); $j < $max_cols; ++$j) {
$tempRows[$i][] = 'NULL';
}
}
/* Store the table name so we know where to place the row set */
$tbl_attr = $sheet->attributes('table', true);
$tables[] = [(string) $tbl_attr['name']];
/* Store the current sheet in the accumulator */
$rows[] = [
(string) $tbl_attr['name'],
$col_names,
$tempRows,
];
$tempRows = [];
$col_names = [];
$max_cols = 0;
}
return [$tables, $rows];
}
}

View file

@ -1,336 +0,0 @@
<?php
/**
* ESRI Shape file import plugin for phpMyAdmin
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Import;
use PhpMyAdmin\File;
use PhpMyAdmin\Gis\GisFactory;
use PhpMyAdmin\Gis\GisMultiLineString;
use PhpMyAdmin\Gis\GisMultiPoint;
use PhpMyAdmin\Gis\GisPoint;
use PhpMyAdmin\Gis\GisPolygon;
use PhpMyAdmin\Import;
use PhpMyAdmin\Message;
use PhpMyAdmin\Plugins\ImportPlugin;
use PhpMyAdmin\Properties\Plugins\ImportPluginProperties;
use PhpMyAdmin\Sanitize;
use PhpMyAdmin\ZipExtension;
use ZipArchive;
use function __;
use function count;
use function extension_loaded;
use function file_exists;
use function file_put_contents;
use function mb_substr;
use function method_exists;
use function pathinfo;
use function strcmp;
use function strlen;
use function substr;
use function trim;
use function unlink;
use const LOCK_EX;
/**
* Handles the import for ESRI Shape files
*/
class ImportShp extends ImportPlugin
{
/** @var ZipExtension|null */
private $zipExtension = null;
protected function init(): void
{
if (! extension_loaded('zip')) {
return;
}
$this->zipExtension = new ZipExtension(new ZipArchive());
}
/**
* @psalm-return non-empty-lowercase-string
*/
public function getName(): string
{
return 'shp';
}
protected function setProperties(): ImportPluginProperties
{
$importPluginProperties = new ImportPluginProperties();
$importPluginProperties->setText(__('ESRI Shape File'));
$importPluginProperties->setExtension('shp');
$importPluginProperties->setOptionsText(__('Options'));
return $importPluginProperties;
}
/**
* Handles the whole import logic
*
* @param array $sql_data 2-element array with sql data
*/
public function doImport(?File $importHandle = null, array &$sql_data = []): void
{
global $db, $error, $finished, $import_file, $local_import_file, $message, $dbi;
$GLOBALS['finished'] = false;
if ($importHandle === null || $this->zipExtension === null) {
return;
}
/** @see ImportShp::readFromBuffer() */
$GLOBALS['importHandle'] = $importHandle;
$compression = $importHandle->getCompression();
$shp = new ShapeFileImport(1);
// If the zip archive has more than one file,
// get the correct content to the buffer from .shp file.
if ($compression === 'application/zip' && $this->zipExtension->getNumberOfFiles($import_file) > 1) {
if ($importHandle->openZip('/^.*\.shp$/i') === false) {
$message = Message::error(
__('There was an error importing the ESRI shape file: "%s".')
);
$message->addParam($importHandle->getError());
return;
}
}
$temp_dbf_file = false;
// We need dbase extension to handle .dbf file
if (extension_loaded('dbase')) {
$temp = $GLOBALS['config']->getTempDir('shp');
// If we can extract the zip archive to 'TempDir'
// and use the files in it for import
if ($compression === 'application/zip' && $temp !== null) {
$dbf_file_name = $this->zipExtension->findFile($import_file, '/^.*\.dbf$/i');
// If the corresponding .dbf file is in the zip archive
if ($dbf_file_name) {
// Extract the .dbf file and point to it.
$extracted = $this->zipExtension->extract($import_file, $dbf_file_name);
if ($extracted !== false) {
// remove filename extension, e.g.
// dresden_osm.shp/gis.osm_transport_a_v06.dbf
// to
// dresden_osm.shp/gis.osm_transport_a_v06
$path_parts = pathinfo($dbf_file_name);
$dbf_file_name = $path_parts['dirname'] . '/' . $path_parts['filename'];
// sanitize filename
$dbf_file_name = Sanitize::sanitizeFilename($dbf_file_name, true);
// concat correct filename and extension
$dbf_file_path = $temp . '/' . $dbf_file_name . '.dbf';
if (file_put_contents($dbf_file_path, $extracted, LOCK_EX) !== false) {
$temp_dbf_file = true;
// Replace the .dbf with .*, as required by the bsShapeFiles library.
$shp->fileName = substr($dbf_file_path, 0, -4) . '.*';
}
}
}
} elseif (! empty($local_import_file) && ! empty($GLOBALS['cfg']['UploadDir']) && $compression === 'none') {
// If file is in UploadDir, use .dbf file in the same UploadDir
// to load extra data.
// Replace the .shp with .*,
// so the bsShapeFiles library correctly locates .dbf file.
$shp->fileName = mb_substr($import_file, 0, -4) . '.*';
}
}
// It should load data before file being deleted
$shp->loadFromFile('');
// Delete the .dbf file extracted to 'TempDir'
if ($temp_dbf_file && isset($dbf_file_path) && @file_exists($dbf_file_path)) {
unlink($dbf_file_path);
}
if ($shp->lastError != '') {
$error = true;
$message = Message::error(
__('There was an error importing the ESRI shape file: "%s".')
);
$message->addParam($shp->lastError);
return;
}
switch ($shp->shapeType) {
// ESRI Null Shape
case 0:
break;
// ESRI Point
case 1:
$gis_type = 'point';
break;
// ESRI PolyLine
case 3:
$gis_type = 'multilinestring';
break;
// ESRI Polygon
case 5:
$gis_type = 'multipolygon';
break;
// ESRI MultiPoint
case 8:
$gis_type = 'multipoint';
break;
default:
$error = true;
$message = Message::error(
__('MySQL Spatial Extension does not support ESRI type "%s".')
);
$message->addParam($shp->getShapeName());
return;
}
if (isset($gis_type)) {
/** @var GisMultiLineString|GisMultiPoint|GisPoint|GisPolygon $gis_obj */
$gis_obj = GisFactory::factory($gis_type);
} else {
$gis_obj = null;
}
$num_rows = count($shp->records);
// If .dbf file is loaded, the number of extra data columns
$num_data_cols = $shp->getDBFHeader() !== null ? count($shp->getDBFHeader()) : 0;
$rows = [];
$col_names = [];
if ($num_rows != 0) {
foreach ($shp->records as $record) {
$tempRow = [];
if ($gis_obj == null || ! method_exists($gis_obj, 'getShape')) {
$tempRow[] = null;
} else {
$tempRow[] = "GeomFromText('"
. $gis_obj->getShape($record->shpData) . "')";
}
if ($shp->getDBFHeader() !== null) {
foreach ($shp->getDBFHeader() as $c) {
$cell = trim((string) $record->dbfData[$c[0]]);
if (! strcmp($cell, '')) {
$cell = 'NULL';
}
$tempRow[] = $cell;
}
}
$rows[] = $tempRow;
}
}
if (count($rows) === 0) {
$error = true;
$message = Message::error(
__('The imported file does not contain any data!')
);
return;
}
// Column names for spatial column and the rest of the columns,
// if they are available
$col_names[] = 'SPATIAL';
$dbfHeader = $shp->getDBFHeader();
for ($n = 0; $n < $num_data_cols; $n++) {
if ($dbfHeader === null) {
continue;
}
$col_names[] = $dbfHeader[$n][0];
}
// Set table name based on the number of tables
if (strlen((string) $db) > 0) {
$result = $dbi->fetchResult('SHOW TABLES');
$table_name = 'TABLE ' . (count($result) + 1);
} else {
$table_name = 'TBL_NAME';
}
$tables = [
[
$table_name,
$col_names,
$rows,
],
];
// Use data from shape file to chose best-fit MySQL types for each column
$analyses = [];
$analyses[] = $this->import->analyzeTable($tables[0]);
$table_no = 0;
$spatial_col = 0;
$analyses[$table_no][Import::TYPES][$spatial_col] = Import::GEOMETRY;
$analyses[$table_no][Import::FORMATTEDSQL][$spatial_col] = true;
// Set database name to the currently selected one, if applicable
if (strlen((string) $db) > 0) {
$db_name = $db;
$options = ['create_db' => false];
} else {
$db_name = 'SHP_DB';
$options = null;
}
// Created and execute necessary SQL statements from data
$null_param = null;
$this->import->buildSql($db_name, $tables, $analyses, $null_param, $options, $sql_data);
unset($tables, $analyses);
$finished = true;
$error = false;
// Commit any possible data in buffers
$this->import->runQuery('', '', $sql_data);
}
/**
* Returns specified number of bytes from the buffer.
* Buffer automatically fetches next chunk of data when the buffer
* falls short.
* Sets $eof when $GLOBALS['finished'] is set and the buffer falls short.
*
* @param int $length number of bytes
*
* @return string
*/
public static function readFromBuffer($length)
{
global $buffer, $eof, $importHandle;
$import = new Import();
if (strlen((string) $buffer) < $length) {
if ($GLOBALS['finished']) {
$eof = true;
} else {
$buffer .= $import->getNextChunk($importHandle);
}
}
$result = substr($buffer, 0, $length);
$buffer = substr($buffer, $length);
return $result;
}
}

View file

@ -1,193 +0,0 @@
<?php
/**
* SQL import plugin for phpMyAdmin
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Import;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\File;
use PhpMyAdmin\Plugins\ImportPlugin;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyMainGroup;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyRootGroup;
use PhpMyAdmin\Properties\Options\Items\BoolPropertyItem;
use PhpMyAdmin\Properties\Options\Items\SelectPropertyItem;
use PhpMyAdmin\Properties\Plugins\ImportPluginProperties;
use PhpMyAdmin\SqlParser\Utils\BufferedQuery;
use function __;
use function count;
use function implode;
use function mb_strlen;
use function preg_replace;
/**
* Handles the import for the SQL format
*/
class ImportSql extends ImportPlugin
{
/**
* @psalm-return non-empty-lowercase-string
*/
public function getName(): string
{
return 'sql';
}
protected function setProperties(): ImportPluginProperties
{
global $dbi;
$importPluginProperties = new ImportPluginProperties();
$importPluginProperties->setText('SQL');
$importPluginProperties->setExtension('sql');
$importPluginProperties->setOptionsText(__('Options'));
$compats = $dbi->getCompatibilities();
if (count($compats) > 0) {
$values = [];
foreach ($compats as $val) {
$values[$val] = $val;
}
// create the root group that will be the options field for
// $importPluginProperties
// this will be shown as "Format specific options"
$importSpecificOptions = new OptionsPropertyRootGroup('Format Specific Options');
// general options main group
$generalOptions = new OptionsPropertyMainGroup('general_opts');
// create primary items and add them to the group
$leaf = new SelectPropertyItem(
'compatibility',
__('SQL compatibility mode:')
);
$leaf->setValues($values);
$leaf->setDoc(
[
'manual_MySQL_Database_Administration',
'Server_SQL_mode',
]
);
$generalOptions->addProperty($leaf);
$leaf = new BoolPropertyItem(
'no_auto_value_on_zero',
__('Do not use <code>AUTO_INCREMENT</code> for zero values')
);
$leaf->setDoc(
[
'manual_MySQL_Database_Administration',
'Server_SQL_mode',
'sqlmode_no_auto_value_on_zero',
]
);
$generalOptions->addProperty($leaf);
// add the main group to the root group
$importSpecificOptions->addProperty($generalOptions);
// set the options for the import plugin property item
$importPluginProperties->setOptions($importSpecificOptions);
}
return $importPluginProperties;
}
/**
* Handles the whole import logic
*
* @param array $sql_data 2-element array with sql data
*/
public function doImport(?File $importHandle = null, array &$sql_data = []): void
{
global $error, $timeout_passed, $dbi;
// Handle compatibility options.
$this->setSQLMode($dbi, $_REQUEST);
$bq = new BufferedQuery();
if (isset($_POST['sql_delimiter'])) {
$bq->setDelimiter($_POST['sql_delimiter']);
}
/**
* Will be set in Import::getNextChunk().
*
* @global bool $GLOBALS ['finished']
*/
$GLOBALS['finished'] = false;
while (! $error && (! $timeout_passed)) {
// Getting the first statement, the remaining data and the last
// delimiter.
$statement = $bq->extract();
// If there is no full statement, we are looking for more data.
if (empty($statement)) {
// Importing new data.
$newData = $this->import->getNextChunk($importHandle);
// Subtract data we didn't handle yet and stop processing.
if ($newData === false) {
$GLOBALS['offset'] -= mb_strlen($bq->query);
break;
}
// Checking if the input buffer has finished.
if ($newData === true) {
$GLOBALS['finished'] = true;
break;
}
// Convert CR (but not CRLF) to LF otherwise all queries may
// not get executed on some platforms.
$bq->query .= preg_replace("/\r($|[^\n])/", "\n$1", $newData);
continue;
}
// Executing the query.
$this->import->runQuery($statement, $statement, $sql_data);
}
// Extracting remaining statements.
while (! $error && ! $timeout_passed && ! empty($bq->query)) {
$statement = $bq->extract(true);
if (empty($statement)) {
continue;
}
$this->import->runQuery($statement, $statement, $sql_data);
}
// Finishing.
$this->import->runQuery('', '', $sql_data);
}
/**
* Handle compatibility options
*
* @param DatabaseInterface $dbi Database interface
* @param array $request Request array
*/
private function setSQLMode($dbi, array $request): void
{
$sql_modes = [];
if (isset($request['sql_compatibility']) && $request['sql_compatibility'] !== 'NONE') {
$sql_modes[] = $request['sql_compatibility'];
}
if (isset($request['sql_no_auto_value_on_zero'])) {
$sql_modes[] = 'NO_AUTO_VALUE_ON_ZERO';
}
if (count($sql_modes) <= 0) {
return;
}
$dbi->tryQuery(
'SET SQL_MODE="' . implode(',', $sql_modes) . '"'
);
}
}

View file

@ -1,361 +0,0 @@
<?php
/**
* XML import plugin for phpMyAdmin
*
* @todo Improve efficiency
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Import;
use PhpMyAdmin\File;
use PhpMyAdmin\Import;
use PhpMyAdmin\Message;
use PhpMyAdmin\Plugins\ImportPlugin;
use PhpMyAdmin\Properties\Plugins\ImportPluginProperties;
use PhpMyAdmin\Util;
use SimpleXMLElement;
use function __;
use function count;
use function in_array;
use function libxml_disable_entity_loader;
use function simplexml_load_string;
use function str_replace;
use function strcmp;
use function strlen;
use const LIBXML_COMPACT;
use const PHP_VERSION_ID;
/**
* Handles the import for the XML format
*/
class ImportXml extends ImportPlugin
{
/**
* @psalm-return non-empty-lowercase-string
*/
public function getName(): string
{
return 'xml';
}
protected function setProperties(): ImportPluginProperties
{
$importPluginProperties = new ImportPluginProperties();
$importPluginProperties->setText(__('XML'));
$importPluginProperties->setExtension('xml');
$importPluginProperties->setMimeType('text/xml');
$importPluginProperties->setOptionsText(__('Options'));
return $importPluginProperties;
}
/**
* Handles the whole import logic
*
* @param array $sql_data 2-element array with sql data
*/
public function doImport(?File $importHandle = null, array &$sql_data = []): void
{
global $error, $timeout_passed, $finished, $db;
$buffer = '';
/**
* Read in the file via Import::getNextChunk so that
* it can process compressed files
*/
while (! $finished && ! $error && ! $timeout_passed) {
$data = $this->import->getNextChunk($importHandle);
if ($data === false) {
/* subtract data we didn't handle yet and stop processing */
$GLOBALS['offset'] -= strlen($buffer);
break;
}
if ($data === true) {
continue;
}
/* Append new data to buffer */
$buffer .= $data;
}
/**
* Disable loading of external XML entities for PHP versions below 8.0.
*/
if (PHP_VERSION_ID < 80000) {
// phpcs:ignore Generic.PHP.DeprecatedFunctions.Deprecated
libxml_disable_entity_loader();
}
/**
* Load the XML string
*
* The option LIBXML_COMPACT is specified because it can
* result in increased performance without the need to
* alter the code in any way. It's basically a freebee.
*/
$xml = @simplexml_load_string($buffer, SimpleXMLElement::class, LIBXML_COMPACT);
unset($buffer);
/**
* The XML was malformed
*/
if ($xml === false) {
echo Message::error(
__(
'The XML file specified was either malformed or incomplete. Please correct the issue and try again.'
)
)->getDisplay();
unset($xml);
$GLOBALS['finished'] = false;
return;
}
/**
* Table accumulator
*/
$tables = [];
/**
* Row accumulator
*/
$rows = [];
/**
* Temp arrays
*/
$tempRow = [];
$tempCells = [];
/**
* CREATE code included (by default: no)
*/
$struct_present = false;
/**
* Analyze the data in each table
*/
$namespaces = $xml->getNamespaces(true);
/**
* Get the database name, collation and charset
*/
$db_attr = $xml->children($namespaces['pma'] ?? null)
->{'structure_schemas'}->{'database'};
if ($db_attr instanceof SimpleXMLElement) {
$db_attr = $db_attr->attributes();
$db_name = (string) $db_attr['name'];
$collation = (string) $db_attr['collation'];
$charset = (string) $db_attr['charset'];
} else {
/**
* If the structure section is not present
* get the database name from the data section
*/
$db_attr = $xml->children()
->attributes();
$db_name = (string) $db_attr['name'];
$collation = null;
$charset = null;
}
/**
* The XML was malformed
*/
if ($db_name === '') {
echo Message::error(
__(
'The XML file specified was either malformed or incomplete. Please correct the issue and try again.'
)
)->getDisplay();
unset($xml);
$GLOBALS['finished'] = false;
return;
}
/**
* Retrieve the structure information
*/
if (isset($namespaces['pma'])) {
/**
* Get structures for all tables
*
* @var SimpleXMLElement $struct
*/
$struct = $xml->children($namespaces['pma']);
$create = [];
foreach ($struct as $val1) {
foreach ($val1 as $val2) {
// Need to select the correct database for the creation of
// tables, views, triggers, etc.
/**
* @todo Generating a USE here blocks importing of a table
* into another database.
*/
$attrs = $val2->attributes();
$create[] = 'USE ' . Util::backquote((string) $attrs['name']);
foreach ($val2 as $val3) {
/**
* Remove the extra cosmetic spacing
*/
$val3 = str_replace(' ', '', (string) $val3);
$create[] = $val3;
}
}
}
$struct_present = true;
}
/**
* Move down the XML tree to the actual data
*/
$xml = $xml->children()
->children();
$data_present = false;
/**
* Only attempt to analyze/collect data if there is data present
*/
if ($xml && $xml->children()->count()) {
$data_present = true;
/**
* Process all database content
*/
foreach ($xml as $v1) {
/** @psalm-suppress PossiblyNullReference */
$tbl_attr = $v1->attributes();
$isInTables = false;
$num_tables = count($tables);
for ($i = 0; $i < $num_tables; ++$i) {
if (! strcmp($tables[$i][Import::TBL_NAME], (string) $tbl_attr['name'])) {
$isInTables = true;
break;
}
}
if (! $isInTables) {
$tables[] = [(string) $tbl_attr['name']];
}
foreach ($v1 as $v2) {
/** @psalm-suppress PossiblyNullReference */
$row_attr = $v2->attributes();
if (! in_array((string) $row_attr['name'], $tempRow)) {
$tempRow[] = (string) $row_attr['name'];
}
$tempCells[] = (string) $v2;
}
$rows[] = [
(string) $tbl_attr['name'],
$tempRow,
$tempCells,
];
$tempRow = [];
$tempCells = [];
}
unset($tempRow, $tempCells, $xml);
/**
* Bring accumulated rows into the corresponding table
*/
$num_tables = count($tables);
for ($i = 0; $i < $num_tables; ++$i) {
$num_rows = count($rows);
for ($j = 0; $j < $num_rows; ++$j) {
if (strcmp($tables[$i][Import::TBL_NAME], $rows[$j][Import::TBL_NAME])) {
continue;
}
if (! isset($tables[$i][Import::COL_NAMES])) {
$tables[$i][] = $rows[$j][Import::COL_NAMES];
}
$tables[$i][Import::ROWS][] = $rows[$j][Import::ROWS];
}
}
unset($rows);
if (! $struct_present) {
$analyses = [];
$len = count($tables);
for ($i = 0; $i < $len; ++$i) {
$analyses[] = $this->import->analyzeTable($tables[$i]);
}
}
}
unset($xml, $tempCells, $rows);
/**
* Only build SQL from data if there is data present
*/
if ($data_present) {
/**
* Set values to NULL if they were not present
* to maintain Import::buildSql() call integrity
*/
if (! isset($analyses)) {
$analyses = null;
if (! $struct_present) {
$create = null;
}
}
}
/**
* string $db_name (no backquotes)
*
* array $table = array(table_name, array() column_names, array()() rows)
* array $tables = array of "$table"s
*
* array $analysis = array(array() column_types, array() column_sizes)
* array $analyses = array of "$analysis"s
*
* array $create = array of SQL strings
*
* array $options = an associative array of options
*/
/* Set database name to the currently selected one, if applicable */
if (strlen((string) $db)) {
/* Override the database name in the XML file, if one is selected */
$db_name = $db;
$options = ['create_db' => false];
} else {
/* Set database collation/charset */
$options = [
'db_collation' => $collation,
'db_charset' => $charset,
];
}
/* Created and execute necessary SQL statements from data */
$this->import->buildSql($db_name, $tables, $analyses, $create, $options, $sql_data);
unset($analyses, $tables, $create);
/* Commit any possible data in buffers */
$this->import->runQuery('', '', $sql_data);
}
}

View file

@ -1,153 +0,0 @@
# Import plugin creation
This directory holds import plugins for phpMyAdmin. Any new plugin should
basically follow the structure presented here. The messages must use our
gettext mechanism, see https://wiki.phpmyadmin.net/pma/Gettext_for_developers.
```php
<?php
/**
* [Name] import plugin for phpMyAdmin
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Import;
use PhpMyAdmin\Plugins\ImportPlugin;
use function strlen;
/**
* Handles the import for the [Name] format
*/
class Import[Name] extends ImportPlugin
{
/**
* optional - declare variables and descriptions
*
* @var type
*/
private $myOptionalVariable;
/**
* Constructor
*/
public function __construct()
{
parent::__construct();
$this->setProperties();
}
/**
* Sets the import plugin properties.
* Called in the constructor.
*
* @return void
*/
protected function setProperties()
{
$importPluginProperties = new PhpMyAdmin\Properties\Plugins\ImportPluginProperties();
$importPluginProperties->setText('[name]'); // the name of your plug-in
$importPluginProperties->setExtension('[ext]'); // extension this plug-in can handle
$importPluginProperties->setOptionsText(__('Options'));
// create the root group that will be the options field for
// $importPluginProperties
// this will be shown as "Format specific options"
$importSpecificOptions = new PhpMyAdmin\Properties\Options\Groups\OptionsPropertyRootGroup(
'Format Specific Options'
);
// general options main group
$generalOptions = new PhpMyAdmin\Properties\Options\Groups\OptionsPropertyMainGroup(
'general_opts'
);
// optional :
// create primary items and add them to the group
// type - one of the classes listed in libraries/properties/options/items/
// name - form element name
// text - description in GUI
// size - size of text element
// len - maximal size of input
// values - possible values of the item
$leaf = new PhpMyAdmin\Properties\Options\Items\RadioPropertyItem(
'structure_or_data'
);
$leaf->setValues(
[
'structure' => __('structure'),
'data' => __('data'),
'structure_and_data' => __('structure and data'),
]
);
$generalOptions->addProperty($leaf);
// add the main group to the root group
$importSpecificOptions->addProperty($generalOptions);
// set the options for the import plugin property item
$importPluginProperties->setOptions($importSpecificOptions);
$this->properties = $importPluginProperties;
}
/**
* Handles the whole import logic
*
* @param array &$sql_data 2-element array with sql data
*
* @return void
*/
public function doImport(&$sql_data = [])
{
// get globals (others are optional)
global $error, $timeout_passed, $finished;
$buffer = '';
while (! ($finished && $i >= $len) && ! $error && ! $timeout_passed) {
$data = $this->import->getNextChunk();
if ($data === false) {
// subtract data we didn't handle yet and stop processing
$GLOBALS['offset'] -= strlen($buffer);
break;
}
if ($data === true) {
// Handle rest of buffer
} else {
// Append new data to buffer
$buffer .= $data;
}
// PARSE $buffer here, post sql queries using:
$this->import->runQuery($sql, $verbose_sql_with_comments, $sql_data);
} // End of import loop
// Commit any possible data in buffers
$this->import->runQuery('', '', $sql_data);
}
/* optional: */
/* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */
/**
* Getter description
*
* @return type
*/
private function getMyOptionalVariable(): type
{
return $this->myOptionalVariable;
}
/**
* Setter description
*
* @param type $myOptionalVariable description
*
* @return void
*/
private function _setMyOptionalVariable(type $myOptionalVariable): void
{
$this->myOptionalVariable = $myOptionalVariable;
}
}
```

View file

@ -1,39 +0,0 @@
<?php
/**
* This class extends ShapeFile class to cater the following phpMyAdmin
* specific requirements.
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Import;
use PhpMyAdmin\ShapeFile\ShapeFile;
/**
* ShapeFileImport class
*/
class ShapeFileImport extends ShapeFile
{
/**
* Reads given number of bytes from SHP file
*
* @param int $bytes number of bytes
*
* @return string|false
*/
public function readSHP(int $bytes)
{
return ImportShp::readFromBuffer($bytes);
}
/**
* Checks whether file is at EOF
*/
public function eofSHP(): bool
{
global $eof;
return (bool) $eof;
}
}

View file

@ -1,61 +0,0 @@
<?php
/**
* Provides upload functionalities for the import plugins
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Import\Upload;
use PhpMyAdmin\Plugins\UploadInterface;
use function array_key_exists;
use function trim;
/**
* Implementation for no plugin
*/
class UploadNoplugin implements UploadInterface
{
/**
* Gets the specific upload ID Key
*
* @return string ID Key
*/
public static function getIdKey()
{
return 'noplugin';
}
/**
* Returns upload status.
*
* This is implementation when no webserver support exists,
* so it returns just zeroes.
*
* @param string $id upload id
*
* @return array|null
*/
public static function getUploadStatus($id)
{
global $SESSION_KEY;
if (trim($id) == '') {
return null;
}
if (! array_key_exists($id, $_SESSION[$SESSION_KEY])) {
$_SESSION[$SESSION_KEY][$id] = [
'id' => $id,
'finished' => false,
'percent' => 0,
'total' => 0,
'complete' => 0,
'plugin' => self::getIdKey(),
];
}
return $_SESSION[$SESSION_KEY][$id];
}
}

View file

@ -1,101 +0,0 @@
<?php
/**
* Provides upload functionalities for the import plugins
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Import\Upload;
use PhpMyAdmin\Import\Ajax;
use PhpMyAdmin\Plugins\UploadInterface;
use function array_key_exists;
use function function_exists;
use function trim;
/**
* Implementation for upload progress
*/
class UploadProgress implements UploadInterface
{
/**
* Gets the specific upload ID Key
*
* @return string ID Key
*/
public static function getIdKey()
{
return 'UPLOAD_IDENTIFIER';
}
/**
* Returns upload status.
*
* This is implementation for upload progress
*
* @param string $id upload id
*
* @return array|null
*/
public static function getUploadStatus($id)
{
global $SESSION_KEY;
if (trim($id) == '') {
return null;
}
if (! array_key_exists($id, $_SESSION[$SESSION_KEY])) {
$_SESSION[$SESSION_KEY][$id] = [
'id' => $id,
'finished' => false,
'percent' => 0,
'total' => 0,
'complete' => 0,
'plugin' => self::getIdKey(),
];
}
$ret = $_SESSION[$SESSION_KEY][$id];
if (! Ajax::progressCheck() || $ret['finished']) {
return $ret;
}
$status = null;
// @see https://pecl.php.net/package/uploadprogress
if (function_exists('uploadprogress_get_info')) {
// phpcs:ignore SlevomatCodingStandard.Namespaces.ReferenceUsedNamesOnly.ReferenceViaFullyQualifiedName
$status = \uploadprogress_get_info($id);
}
if ($status) {
$ret['finished'] = false;
if ($status['bytes_uploaded'] == $status['bytes_total']) {
$ret['finished'] = true;
}
$ret['total'] = $status['bytes_total'];
$ret['complete'] = $status['bytes_uploaded'];
if ($ret['total'] > 0) {
$ret['percent'] = $ret['complete'] / $ret['total'] * 100;
}
} else {
$ret = [
'id' => $id,
'finished' => true,
'percent' => 100,
'total' => $ret['total'],
'complete' => $ret['total'],
'plugin' => self::getIdKey(),
];
}
$_SESSION[$SESSION_KEY][$id] = $ret;
return $ret;
}
}

View file

@ -1,96 +0,0 @@
<?php
/**
* Provides upload functionalities for the import plugins
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Import\Upload;
use PhpMyAdmin\Import\Ajax;
use PhpMyAdmin\Plugins\UploadInterface;
use function array_key_exists;
use function ini_get;
use function trim;
/**
* Implementation for session
*/
class UploadSession implements UploadInterface
{
/**
* Gets the specific upload ID Key
*
* @return string ID Key
*/
public static function getIdKey()
{
return (string) ini_get('session.upload_progress.name');
}
/**
* Returns upload status.
*
* This is implementation for session.upload_progress in PHP 5.4+.
*
* @param string $id upload id
*
* @return array|null
*/
public static function getUploadStatus($id)
{
global $SESSION_KEY;
if (trim($id) == '') {
return null;
}
if (! array_key_exists($id, $_SESSION[$SESSION_KEY])) {
$_SESSION[$SESSION_KEY][$id] = [
'id' => $id,
'finished' => false,
'percent' => 0,
'total' => 0,
'complete' => 0,
'plugin' => self::getIdKey(),
];
}
$ret = $_SESSION[$SESSION_KEY][$id];
if (! Ajax::sessionCheck() || $ret['finished']) {
return $ret;
}
$status = false;
$sessionkey = ini_get('session.upload_progress.prefix') . $id;
if (isset($_SESSION[$sessionkey])) {
$status = $_SESSION[$sessionkey];
}
if ($status) {
$ret['finished'] = $status['done'];
$ret['total'] = $status['content_length'];
$ret['complete'] = $status['bytes_processed'];
if ($ret['total'] > 0) {
$ret['percent'] = $ret['complete'] / $ret['total'] * 100;
}
} else {
$ret = [
'id' => $id,
'finished' => true,
'percent' => 100,
'total' => $ret['total'],
'complete' => $ret['total'],
'plugin' => self::getIdKey(),
];
}
$_SESSION[$SESSION_KEY][$id] = $ret;
return $ret;
}
}

View file

@ -1,97 +0,0 @@
<?php
/**
* Abstract class for the import plugins
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins;
use PhpMyAdmin\File;
use PhpMyAdmin\Import;
use PhpMyAdmin\Properties\Plugins\ImportPluginProperties;
use PhpMyAdmin\Properties\Plugins\PluginPropertyItem;
use function strlen;
/**
* Provides a common interface that will have to be implemented by all of the
* import plugins.
*/
abstract class ImportPlugin implements Plugin
{
/**
* Object containing the import plugin properties.
*
* @var ImportPluginProperties
*/
protected $properties;
/** @var Import */
protected $import;
final public function __construct()
{
$this->import = new Import();
$this->init();
$this->properties = $this->setProperties();
}
/**
* Plugin specific initializations.
*/
protected function init(): void
{
}
/**
* Handles the whole import logic
*
* @param array $sql_data 2-element array with sql data
*/
abstract public function doImport(?File $importHandle = null, array &$sql_data = []): void;
/**
* Gets the import specific format plugin properties
*
* @return ImportPluginProperties
*/
public function getProperties(): PluginPropertyItem
{
return $this->properties;
}
/**
* Sets the export plugins properties and is implemented by each import plugin.
*/
abstract protected function setProperties(): ImportPluginProperties;
/**
* Define DB name and options
*
* @param string $currentDb DB
* @param string $defaultDb Default DB name
*
* @return array DB name and options (an associative array of options)
*/
protected function getDbnameAndOptions($currentDb, $defaultDb)
{
$db_name = $defaultDb;
$options = null;
if (strlen((string) $currentDb) > 0) {
$db_name = $currentDb;
$options = ['create_db' => false];
}
return [
$db_name,
$options,
];
}
public static function isAvailable(): bool
{
return true;
}
}

View file

@ -1,19 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Plugins;
use PhpMyAdmin\Properties\Plugins\PluginPropertyItem;
interface Plugin
{
/**
* @psalm-return non-empty-lowercase-string
*/
public function getName(): string;
public function getProperties(): PluginPropertyItem;
public static function isAvailable(): bool;
}

View file

@ -1,187 +0,0 @@
<?php
/**
* Classes to create relation schema in Dia format.
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Schema\Dia;
use PhpMyAdmin\Core;
use PhpMyAdmin\ResponseRenderer;
use XMLWriter;
use function ob_end_clean;
use function ob_get_clean;
use function strlen;
/**
* This Class inherits the XMLwriter class and
* helps in developing structure of DIA Schema Export
*
* @see https://www.php.net/manual/en/book.xmlwriter.php
*/
class Dia extends XMLWriter
{
/**
* Upon instantiation This starts writing the Dia XML document
*
* @see XMLWriter::openMemory()
* @see XMLWriter::setIndent()
* @see XMLWriter::startDocument()
*/
public function __construct()
{
$this->openMemory();
/*
* Set indenting using three spaces,
* so output is formatted
*/
$this->setIndent(true);
$this->setIndentString(' ');
/*
* Create the XML document
*/
$this->startDocument('1.0', 'UTF-8');
}
/**
* Starts Dia Document
*
* dia document starts by first initializing dia:diagram tag
* then dia:diagramdata contains all the attributes that needed
* to define the document, then finally a Layer starts which
* holds all the objects.
*
* @see XMLWriter::startElement()
* @see XMLWriter::writeAttribute()
* @see XMLWriter::writeRaw()
*
* @param string $paper the size of the paper/document
* @param float $topMargin top margin of the paper/document in cm
* @param float $bottomMargin bottom margin of the paper/document in cm
* @param float $leftMargin left margin of the paper/document in cm
* @param float $rightMargin right margin of the paper/document in cm
* @param string $orientation orientation of the document, portrait or landscape
*/
public function startDiaDoc(
$paper,
$topMargin,
$bottomMargin,
$leftMargin,
$rightMargin,
$orientation
): void {
$isPortrait = 'false';
if ($orientation === 'P') {
$isPortrait = 'true';
}
$this->startElement('dia:diagram');
$this->writeAttribute('xmlns:dia', 'http://www.lysator.liu.se/~alla/dia/');
$this->startElement('dia:diagramdata');
$this->writeRaw(
'<dia:attribute name="background">
<dia:color val="#ffffff"/>
</dia:attribute>
<dia:attribute name="pagebreak">
<dia:color val="#000099"/>
</dia:attribute>
<dia:attribute name="paper">
<dia:composite type="paper">
<dia:attribute name="name">
<dia:string>#' . $paper . '#</dia:string>
</dia:attribute>
<dia:attribute name="tmargin">
<dia:real val="' . $topMargin . '"/>
</dia:attribute>
<dia:attribute name="bmargin">
<dia:real val="' . $bottomMargin . '"/>
</dia:attribute>
<dia:attribute name="lmargin">
<dia:real val="' . $leftMargin . '"/>
</dia:attribute>
<dia:attribute name="rmargin">
<dia:real val="' . $rightMargin . '"/>
</dia:attribute>
<dia:attribute name="is_portrait">
<dia:boolean val="' . $isPortrait . '"/>
</dia:attribute>
<dia:attribute name="scaling">
<dia:real val="1"/>
</dia:attribute>
<dia:attribute name="fitto">
<dia:boolean val="false"/>
</dia:attribute>
</dia:composite>
</dia:attribute>
<dia:attribute name="grid">
<dia:composite type="grid">
<dia:attribute name="width_x">
<dia:real val="1"/>
</dia:attribute>
<dia:attribute name="width_y">
<dia:real val="1"/>
</dia:attribute>
<dia:attribute name="visible_x">
<dia:int val="1"/>
</dia:attribute>
<dia:attribute name="visible_y">
<dia:int val="1"/>
</dia:attribute>
<dia:composite type="color"/>
</dia:composite>
</dia:attribute>
<dia:attribute name="color">
<dia:color val="#d8e5e5"/>
</dia:attribute>
<dia:attribute name="guides">
<dia:composite type="guides">
<dia:attribute name="hguides"/>
<dia:attribute name="vguides"/>
</dia:composite>
</dia:attribute>'
);
$this->endElement();
$this->startElement('dia:layer');
$this->writeAttribute('name', 'Background');
$this->writeAttribute('visible', 'true');
$this->writeAttribute('active', 'true');
}
/**
* Ends Dia Document
*
* @see XMLWriter::endElement()
* @see XMLWriter::endDocument()
*/
public function endDiaDoc(): void
{
$this->endElement();
$this->endDocument();
}
/**
* Output Dia Document for download
*
* @see XMLWriter::flush()
*
* @param string $fileName name of the dia document
*/
public function showOutput($fileName): void
{
if (ob_get_clean()) {
ob_end_clean();
}
$output = $this->flush();
ResponseRenderer::getInstance()->disable();
Core::downloadHeader(
$fileName,
'application/x-dia-diagram',
strlen($output)
);
print $output;
}
}

View file

@ -1,236 +0,0 @@
<?php
/**
* Classes to create relation schema in Dia format.
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Schema\Dia;
use PhpMyAdmin\Plugins\Schema\ExportRelationSchema;
use function in_array;
/**
* Dia Relation Schema Class
*
* Purpose of this class is to generate the Dia XML Document
* which is used for representing the database diagrams in Dia IDE
* This class uses Database Table and Reference Objects of Dia and with
* the combination of these objects actually helps in preparing Dia XML.
*
* Dia XML is generated by using XMLWriter php extension and this class
* inherits ExportRelationSchema class has common functionality added
* to this class
*
* @property Dia $diagram
*/
class DiaRelationSchema extends ExportRelationSchema
{
/** @var TableStatsDia[] */
private $tables = [];
/** @var RelationStatsDia[] Relations */
private $relations = [];
/** @var float */
private $topMargin = 2.8222000598907471;
/** @var float */
private $bottomMargin = 2.8222000598907471;
/** @var float */
private $leftMargin = 2.8222000598907471;
/** @var float */
private $rightMargin = 2.8222000598907471;
/** @var int */
public static $objectId = 0;
/**
* Upon instantiation This outputs the Dia XML document
* that user can download
*
* @see Dia
* @see TableStatsDia
* @see RelationStatsDia
*
* @param string $db database name
*/
public function __construct($db)
{
parent::__construct($db, new Dia());
$this->setShowColor(isset($_REQUEST['dia_show_color']));
$this->setShowKeys(isset($_REQUEST['dia_show_keys']));
$this->setOrientation((string) $_REQUEST['dia_orientation']);
$this->setPaper((string) $_REQUEST['dia_paper']);
$this->diagram->startDiaDoc(
$this->paper,
$this->topMargin,
$this->bottomMargin,
$this->leftMargin,
$this->rightMargin,
$this->orientation
);
$alltables = $this->getTablesFromRequest();
foreach ($alltables as $table) {
if (isset($this->tables[$table])) {
continue;
}
$this->tables[$table] = new TableStatsDia(
$this->diagram,
$this->db,
$table,
$this->pageNumber,
$this->showKeys,
$this->offline
);
}
$seen_a_relation = false;
foreach ($alltables as $one_table) {
$exist_rel = $this->relation->getForeigners($this->db, $one_table, '', 'both');
if (! $exist_rel) {
continue;
}
$seen_a_relation = true;
foreach ($exist_rel as $master_field => $rel) {
/* put the foreign table on the schema only if selected
* by the user
* (do not use array_search() because we would have to
* to do a === false and this is not PHP3 compatible)
*/
if ($master_field !== 'foreign_keys_data') {
if (in_array($rel['foreign_table'], $alltables)) {
$this->addRelation(
$one_table,
$master_field,
$rel['foreign_table'],
$rel['foreign_field'],
$this->showKeys
);
}
continue;
}
foreach ($rel as $one_key) {
if (! in_array($one_key['ref_table_name'], $alltables)) {
continue;
}
foreach ($one_key['index_list'] as $index => $one_field) {
$this->addRelation(
$one_table,
$one_field,
$one_key['ref_table_name'],
$one_key['ref_index_list'][$index],
$this->showKeys
);
}
}
}
}
$this->drawTables();
if ($seen_a_relation) {
$this->drawRelations();
}
$this->diagram->endDiaDoc();
}
/**
* Output Dia Document for download
*/
public function showOutput(): void
{
$this->diagram->showOutput($this->getFileName('.dia'));
}
/**
* Defines relation objects
*
* @see TableStatsDia::__construct(),RelationStatsDia::__construct()
*
* @param string $masterTable The master table name
* @param string $masterField The relation field in the master table
* @param string $foreignTable The foreign table name
* @param string $foreignField The relation field in the foreign table
* @param bool $showKeys Whether to display ONLY keys or not
*/
private function addRelation(
$masterTable,
$masterField,
$foreignTable,
$foreignField,
$showKeys
): void {
if (! isset($this->tables[$masterTable])) {
$this->tables[$masterTable] = new TableStatsDia(
$this->diagram,
$this->db,
$masterTable,
$this->pageNumber,
$showKeys
);
}
if (! isset($this->tables[$foreignTable])) {
$this->tables[$foreignTable] = new TableStatsDia(
$this->diagram,
$this->db,
$foreignTable,
$this->pageNumber,
$showKeys
);
}
$this->relations[] = new RelationStatsDia(
$this->diagram,
$this->tables[$masterTable],
$masterField,
$this->tables[$foreignTable],
$foreignField
);
}
/**
* Draws relation references
*
* connects master table's master field to
* foreign table's foreign field using Dia object
* type Database - Reference
*
* @see RelationStatsDia::relationDraw()
*/
private function drawRelations(): void
{
foreach ($this->relations as $relation) {
$relation->relationDraw($this->showColor);
}
}
/**
* Draws tables
*
* Tables are generated using Dia object type Database - Table
* primary fields are underlined and bold in tables
*
* @see TableStatsDia::tableDraw()
*/
private function drawTables(): void
{
foreach ($this->tables as $table) {
$table->tableDraw($this->showColor);
}
}
}

View file

@ -1,237 +0,0 @@
<?php
/**
* Contains PhpMyAdmin\Plugins\Schema\Dia\RelationStatsDia class
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Schema\Dia;
use function array_search;
use function shuffle;
/**
* Relation preferences/statistics
*
* This class fetches the table master and foreign fields positions
* and helps in generating the Table references and then connects
* master table's master field to foreign table's foreign key
* in dia XML document.
*/
class RelationStatsDia
{
/** @var Dia */
protected $diagram;
/** @var mixed */
public $srcConnPointsRight;
/** @var mixed */
public $srcConnPointsLeft;
/** @var mixed */
public $destConnPointsRight;
/** @var mixed */
public $destConnPointsLeft;
/** @var int */
public $masterTableId;
/** @var int */
public $foreignTableId;
/** @var mixed */
public $masterTablePos;
/** @var mixed */
public $foreignTablePos;
/** @var string */
public $referenceColor = '#000000';
/**
* @see Relation_Stats_Dia::getXy
*
* @param Dia $diagram The DIA diagram
* @param TableStatsDia $master_table The master table name
* @param string $master_field The relation field in the master table
* @param TableStatsDia $foreign_table The foreign table name
* @param string $foreign_field The relation field in the foreign table
*/
public function __construct(
$diagram,
$master_table,
$master_field,
$foreign_table,
$foreign_field
) {
$this->diagram = $diagram;
$src_pos = $this->getXy($master_table, $master_field);
$dest_pos = $this->getXy($foreign_table, $foreign_field);
$this->srcConnPointsLeft = $src_pos[0];
$this->srcConnPointsRight = $src_pos[1];
$this->destConnPointsLeft = $dest_pos[0];
$this->destConnPointsRight = $dest_pos[1];
$this->masterTablePos = $src_pos[2];
$this->foreignTablePos = $dest_pos[2];
$this->masterTableId = $master_table->tableId;
$this->foreignTableId = $foreign_table->tableId;
}
/**
* Each Table object have connection points
* which is used to connect to other objects in Dia
* we detect the position of key in fields and
* then determines its left and right connection
* points.
*
* @param TableStatsDia $table The current table name
* @param string $column The relation column name
*
* @return array Table right,left connection points and key position
*/
private function getXy($table, $column)
{
$pos = array_search($column, $table->fields);
// left, right, position
$value = 12;
if ($pos != 0) {
return [
$pos + $value + $pos,
$pos + $value + $pos + 1,
$pos,
];
}
return [
$pos + $value,
$pos + $value + 1,
$pos,
];
}
/**
* Draws relation references
*
* connects master table's master field to foreign table's
* foreign field using Dia object type Database - Reference
* Dia object is used to generate the XML of Dia Document.
* Database reference Object and their attributes are involved
* in the combination of displaying Database - reference on Dia Document.
*
* @see PDF
*
* @param bool $showColor Whether to use one color per relation or not
* if showColor is true then an array of $listOfColors
* will be used to choose the random colors for
* references lines. we can change/add more colors to
* this
*
* @return bool|void
*/
public function relationDraw($showColor)
{
++DiaRelationSchema::$objectId;
/*
* if source connection points and destination connection
* points are same then return it false and don't draw that
* relation
*/
if ($this->srcConnPointsRight == $this->destConnPointsRight) {
if ($this->srcConnPointsLeft == $this->destConnPointsLeft) {
return false;
}
}
if ($showColor) {
$listOfColors = [
'FF0000',
'000099',
'00FF00',
];
shuffle($listOfColors);
$this->referenceColor = '#' . $listOfColors[0] . '';
} else {
$this->referenceColor = '#000000';
}
$this->diagram->writeRaw(
'<dia:object type="Database - Reference" version="0" id="'
. DiaRelationSchema::$objectId . '">
<dia:attribute name="obj_pos">
<dia:point val="3.27,18.9198"/>
</dia:attribute>
<dia:attribute name="obj_bb">
<dia:rectangle val="2.27,8.7175;17.7679,18.9198"/>
</dia:attribute>
<dia:attribute name="meta">
<dia:composite type="dict"/>
</dia:attribute>
<dia:attribute name="orth_points">
<dia:point val="3.27,18.9198"/>
<dia:point val="2.27,18.9198"/>
<dia:point val="2.27,14.1286"/>
<dia:point val="17.7679,14.1286"/>
<dia:point val="17.7679,9.3375"/>
<dia:point val="16.7679,9.3375"/>
</dia:attribute>
<dia:attribute name="orth_orient">
<dia:enum val="0"/>
<dia:enum val="1"/>
<dia:enum val="0"/>
<dia:enum val="1"/>
<dia:enum val="0"/>
</dia:attribute>
<dia:attribute name="orth_autoroute">
<dia:boolean val="true"/>
</dia:attribute>
<dia:attribute name="text_colour">
<dia:color val="#000000"/>
</dia:attribute>
<dia:attribute name="line_colour">
<dia:color val="' . $this->referenceColor . '"/>
</dia:attribute>
<dia:attribute name="line_width">
<dia:real val="0.10000000000000001"/>
</dia:attribute>
<dia:attribute name="line_style">
<dia:enum val="0"/>
<dia:real val="1"/>
</dia:attribute>
<dia:attribute name="corner_radius">
<dia:real val="0"/>
</dia:attribute>
<dia:attribute name="end_arrow">
<dia:enum val="22"/>
</dia:attribute>
<dia:attribute name="end_arrow_length">
<dia:real val="0.5"/>
</dia:attribute>
<dia:attribute name="end_arrow_width">
<dia:real val="0.5"/>
</dia:attribute>
<dia:attribute name="start_point_desc">
<dia:string>#1#</dia:string>
</dia:attribute>
<dia:attribute name="end_point_desc">
<dia:string>#n#</dia:string>
</dia:attribute>
<dia:attribute name="normal_font">
<dia:font family="monospace" style="0" name="Courier"/>
</dia:attribute>
<dia:attribute name="normal_font_height">
<dia:real val="0.59999999999999998"/>
</dia:attribute>
<dia:connections>
<dia:connection handle="0" to="'
. $this->masterTableId . '" connection="'
. $this->srcConnPointsRight . '"/>
<dia:connection handle="1" to="'
. $this->foreignTableId . '" connection="'
. $this->destConnPointsRight . '"/>
</dia:connections>
</dia:object>'
);
}
}

View file

@ -1,223 +0,0 @@
<?php
/**
* Contains PhpMyAdmin\Plugins\Schema\Dia\TableStatsDia class
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Schema\Dia;
use PhpMyAdmin\Plugins\Schema\ExportRelationSchema;
use PhpMyAdmin\Plugins\Schema\TableStats;
use function __;
use function in_array;
use function shuffle;
use function sprintf;
/**
* Table preferences/statistics
*
* This class preserves the table co-ordinates,fields
* and helps in drawing/generating the Tables in dia XML document.
*
* @property Dia $diagram
*/
class TableStatsDia extends TableStats
{
/** @var int */
public $tableId;
/** @var string */
public $tableColor = '#000000';
/**
* @param Dia $diagram The current dia document
* @param string $db The database name
* @param string $tableName The table name
* @param int $pageNumber The current page number (from the
* $cfg['Servers'][$i]['table_coords'] table)
* @param bool $showKeys Whether to display ONLY keys or not
* @param bool $offline Whether the coordinates are sent from the browser
*/
public function __construct(
$diagram,
$db,
$tableName,
$pageNumber,
$showKeys = false,
$offline = false
) {
parent::__construct($diagram, $db, $pageNumber, $tableName, $showKeys, false, $offline);
/**
* Every object in Dia document needs an ID to identify
* so, we used a static variable to keep the things unique
*/
$this->tableId = ++DiaRelationSchema::$objectId;
}
/**
* Displays an error when the table cannot be found.
*/
protected function showMissingTableError(): void
{
ExportRelationSchema::dieSchema(
$this->pageNumber,
'DIA',
sprintf(__('The %s table doesn\'t exist!'), $this->tableName)
);
}
/**
* Do draw the table
*
* Tables are generated using object type Database - Table
* primary fields are underlined in tables. Dia object
* is used to generate the XML of Dia Document. Database Table
* Object and their attributes are involved in the combination
* of displaying Database - Table on Dia Document.
*
* @see Dia
*
* @param bool $showColor Whether to show color for tables text or not
* if showColor is true then an array of $listOfColors
* will be used to choose the random colors for tables
* text we can change/add more colors to this array
*/
public function tableDraw($showColor): void
{
if ($showColor) {
$listOfColors = [
'FF0000',
'000099',
'00FF00',
];
shuffle($listOfColors);
$this->tableColor = '#' . $listOfColors[0] . '';
} else {
$this->tableColor = '#000000';
}
$factor = 0.1;
$this->diagram->startElement('dia:object');
$this->diagram->writeAttribute('type', 'Database - Table');
$this->diagram->writeAttribute('version', '0');
$this->diagram->writeAttribute('id', '' . $this->tableId . '');
$this->diagram->writeRaw(
'<dia:attribute name="obj_pos">
<dia:point val="'
. ($this->x * $factor) . ',' . ($this->y * $factor) . '"/>
</dia:attribute>
<dia:attribute name="obj_bb">
<dia:rectangle val="'
. ($this->x * $factor) . ',' . ($this->y * $factor) . ';9.97,9.2"/>
</dia:attribute>
<dia:attribute name="meta">
<dia:composite type="dict"/>
</dia:attribute>
<dia:attribute name="elem_corner">
<dia:point val="'
. ($this->x * $factor) . ',' . ($this->y * $factor) . '"/>
</dia:attribute>
<dia:attribute name="elem_width">
<dia:real val="5.9199999999999999"/>
</dia:attribute>
<dia:attribute name="elem_height">
<dia:real val="3.5"/>
</dia:attribute>
<dia:attribute name="text_colour">
<dia:color val="' . $this->tableColor . '"/>
</dia:attribute>
<dia:attribute name="line_colour">
<dia:color val="#000000"/>
</dia:attribute>
<dia:attribute name="fill_colour">
<dia:color val="#ffffff"/>
</dia:attribute>
<dia:attribute name="line_width">
<dia:real val="0.10000000000000001"/>
</dia:attribute>
<dia:attribute name="name">
<dia:string>#' . $this->tableName . '#</dia:string>
</dia:attribute>
<dia:attribute name="comment">
<dia:string>##</dia:string>
</dia:attribute>
<dia:attribute name="visible_comment">
<dia:boolean val="false"/>
</dia:attribute>
<dia:attribute name="tagging_comment">
<dia:boolean val="false"/>
</dia:attribute>
<dia:attribute name="underline_primary_key">
<dia:boolean val="true"/>
</dia:attribute>
<dia:attribute name="bold_primary_keys">
<dia:boolean val="true"/>
</dia:attribute>
<dia:attribute name="normal_font">
<dia:font family="monospace" style="0" name="Courier"/>
</dia:attribute>
<dia:attribute name="name_font">
<dia:font family="sans" style="80" name="Helvetica-Bold"/>
</dia:attribute>
<dia:attribute name="comment_font">
<dia:font family="sans" style="0" name="Helvetica"/>
</dia:attribute>
<dia:attribute name="normal_font_height">
<dia:real val="0.80000000000000004"/>
</dia:attribute>
<dia:attribute name="name_font_height">
<dia:real val="0.69999999999999996"/>
</dia:attribute>
<dia:attribute name="comment_font_height">
<dia:real val="0.69999999999999996"/>
</dia:attribute>'
);
$this->diagram->startElement('dia:attribute');
$this->diagram->writeAttribute('name', 'attributes');
foreach ($this->fields as $field) {
$this->diagram->writeRaw(
'<dia:composite type="table_attribute">
<dia:attribute name="name">
<dia:string>#' . $field . '#</dia:string>
</dia:attribute>
<dia:attribute name="type">
<dia:string>##</dia:string>
</dia:attribute>
<dia:attribute name="comment">
<dia:string>##</dia:string>
</dia:attribute>'
);
unset($pm);
$pm = 'false';
if (in_array($field, $this->primary)) {
$pm = 'true';
}
if ($field == $this->displayfield) {
$pm = 'false';
}
$this->diagram->writeRaw(
'<dia:attribute name="primary_key">
<dia:boolean val="' . $pm . '"/>
</dia:attribute>
<dia:attribute name="nullable">
<dia:boolean val="false"/>
</dia:attribute>
<dia:attribute name="unique">
<dia:boolean val="' . $pm . '"/>
</dia:attribute>
</dia:composite>'
);
}
$this->diagram->endElement();
$this->diagram->endElement();
}
}

View file

@ -1,257 +0,0 @@
<?php
/**
* Classes to create relation schema in EPS format.
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Schema\Eps;
use PhpMyAdmin\Core;
use PhpMyAdmin\ResponseRenderer;
use function strlen;
/**
* This Class is EPS Library and
* helps in developing structure of EPS Schema Export
*
* @see https://www.php.net/manual/en/book.xmlwriter.php
*/
class Eps
{
/** @var string */
public $font = 'Arial';
/** @var int */
public $fontSize = 12;
/** @var string */
public $stringCommands;
/**
* Upon instantiation This starts writing the EPS Document.
* %!PS-Adobe-3.0 EPSF-3.0 This is the MUST first comment to include
* it shows/tells that the Post Script document is purely under
* Document Structuring Convention [DSC] and is Compliant
* Encapsulated Post Script Document
*/
public function __construct()
{
$this->stringCommands = '';
$this->stringCommands .= "%!PS-Adobe-3.0 EPSF-3.0 \n";
}
/**
* Set document title
*
* @param string $value sets the title text
*/
public function setTitle($value): void
{
$this->stringCommands .= '%%Title: ' . $value . "\n";
}
/**
* Set document author
*
* @param string $value sets the author
*/
public function setAuthor($value): void
{
$this->stringCommands .= '%%Creator: ' . $value . "\n";
}
/**
* Set document creation date
*
* @param string $value sets the date
*/
public function setDate($value): void
{
$this->stringCommands .= '%%CreationDate: ' . $value . "\n";
}
/**
* Set document orientation
*
* @param string $orientation sets the orientation
*/
public function setOrientation($orientation): void
{
$this->stringCommands .= "%%PageOrder: Ascend \n";
if ($orientation === 'L') {
$orientation = 'Landscape';
$this->stringCommands .= '%%Orientation: ' . $orientation . "\n";
} else {
$orientation = 'Portrait';
$this->stringCommands .= '%%Orientation: ' . $orientation . "\n";
}
$this->stringCommands .= "%%EndComments \n";
$this->stringCommands .= "%%Pages 1 \n";
$this->stringCommands .= "%%BoundingBox: 72 150 144 170 \n";
}
/**
* Set the font and size
*
* font can be set whenever needed in EPS
*
* @param string $value sets the font name e.g Arial
* @param int $size sets the size of the font e.g 10
*/
public function setFont(string $value, int $size): void
{
$this->font = $value;
$this->fontSize = $size;
$this->stringCommands .= '/' . $value . " findfont % Get the basic font\n";
$this->stringCommands .= ''
. $size . ' scalefont % Scale the font to ' . $size . " points\n";
$this->stringCommands .= "setfont % Make it the current font\n";
}
/**
* Get the font
*
* @return string return the font name e.g Arial
*/
public function getFont()
{
return $this->font;
}
/**
* Get the font Size
*
* @return int return the size of the font e.g 10
*/
public function getFontSize(): int
{
return $this->fontSize;
}
/**
* Draw the line
*
* drawing the lines from x,y source to x,y destination and set the
* width of the line. lines helps in showing relationships of tables
*
* @param int $x_from The x_from attribute defines the start
* left position of the element
* @param int $y_from The y_from attribute defines the start
* right position of the element
* @param int $x_to The x_to attribute defines the end
* left position of the element
* @param int $y_to The y_to attribute defines the end
* right position of the element
* @param int $lineWidth Sets the width of the line e.g 2
*/
public function line(
$x_from = 0,
$y_from = 0,
$x_to = 0,
$y_to = 0,
$lineWidth = 0
): void {
$this->stringCommands .= $lineWidth . " setlinewidth \n";
$this->stringCommands .= $x_from . ' ' . $y_from . " moveto \n";
$this->stringCommands .= $x_to . ' ' . $y_to . " lineto \n";
$this->stringCommands .= "stroke \n";
}
/**
* Draw the rectangle
*
* drawing the rectangle from x,y source to x,y destination and set the
* width of the line. rectangles drawn around the text shown of fields
*
* @param int $x_from The x_from attribute defines the start
* left position of the element
* @param int $y_from The y_from attribute defines the start
* right position of the element
* @param int $x_to The x_to attribute defines the end
* left position of the element
* @param int $y_to The y_to attribute defines the end
* right position of the element
* @param int $lineWidth Sets the width of the line e.g 2
*/
public function rect($x_from, $y_from, $x_to, $y_to, $lineWidth): void
{
$this->stringCommands .= $lineWidth . " setlinewidth \n";
$this->stringCommands .= "newpath \n";
$this->stringCommands .= $x_from . ' ' . $y_from . " moveto \n";
$this->stringCommands .= '0 ' . $y_to . " rlineto \n";
$this->stringCommands .= $x_to . " 0 rlineto \n";
$this->stringCommands .= '0 -' . $y_to . " rlineto \n";
$this->stringCommands .= "closepath \n";
$this->stringCommands .= "stroke \n";
}
/**
* Set the current point
*
* The moveto operator takes two numbers off the stack and treats
* them as x and y coordinates to which to move. The coordinates
* specified become the current point.
*
* @param int $x The x attribute defines the left position of the element
* @param int $y The y attribute defines the right position of the element
*/
public function moveTo($x, $y): void
{
$this->stringCommands .= $x . ' ' . $y . " moveto \n";
}
/**
* Output/Display the text
*
* @param string $text The string to be displayed
*/
public function show($text): void
{
$this->stringCommands .= '(' . $text . ") show \n";
}
/**
* Output the text at specified co-ordinates
*
* @param string $text String to be displayed
* @param int $x X attribute defines the left position of the element
* @param int $y Y attribute defines the right position of the element
*/
public function showXY($text, $x, $y): void
{
$this->moveTo($x, $y);
$this->show($text);
}
/**
* Ends EPS Document
*/
public function endEpsDoc(): void
{
$this->stringCommands .= "showpage \n";
}
/**
* Output EPS Document for download
*
* @param string $fileName name of the eps document
*/
public function showOutput($fileName): void
{
// if(ob_get_clean()){
//ob_end_clean();
//}
$output = $this->stringCommands;
ResponseRenderer::getInstance()
->disable();
Core::downloadHeader(
$fileName,
'image/x-eps',
strlen($output)
);
print $output;
}
}

View file

@ -1,248 +0,0 @@
<?php
/**
* Classes to create relation schema in EPS format.
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Schema\Eps;
use PhpMyAdmin\Plugins\Schema\ExportRelationSchema;
use PhpMyAdmin\Version;
use function __;
use function date;
use function in_array;
use function sprintf;
/**
* EPS Relation Schema Class
*
* Purpose of this class is to generate the EPS Document
* which is used for representing the database diagrams.
* This class uses post script commands and with
* the combination of these commands actually helps in preparing EPS Document.
*
* This class inherits ExportRelationSchema class has common functionality added
* to this class
*
* @property Eps $diagram
*/
class EpsRelationSchema extends ExportRelationSchema
{
/** @var TableStatsEps[] */
private $tables = [];
/** @var RelationStatsEps[] Relations */
private $relations = [];
/** @var int */
private $tablewidth = 0;
/**
* Upon instantiation This starts writing the EPS document
* user will be prompted for download as .eps extension
*
* @see Eps
*
* @param string $db database name
*/
public function __construct($db)
{
parent::__construct($db, new Eps());
$this->setShowColor(isset($_REQUEST['eps_show_color']));
$this->setShowKeys(isset($_REQUEST['eps_show_keys']));
$this->setTableDimension(isset($_REQUEST['eps_show_table_dimension']));
$this->setAllTablesSameWidth(isset($_REQUEST['eps_all_tables_same_width']));
$this->setOrientation((string) $_REQUEST['eps_orientation']);
$this->diagram->setTitle(
sprintf(
__('Schema of the %s database - Page %s'),
$this->db,
$this->pageNumber
)
);
$this->diagram->setAuthor('phpMyAdmin ' . Version::VERSION);
$this->diagram->setDate(date('j F Y, g:i a'));
$this->diagram->setOrientation($this->orientation);
$this->diagram->setFont('Verdana', 10);
$alltables = $this->getTablesFromRequest();
foreach ($alltables as $table) {
if (! isset($this->tables[$table])) {
$this->tables[$table] = new TableStatsEps(
$this->diagram,
$this->db,
$table,
$this->diagram->getFont(),
$this->diagram->getFontSize(),
$this->pageNumber,
$this->tablewidth,
$this->showKeys,
$this->tableDimension,
$this->offline
);
}
if (! $this->sameWide) {
continue;
}
$this->tables[$table]->width = $this->tablewidth;
}
$seen_a_relation = false;
foreach ($alltables as $one_table) {
$exist_rel = $this->relation->getForeigners($this->db, $one_table, '', 'both');
if (! $exist_rel) {
continue;
}
$seen_a_relation = true;
foreach ($exist_rel as $master_field => $rel) {
/* put the foreign table on the schema only if selected
* by the user
* (do not use array_search() because we would have to
* to do a === false and this is not PHP3 compatible)
*/
if ($master_field !== 'foreign_keys_data') {
if (in_array($rel['foreign_table'], $alltables)) {
$this->addRelation(
$one_table,
$this->diagram->getFont(),
$this->diagram->getFontSize(),
$master_field,
$rel['foreign_table'],
$rel['foreign_field'],
$this->tableDimension
);
}
continue;
}
foreach ($rel as $one_key) {
if (! in_array($one_key['ref_table_name'], $alltables)) {
continue;
}
foreach ($one_key['index_list'] as $index => $one_field) {
$this->addRelation(
$one_table,
$this->diagram->getFont(),
$this->diagram->getFontSize(),
$one_field,
$one_key['ref_table_name'],
$one_key['ref_index_list'][$index],
$this->tableDimension
);
}
}
}
}
if ($seen_a_relation) {
$this->drawRelations();
}
$this->drawTables();
$this->diagram->endEpsDoc();
}
/**
* Output Eps Document for download
*/
public function showOutput(): void
{
$this->diagram->showOutput($this->getFileName('.eps'));
}
/**
* Defines relation objects
*
* @see _setMinMax
* @see TableStatsEps::__construct()
* @see PhpMyAdmin\Plugins\Schema\Eps\RelationStatsEps::__construct()
*
* @param string $masterTable The master table name
* @param string $font The font
* @param int $fontSize The font size
* @param string $masterField The relation field in the master table
* @param string $foreignTable The foreign table name
* @param string $foreignField The relation field in the foreign table
* @param bool $tableDimension Whether to display table position or not
*/
private function addRelation(
$masterTable,
$font,
$fontSize,
$masterField,
$foreignTable,
$foreignField,
$tableDimension
): void {
if (! isset($this->tables[$masterTable])) {
$this->tables[$masterTable] = new TableStatsEps(
$this->diagram,
$this->db,
$masterTable,
$font,
$fontSize,
$this->pageNumber,
$this->tablewidth,
false,
$tableDimension
);
}
if (! isset($this->tables[$foreignTable])) {
$this->tables[$foreignTable] = new TableStatsEps(
$this->diagram,
$this->db,
$foreignTable,
$font,
$fontSize,
$this->pageNumber,
$this->tablewidth,
false,
$tableDimension
);
}
$this->relations[] = new RelationStatsEps(
$this->diagram,
$this->tables[$masterTable],
$masterField,
$this->tables[$foreignTable],
$foreignField
);
}
/**
* Draws relation arrows and lines connects master table's master field to
* foreign table's foreign field
*
* @see RelationStatsEps::relationDraw()
*/
private function drawRelations(): void
{
foreach ($this->relations as $relation) {
$relation->relationDraw();
}
}
/**
* Draws tables
*
* @see TableStatsEps::Table_Stats_tableDraw()
*/
private function drawTables(): void
{
foreach ($this->tables as $table) {
$table->tableDraw($this->showColor);
}
}
}

View file

@ -1,96 +0,0 @@
<?php
/**
* Contains PhpMyAdmin\Plugins\Schema\Eps\RelationStatsEps class
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Schema\Eps;
use PhpMyAdmin\Plugins\Schema\RelationStats;
use function sqrt;
/**
* Relation preferences/statistics
*
* This class fetches the table master and foreign fields positions
* and helps in generating the Table references and then connects
* master table's master field to foreign table's foreign key
* in EPS document.
*
* @see Eps
*/
class RelationStatsEps extends RelationStats
{
/**
* @param Eps $diagram The EPS diagram
* @param string $master_table The master table name
* @param string $master_field The relation field in the master table
* @param string $foreign_table The foreign table name
* @param string $foreign_field The relation field in the foreign table
*/
public function __construct(
$diagram,
$master_table,
$master_field,
$foreign_table,
$foreign_field
) {
$this->wTick = 10;
parent::__construct($diagram, $master_table, $master_field, $foreign_table, $foreign_field);
$this->ySrc += 10;
$this->yDest += 10;
}
/**
* draws relation links and arrows
* shows foreign key relations
*
* @see Eps
*/
public function relationDraw(): void
{
// draw a line like -- to foreign field
$this->diagram->line($this->xSrc, $this->ySrc, $this->xSrc + $this->srcDir * $this->wTick, $this->ySrc, 1);
// draw a line like -- to master field
$this->diagram->line($this->xDest + $this->destDir * $this->wTick, $this->yDest, $this->xDest, $this->yDest, 1);
// draw a line that connects to master field line and foreign field line
$this->diagram->line(
$this->xSrc + $this->srcDir * $this->wTick,
$this->ySrc,
$this->xDest + $this->destDir * $this->wTick,
$this->yDest,
1
);
$root2 = 2 * sqrt(2);
$this->diagram->line(
$this->xSrc + $this->srcDir * $this->wTick * 0.75,
$this->ySrc,
$this->xSrc + $this->srcDir * (0.75 - 1 / $root2) * $this->wTick,
$this->ySrc + $this->wTick / $root2,
1
);
$this->diagram->line(
$this->xSrc + $this->srcDir * $this->wTick * 0.75,
$this->ySrc,
$this->xSrc + $this->srcDir * (0.75 - 1 / $root2) * $this->wTick,
$this->ySrc - $this->wTick / $root2,
1
);
$this->diagram->line(
$this->xDest + $this->destDir * $this->wTick / 2,
$this->yDest,
$this->xDest + $this->destDir * (0.5 + 1 / $root2) * $this->wTick,
$this->yDest + $this->wTick / $root2,
1
);
$this->diagram->line(
$this->xDest + $this->destDir * $this->wTick / 2,
$this->yDest,
$this->xDest + $this->destDir * (0.5 + 1 / $root2) * $this->wTick,
$this->yDest - $this->wTick / $root2,
1
);
}
}

View file

@ -1,148 +0,0 @@
<?php
/**
* Contains PhpMyAdmin\Plugins\Schema\Eps\TableStatsEps class
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Schema\Eps;
use PhpMyAdmin\Plugins\Schema\ExportRelationSchema;
use PhpMyAdmin\Plugins\Schema\TableStats;
use function __;
use function count;
use function max;
use function sprintf;
/**
* Table preferences/statistics
*
* This class preserves the table co-ordinates,fields
* and helps in drawing/generating the Tables in EPS.
*
* @see Eps
*
* @property Eps $diagram
*/
class TableStatsEps extends TableStats
{
/** @var int */
public $height;
/** @var int */
public $currentCell = 0;
/**
* @see Eps
* @see TableStatsEps::setWidthTable
* @see TableStatsEps::setHeightTable
*
* @param Eps $diagram The EPS diagram
* @param string $db The database name
* @param string $tableName The table name
* @param string $font The font name
* @param int $fontSize The font size
* @param int $pageNumber Page number
* @param int $same_wide_width The max width among tables
* @param bool $showKeys Whether to display keys or not
* @param bool $tableDimension Whether to display table position or not
* @param bool $offline Whether the coordinates are sent
* from the browser
*/
public function __construct(
$diagram,
$db,
$tableName,
$font,
$fontSize,
$pageNumber,
&$same_wide_width,
$showKeys = false,
$tableDimension = false,
$offline = false
) {
parent::__construct($diagram, $db, $pageNumber, $tableName, $showKeys, $tableDimension, $offline);
// height and width
$this->setHeightTable($fontSize);
// setWidth must me after setHeight, because title
// can include table height which changes table width
$this->setWidthTable($font, $fontSize);
if ($same_wide_width >= $this->width) {
return;
}
$same_wide_width = $this->width;
}
/**
* Displays an error when the table cannot be found.
*/
protected function showMissingTableError(): void
{
ExportRelationSchema::dieSchema(
$this->pageNumber,
'EPS',
sprintf(__('The %s table doesn\'t exist!'), $this->tableName)
);
}
/**
* Sets the width of the table
*
* @see Eps
*
* @param string $font The font name
* @param int $fontSize The font size
*/
private function setWidthTable($font, $fontSize): void
{
foreach ($this->fields as $field) {
$this->width = max(
$this->width,
$this->font->getStringWidth($field, $font, (int) $fontSize)
);
}
$this->width += $this->font->getStringWidth(' ', $font, (int) $fontSize);
/*
* it is unknown what value must be added, because
* table title is affected by the table width value
*/
while ($this->width < $this->font->getStringWidth($this->getTitle(), $font, (int) $fontSize)) {
$this->width += 7;
}
}
/**
* Sets the height of the table
*
* @param int $fontSize The font size
*/
private function setHeightTable($fontSize): void
{
$this->heightCell = $fontSize + 4;
$this->height = (count($this->fields) + 1) * $this->heightCell;
}
/**
* Draw the table
*
* @see Eps
* @see Eps::line
* @see Eps::rect
*
* @param bool $showColor Whether to display color
*/
public function tableDraw($showColor): void
{
$this->diagram->rect($this->x, $this->y + 12, $this->width, $this->heightCell, 1);
$this->diagram->showXY($this->getTitle(), $this->x + 5, $this->y + 14);
foreach ($this->fields as $field) {
$this->currentCell += $this->heightCell;
$this->diagram->rect($this->x, $this->y + 12 + $this->currentCell, $this->width, $this->heightCell, 1);
$this->diagram->showXY($field, $this->x + 5, $this->y + 14 + $this->currentCell);
}
}
}

View file

@ -1,296 +0,0 @@
<?php
/**
* Contains PhpMyAdmin\Plugins\Schema\ExportRelationSchema class which is
* inherited by all schema classes.
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Schema;
use PhpMyAdmin\ConfigStorage\Relation;
use PhpMyAdmin\Url;
use PhpMyAdmin\Util;
use function __;
use function htmlspecialchars;
use function rawurldecode;
/**
* This class is inherited by all schema classes
* It contains those methods which are common in them
* it works like factory pattern
*/
class ExportRelationSchema
{
/** @var string */
protected $db;
/** @var Dia\Dia|Eps\Eps|Pdf\Pdf|Svg\Svg|null */
protected $diagram;
/** @var bool */
protected $showColor = false;
/** @var bool */
protected $tableDimension = false;
/** @var bool */
protected $sameWide = false;
/** @var bool */
protected $showKeys = false;
/** @var string */
protected $orientation = 'L';
/** @var string */
protected $paper = 'A4';
/** @var int */
protected $pageNumber = 0;
/** @var bool */
protected $offline = false;
/** @var Relation */
protected $relation;
/**
* @param string $db database name
* @param Pdf\Pdf|Svg\Svg|Eps\Eps|Dia\Dia|null $diagram schema diagram
*/
public function __construct($db, $diagram)
{
global $dbi;
$this->db = $db;
$this->diagram = $diagram;
$this->setPageNumber((int) $_REQUEST['page_number']);
$this->setOffline(isset($_REQUEST['offline_export']));
$this->relation = new Relation($dbi);
}
/**
* Set Page Number
*
* @param int $value Page Number of the document to be created
*/
public function setPageNumber(int $value): void
{
$this->pageNumber = $value;
}
/**
* Returns the schema page number
*
* @return int schema page number
*/
public function getPageNumber()
{
return $this->pageNumber;
}
/**
* Sets showColor
*
* @param bool $value whether to show colors
*/
public function setShowColor(bool $value): void
{
$this->showColor = $value;
}
/**
* Returns whether to show colors
*/
public function isShowColor(): bool
{
return $this->showColor;
}
/**
* Set Table Dimension
*
* @param bool $value show table co-ordinates or not
*/
public function setTableDimension(bool $value): void
{
$this->tableDimension = $value;
}
/**
* Returns whether to show table dimensions
*/
public function isTableDimension(): bool
{
return $this->tableDimension;
}
/**
* Set same width of All Tables
*
* @param bool $value set same width of all tables or not
*/
public function setAllTablesSameWidth(bool $value): void
{
$this->sameWide = $value;
}
/**
* Returns whether to use same width for all tables or not
*/
public function isAllTableSameWidth(): bool
{
return $this->sameWide;
}
/**
* Set Show only keys
*
* @param bool $value show only keys or not
*/
public function setShowKeys(bool $value): void
{
$this->showKeys = $value;
}
/**
* Returns whether to show keys
*/
public function isShowKeys(): bool
{
return $this->showKeys;
}
/**
* Set Orientation
*
* @param string $value Orientation will be portrait or landscape
*/
public function setOrientation(string $value): void
{
$this->orientation = $value === 'P' ? 'P' : 'L';
}
/**
* Returns orientation
*
* @return string orientation
*/
public function getOrientation()
{
return $this->orientation;
}
/**
* Set type of paper
*
* @param string $value paper type can be A4 etc
*/
public function setPaper(string $value): void
{
$this->paper = $value;
}
/**
* Returns the paper size
*
* @return string paper size
*/
public function getPaper()
{
return $this->paper;
}
/**
* Set whether the document is generated from client side DB
*
* @param bool $value offline or not
*/
public function setOffline(bool $value): void
{
$this->offline = $value;
}
/**
* Returns whether the client side database is used
*/
public function isOffline(): bool
{
return $this->offline;
}
/**
* Get the table names from the request
*
* @return string[] an array of table names
*/
protected function getTablesFromRequest(): array
{
$tables = [];
if (isset($_POST['t_tbl'])) {
foreach ($_POST['t_tbl'] as $table) {
$tables[] = rawurldecode($table);
}
}
return $tables;
}
/**
* Returns the file name
*
* @param string $extension file extension
*
* @return string file name
*/
protected function getFileName($extension): string
{
global $dbi;
$pdfFeature = $this->relation->getRelationParameters()->pdfFeature;
$filename = $this->db . $extension;
// Get the name of this page to use as filename
if ($this->pageNumber != -1 && ! $this->offline && $pdfFeature !== null) {
$_name_sql = 'SELECT page_descr FROM '
. Util::backquote($pdfFeature->database) . '.'
. Util::backquote($pdfFeature->pdfPages)
. ' WHERE page_nr = ' . $this->pageNumber;
$_name_rs = $dbi->queryAsControlUser($_name_sql);
$_name_row = $_name_rs->fetchRow();
$filename = $_name_row[0] . $extension;
}
return $filename;
}
/**
* Displays an error message
*
* @param int $pageNumber ID of the chosen page
* @param string $type Schema Type
* @param string $error_message The error message
*/
public static function dieSchema($pageNumber, $type = '', $error_message = ''): void
{
echo '<p><strong>' , __('SCHEMA ERROR: ') , $type , '</strong></p>' , "\n";
if (! empty($error_message)) {
$error_message = htmlspecialchars($error_message);
}
echo '<p>' , "\n";
echo ' ' , $error_message , "\n";
echo '</p>' , "\n";
echo '<a href="';
echo Url::getFromRoute('/database/designer', [
'db' => $GLOBALS['db'],
'server' => $GLOBALS['server'],
'page' => $pageNumber,
]);
echo '">' . __('Back') . '</a>';
echo "\n";
exit;
}
}

View file

@ -1,435 +0,0 @@
<?php
/**
* PDF schema handling
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Schema\Pdf;
use PhpMyAdmin\ConfigStorage\Relation;
use PhpMyAdmin\Pdf as PdfLib;
use PhpMyAdmin\Util;
use function __;
use function count;
use function getcwd;
use function max;
use function mb_ord;
use function str_replace;
use function strlen;
use function ucfirst;
// phpcs:disable PSR1.Files.SideEffects
/**
* block attempts to directly run this script
*/
if (getcwd() == __DIR__) {
die('Attack stopped');
}
// phpcs:enable
/**
* Extends the "TCPDF" class and helps
* in developing the structure of PDF Schema Export
*
* @see TCPDF
*/
class Pdf extends PdfLib
{
/** @var int|float */
public $xMin = 0;
/** @var int|float */
public $yMin = 0;
/** @var int|float */
public $leftMargin = 10;
/** @var int|float */
public $topMargin = 10;
/** @var int|float */
public $scale = 1;
/** @var array */
public $customLinks = [];
/** @var array */
public $widths = [];
/** @var float */
public $cMargin = 0;
/** @var string */
private $ff = PdfLib::PMA_PDF_FONT;
/** @var bool */
private $offline = false;
/** @var int */
private $pageNumber;
/** @var bool */
private $withDoc;
/** @var string */
private $db;
/** @var Relation */
private $relation;
/**
* Constructs PDF for schema export.
*
* @param string $orientation page orientation
* @param string $unit unit
* @param string $paper the format used for pages
* @param int $pageNumber schema page number that is being exported
* @param bool $withDoc with document dictionary
* @param string $db the database name
*/
public function __construct(
$orientation,
$unit,
$paper,
$pageNumber,
$withDoc,
$db
) {
global $dbi;
parent::__construct($orientation, $unit, $paper);
$this->pageNumber = $pageNumber;
$this->withDoc = $withDoc;
$this->db = $db;
$this->relation = new Relation($dbi);
}
/**
* Sets the value for margins
*
* @param float $c_margin margin
*/
public function setCMargin($c_margin): void
{
$this->cMargin = $c_margin;
}
/**
* Sets the scaling factor, defines minimum coordinates and margins
*
* @param float|int $scale The scaling factor
* @param float|int $xMin The minimum X coordinate
* @param float|int $yMin The minimum Y coordinate
* @param float|int $leftMargin The left margin
* @param float|int $topMargin The top margin
*/
public function setScale(
$scale = 1,
$xMin = 0,
$yMin = 0,
$leftMargin = -1,
$topMargin = -1
): void {
$this->scale = $scale;
$this->xMin = $xMin;
$this->yMin = $yMin;
if ($this->leftMargin != -1) {
$this->leftMargin = $leftMargin;
}
if ($this->topMargin == -1) {
return;
}
$this->topMargin = $topMargin;
}
/**
* Outputs a scaled cell
*
* @see TCPDF::Cell()
*
* @param float|int $w The cell width
* @param float|int $h The cell height
* @param string $txt The text to output
* @param mixed $border Whether to add borders or not
* @param int $ln Where to put the cursor once the output is done
* @param string $align Align mode
* @param bool $fill Whether to fill the cell with a color or not
* @param string $link Link
*/
public function cellScale(
$w,
$h = 0,
$txt = '',
$border = 0,
$ln = 0,
$align = '',
bool $fill = false,
$link = ''
): void {
$h /= $this->scale;
$w /= $this->scale;
$this->Cell($w, $h, $txt, $border, $ln, $align, $fill, $link);
}
/**
* Draws a scaled line
*
* @see TCPDF::Line()
*
* @param float $x1 The horizontal position of the starting point
* @param float $y1 The vertical position of the starting point
* @param float $x2 The horizontal position of the ending point
* @param float $y2 The vertical position of the ending point
*/
public function lineScale($x1, $y1, $x2, $y2): void
{
$x1 = ($x1 - $this->xMin) / $this->scale + $this->leftMargin;
$y1 = ($y1 - $this->yMin) / $this->scale + $this->topMargin;
$x2 = ($x2 - $this->xMin) / $this->scale + $this->leftMargin;
$y2 = ($y2 - $this->yMin) / $this->scale + $this->topMargin;
$this->Line($x1, $y1, $x2, $y2);
}
/**
* Sets x and y scaled positions
*
* @see TCPDF::setXY()
*
* @param float $x The x position
* @param float $y The y position
*/
public function setXyScale($x, $y): void
{
$x = ($x - $this->xMin) / $this->scale + $this->leftMargin;
$y = ($y - $this->yMin) / $this->scale + $this->topMargin;
$this->setXY($x, $y);
}
/**
* Sets the X scaled positions
*
* @see TCPDF::setX()
*
* @param float $x The x position
*/
public function setXScale($x): void
{
$x = ($x - $this->xMin) / $this->scale + $this->leftMargin;
$this->setX($x);
}
/**
* Sets the scaled font size
*
* @see TCPDF::setFontSize()
*
* @param float $size The font size (in points)
*/
public function setFontSizeScale($size): void
{
// Set font size in points
$size /= $this->scale;
$this->setFontSize($size);
}
/**
* Sets the scaled line width
*
* @see TCPDF::setLineWidth()
*
* @param float $width The line width
*/
public function setLineWidthScale($width): void
{
$width /= $this->scale;
$this->setLineWidth($width);
}
/**
* This method is used to render the page header.
*
* @see TCPDF::Header()
*/
// phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps
public function Header(): void
{
global $dbi;
// We only show this if we find something in the new pdf_pages table
// This function must be named "Header" to work with the TCPDF library
if (! $this->withDoc) {
return;
}
$pdfFeature = $this->relation->getRelationParameters()->pdfFeature;
if ($this->offline || $this->pageNumber == -1 || $pdfFeature === null) {
$pg_name = __('PDF export page');
} else {
$test_query = 'SELECT * FROM '
. Util::backquote($pdfFeature->database) . '.'
. Util::backquote($pdfFeature->pdfPages)
. ' WHERE db_name = \'' . $dbi->escapeString($this->db)
. '\' AND page_nr = \'' . $this->pageNumber . '\'';
$test_rs = $dbi->queryAsControlUser($test_query);
$pageDesc = (string) $test_rs->fetchValue('page_descr');
$pg_name = ucfirst($pageDesc);
}
$this->setFont($this->ff, 'B', 14);
$this->Cell(0, 6, $pg_name, 'B', 1, 'C');
$this->setFont($this->ff, '');
$this->Ln();
}
/**
* This function must be named "Footer" to work with the TCPDF library
*
* @see PDF::Footer()
*/
// phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps
public function Footer(): void
{
if (! $this->withDoc) {
return;
}
parent::Footer();
}
/**
* Sets widths
*
* @param array $w array of widths
*/
public function setWidths(array $w): void
{
// column widths
$this->widths = $w;
}
/**
* Generates table row.
*
* @param array $data Data for table
* @param array $links Links for table cells
*/
public function row(array $data, array $links): void
{
// line height
$nb = 0;
$data_cnt = count($data);
for ($i = 0; $i < $data_cnt; $i++) {
$nb = max($nb, $this->numLines($this->widths[$i], $data[$i]));
}
// phpcs:ignore Squiz.NamingConventions.ValidVariableName.MemberNotCamelCaps
$il = $this->FontSize;
$h = ($il + 1) * $nb;
// page break if necessary
$this->checkPageBreak($h);
// draw the cells
$data_cnt = count($data);
for ($i = 0; $i < $data_cnt; $i++) {
$w = $this->widths[$i];
// save current position
$x = $this->GetX();
$y = $this->GetY();
// draw the border
$this->Rect($x, $y, $w, $h);
if (isset($links[$i])) {
$this->Link($x, $y, $w, $h, $links[$i]);
}
// print text
$this->MultiCell($w, $il + 1, $data[$i], 0, 'L');
// go to right side
$this->setXY($x + $w, $y);
}
// go to line
$this->Ln($h);
}
/**
* Compute number of lines used by a multicell of width w
*
* @param int $w width
* @param string $txt text
*
* @return int
*/
public function numLines($w, $txt)
{
// phpcs:ignore Squiz.NamingConventions.ValidVariableName.MemberNotCamelCaps
$cw = &$this->CurrentFont['cw'];
if ($w == 0) {
$w = $this->w - $this->rMargin - $this->x;
}
// phpcs:ignore Squiz.NamingConventions.ValidVariableName.MemberNotCamelCaps
$wmax = ($w - 2 * $this->cMargin) * 1000 / $this->FontSize;
$s = str_replace("\r", '', $txt);
$nb = strlen($s);
if ($nb > 0 && $s[$nb - 1] == "\n") {
$nb--;
}
$sep = -1;
$i = 0;
$j = 0;
$l = 0;
$nl = 1;
while ($i < $nb) {
$c = $s[$i];
if ($c == "\n") {
$i++;
$sep = -1;
$j = $i;
$l = 0;
$nl++;
continue;
}
if ($c === ' ') {
$sep = $i;
}
$l += $cw[mb_ord($c)] ?? 0;
if ($l > $wmax) {
if ($sep == -1) {
if ($i == $j) {
$i++;
}
} else {
$i = $sep + 1;
}
$sep = -1;
$j = $i;
$l = 0;
$nl++;
} else {
$i++;
}
}
return $nl;
}
/**
* Set whether the document is generated from client side DB
*
* @param bool $value whether offline
*/
public function setOffline($value): void
{
$this->offline = $value;
}
}

View file

@ -1,781 +0,0 @@
<?php
/**
* PDF schema handling
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Schema\Pdf;
use PhpMyAdmin\Pdf as PdfLib;
use PhpMyAdmin\Plugins\Schema\ExportRelationSchema;
use PhpMyAdmin\Transformations;
use PhpMyAdmin\Util;
use function __;
use function ceil;
use function getcwd;
use function in_array;
use function intval;
use function max;
use function min;
use function rsort;
use function sort;
use function sprintf;
use function str_replace;
use function strtotime;
// phpcs:disable PSR1.Files.SideEffects
/**
* block attempts to directly run this script
*/
if (getcwd() == __DIR__) {
die('Attack stopped');
}
// phpcs:enable
/**
* Pdf Relation Schema Class
*
* Purpose of this class is to generate the PDF Document. PDF is widely
* used format for documenting text,fonts,images and 3d vector graphics.
*
* This class inherits ExportRelationSchema class has common functionality added
* to this class
*
* @property Pdf $diagram
*/
class PdfRelationSchema extends ExportRelationSchema
{
/** @var bool */
private $showGrid = false;
/** @var bool */
private $withDoc = false;
/** @var string */
private $tableOrder = '';
/** @var TableStatsPdf[] */
private $tables = [];
/** @var string */
private $ff = PdfLib::PMA_PDF_FONT;
/** @var int|float */
private $xMax = 0;
/** @var int|float */
private $yMax = 0;
/** @var float|int */
private $scale;
/** @var int|float */
private $xMin = 100000;
/** @var int|float */
private $yMin = 100000;
/** @var int */
private $topMargin = 10;
/** @var int */
private $bottomMargin = 10;
/** @var int */
private $leftMargin = 10;
/** @var int */
private $rightMargin = 10;
/** @var int */
private $tablewidth = 0;
/** @var RelationStatsPdf[] */
protected $relations = [];
/** @var Transformations */
private $transformations;
/**
* @see Schema\Pdf
*
* @param string $db database name
*/
public function __construct($db)
{
$this->transformations = new Transformations();
$this->setShowGrid(isset($_REQUEST['pdf_show_grid']));
$this->setShowColor(isset($_REQUEST['pdf_show_color']));
$this->setShowKeys(isset($_REQUEST['pdf_show_keys']));
$this->setTableDimension(isset($_REQUEST['pdf_show_table_dimension']));
$this->setAllTablesSameWidth(isset($_REQUEST['pdf_all_tables_same_width']));
$this->setWithDataDictionary(isset($_REQUEST['pdf_with_doc']));
$this->setTableOrder($_REQUEST['pdf_table_order']);
$this->setOrientation((string) $_REQUEST['pdf_orientation']);
$this->setPaper((string) $_REQUEST['pdf_paper']);
// Initializes a new document
parent::__construct(
$db,
new Pdf(
$this->orientation,
'mm',
$this->paper,
$this->pageNumber,
$this->withDoc,
$db
)
);
$this->diagram->setTitle(
sprintf(
__('Schema of the %s database'),
$this->db
)
);
$this->diagram->setCMargin(0);
$this->diagram->Open();
$this->diagram->setAutoPageBreak(true);
$this->diagram->setOffline($this->offline);
$alltables = $this->getTablesFromRequest();
if ($this->getTableOrder() === 'name_asc') {
sort($alltables);
} elseif ($this->getTableOrder() === 'name_desc') {
rsort($alltables);
}
if ($this->withDoc) {
$this->diagram->setAutoPageBreak(true, 15);
$this->diagram->setCMargin(1);
$this->dataDictionaryDoc($alltables);
$this->diagram->setAutoPageBreak(true);
$this->diagram->setCMargin(0);
}
$this->diagram->AddPage();
if ($this->withDoc) {
$this->diagram->setLink($this->diagram->customLinks['RT']['-'], -1);
$this->diagram->Bookmark(__('Relational schema'));
$this->diagram->setAlias('{00}', $this->diagram->PageNo());
$this->topMargin = 28;
$this->bottomMargin = 28;
}
/* snip */
foreach ($alltables as $table) {
if (! isset($this->tables[$table])) {
$this->tables[$table] = new TableStatsPdf(
$this->diagram,
$this->db,
$table,
null,
$this->pageNumber,
$this->tablewidth,
$this->showKeys,
$this->tableDimension,
$this->offline
);
}
if ($this->sameWide) {
$this->tables[$table]->width = $this->tablewidth;
}
$this->setMinMax($this->tables[$table]);
}
// Defines the scale factor
$innerWidth = $this->diagram->getPageWidth() - $this->rightMargin
- $this->leftMargin;
$innerHeight = $this->diagram->getPageHeight() - $this->topMargin
- $this->bottomMargin;
$this->scale = ceil(
max(
($this->xMax - $this->xMin) / $innerWidth,
($this->yMax - $this->yMin) / $innerHeight
) * 100
) / 100;
$this->diagram->setScale($this->scale, $this->xMin, $this->yMin, $this->leftMargin, $this->topMargin);
// Builds and save the PDF document
$this->diagram->setLineWidthScale(0.1);
if ($this->showGrid) {
$this->diagram->setFontSize(10);
$this->strokeGrid();
}
$this->diagram->setFontSizeScale(14);
// previous logic was checking master tables and foreign tables
// but I think that looping on every table of the pdf page as a master
// and finding its foreigns is OK (then we can support innodb)
$seen_a_relation = false;
foreach ($alltables as $one_table) {
$exist_rel = $this->relation->getForeigners($this->db, $one_table, '', 'both');
if (! $exist_rel) {
continue;
}
$seen_a_relation = true;
foreach ($exist_rel as $master_field => $rel) {
// put the foreign table on the schema only if selected
// by the user
// (do not use array_search() because we would have to
// to do a === false and this is not PHP3 compatible)
if ($master_field !== 'foreign_keys_data') {
if (in_array($rel['foreign_table'], $alltables)) {
$this->addRelation($one_table, $master_field, $rel['foreign_table'], $rel['foreign_field']);
}
continue;
}
foreach ($rel as $one_key) {
if (! in_array($one_key['ref_table_name'], $alltables)) {
continue;
}
foreach ($one_key['index_list'] as $index => $one_field) {
$this->addRelation(
$one_table,
$one_field,
$one_key['ref_table_name'],
$one_key['ref_index_list'][$index]
);
}
}
}
}
if ($seen_a_relation) {
$this->drawRelations();
}
$this->drawTables();
}
/**
* Set Show Grid
*
* @param bool $value show grid of the document or not
*/
public function setShowGrid($value): void
{
$this->showGrid = $value;
}
/**
* Returns whether to show grid
*/
public function isShowGrid(): bool
{
return $this->showGrid;
}
/**
* Set Data Dictionary
*
* @param bool $value show selected database data dictionary or not
*/
public function setWithDataDictionary($value): void
{
$this->withDoc = $value;
}
/**
* Return whether to show selected database data dictionary or not
*/
public function isWithDataDictionary(): bool
{
return $this->withDoc;
}
/**
* Sets the order of the table in data dictionary
*
* @param string $value table order
*/
public function setTableOrder($value): void
{
$this->tableOrder = $value;
}
/**
* Returns the order of the table in data dictionary
*
* @return string table order
*/
public function getTableOrder()
{
return $this->tableOrder;
}
/**
* Output Pdf Document for download
*/
public function showOutput(): void
{
$this->diagram->download($this->getFileName('.pdf'));
}
/**
* Sets X and Y minimum and maximum for a table cell
*
* @param TableStatsPdf $table The table name of which sets XY co-ordinates
*/
private function setMinMax($table): void
{
$this->xMax = max($this->xMax, $table->x + $table->width);
$this->yMax = max($this->yMax, $table->y + $table->height);
$this->xMin = min($this->xMin, $table->x);
$this->yMin = min($this->yMin, $table->y);
}
/**
* Defines relation objects
*
* @see setMinMax
*
* @param string $masterTable The master table name
* @param string $masterField The relation field in the master table
* @param string $foreignTable The foreign table name
* @param string $foreignField The relation field in the foreign table
*/
private function addRelation(
$masterTable,
$masterField,
$foreignTable,
$foreignField
): void {
if (! isset($this->tables[$masterTable])) {
$this->tables[$masterTable] = new TableStatsPdf(
$this->diagram,
$this->db,
$masterTable,
null,
$this->pageNumber,
$this->tablewidth,
$this->showKeys,
$this->tableDimension
);
$this->setMinMax($this->tables[$masterTable]);
}
if (! isset($this->tables[$foreignTable])) {
$this->tables[$foreignTable] = new TableStatsPdf(
$this->diagram,
$this->db,
$foreignTable,
null,
$this->pageNumber,
$this->tablewidth,
$this->showKeys,
$this->tableDimension
);
$this->setMinMax($this->tables[$foreignTable]);
}
$this->relations[] = new RelationStatsPdf(
$this->diagram,
$this->tables[$masterTable],
$masterField,
$this->tables[$foreignTable],
$foreignField
);
}
/**
* Draws the grid
*
* @see PMA_Schema_PDF
*/
private function strokeGrid(): void
{
$gridSize = 10;
$labelHeight = 4;
$labelWidth = 5;
if ($this->withDoc) {
$topSpace = 6;
$bottomSpace = 15;
} else {
$topSpace = 0;
$bottomSpace = 0;
}
$this->diagram->setMargins(0, 0);
$this->diagram->setDrawColor(200, 200, 200);
// Draws horizontal lines
$innerHeight = $this->diagram->getPageHeight() - $topSpace - $bottomSpace;
for ($l = 0, $size = intval($innerHeight / $gridSize); $l <= $size; $l++) {
$this->diagram->line(
0,
$l * $gridSize + $topSpace,
$this->diagram->getPageWidth(),
$l * $gridSize + $topSpace
);
// Avoid duplicates
if ($l <= 0 || $l > intval(($innerHeight - $labelHeight) / $gridSize)) {
continue;
}
$this->diagram->setXY(0, $l * $gridSize + $topSpace);
$label = (string) sprintf(
'%.0f',
($l * $gridSize + $topSpace - $this->topMargin)
* $this->scale + $this->yMin
);
$this->diagram->Cell($labelWidth, $labelHeight, ' ' . $label);
}
// Draws vertical lines
for ($j = 0, $size = intval($this->diagram->getPageWidth() / $gridSize); $j <= $size; $j++) {
$this->diagram->line(
$j * $gridSize,
$topSpace,
$j * $gridSize,
$this->diagram->getPageHeight() - $bottomSpace
);
$this->diagram->setXY($j * $gridSize, $topSpace);
$label = (string) sprintf('%.0f', ($j * $gridSize - $this->leftMargin) * $this->scale + $this->xMin);
$this->diagram->Cell($labelWidth, $labelHeight, $label);
}
}
/**
* Draws relation arrows
*
* @see Relation_Stats_Pdf::relationdraw()
*/
private function drawRelations(): void
{
$i = 0;
foreach ($this->relations as $relation) {
$relation->relationDraw($this->showColor, $i);
$i++;
}
}
/**
* Draws tables
*
* @see TableStatsPdf::tableDraw()
*/
private function drawTables(): void
{
foreach ($this->tables as $table) {
$table->tableDraw(null, $this->withDoc, $this->showColor);
}
}
/**
* Generates data dictionary pages.
*
* @param array $alltables Tables to document.
*/
public function dataDictionaryDoc(array $alltables): void
{
global $dbi;
// TOC
$this->diagram->AddPage($this->orientation);
$this->diagram->Cell(0, 9, __('Table of contents'), 1, 0, 'C');
$this->diagram->Ln(15);
$i = 1;
foreach ($alltables as $table) {
$this->diagram->customLinks['doc'][$table]['-'] = $this->diagram->AddLink();
$this->diagram->setX(10);
// $this->diagram->Ln(1);
$this->diagram->Cell(
0,
6,
__('Page number:') . ' {' . sprintf('%02d', $i) . '}',
0,
0,
'R',
false,
$this->diagram->customLinks['doc'][$table]['-']
);
$this->diagram->setX(10);
$this->diagram->Cell(
0,
6,
$i . ' ' . $table,
0,
1,
'L',
false,
$this->diagram->customLinks['doc'][$table]['-']
);
// $this->diagram->Ln(1);
$fields = $dbi->getColumns($this->db, $table);
foreach ($fields as $row) {
$this->diagram->setX(20);
$field_name = $row['Field'];
$this->diagram->customLinks['doc'][$table][$field_name] = $this->diagram->AddLink();
}
$i++;
}
$this->diagram->customLinks['RT']['-'] = $this->diagram->AddLink();
$this->diagram->setX(10);
$this->diagram->Cell(
0,
6,
__('Page number:') . ' {00}',
0,
0,
'R',
false,
$this->diagram->customLinks['RT']['-']
);
$this->diagram->setX(10);
$this->diagram->Cell(
0,
6,
$i . ' ' . __('Relational schema'),
0,
1,
'L',
false,
$this->diagram->customLinks['RT']['-']
);
$z = 0;
foreach ($alltables as $table) {
$z++;
$this->diagram->setAutoPageBreak(true, 15);
$this->diagram->AddPage($this->orientation);
$this->diagram->Bookmark($table);
$this->diagram->setAlias(
'{' . sprintf('%02d', $z) . '}',
$this->diagram->PageNo()
);
$this->diagram->customLinks['RT'][$table]['-'] = $this->diagram->AddLink();
$this->diagram->setLink($this->diagram->customLinks['doc'][$table]['-'], -1);
$this->diagram->setFont($this->ff, 'B', 18);
$this->diagram->Cell(
0,
8,
$z . ' ' . $table,
1,
1,
'C',
false,
$this->diagram->customLinks['RT'][$table]['-']
);
$this->diagram->setFont($this->ff, '', 8);
$this->diagram->Ln();
$relationParameters = $this->relation->getRelationParameters();
$comments = $this->relation->getComments($this->db, $table);
if ($relationParameters->browserTransformationFeature !== null) {
$mime_map = $this->transformations->getMime($this->db, $table, true);
}
/**
* Gets table information
*/
$showtable = $dbi->getTable($this->db, $table)
->getStatusInfo();
$show_comment = $showtable['Comment'] ?? '';
$create_time = isset($showtable['Create_time'])
? Util::localisedDate(
strtotime($showtable['Create_time'])
)
: '';
$update_time = isset($showtable['Update_time'])
? Util::localisedDate(
strtotime($showtable['Update_time'])
)
: '';
$check_time = isset($showtable['Check_time'])
? Util::localisedDate(
strtotime($showtable['Check_time'])
)
: '';
/**
* Gets fields properties
*/
$columns = $dbi->getColumns($this->db, $table);
// Find which tables are related with the current one and write it in
// an array
$res_rel = $this->relation->getForeigners($this->db, $table);
/**
* Displays the comments of the table if MySQL >= 3.23
*/
$break = false;
if (! empty($show_comment)) {
$this->diagram->Cell(
0,
3,
__('Table comments:') . ' ' . $show_comment,
0,
1
);
$break = true;
}
if (! empty($create_time)) {
$this->diagram->Cell(
0,
3,
__('Creation:') . ' ' . $create_time,
0,
1
);
$break = true;
}
if (! empty($update_time)) {
$this->diagram->Cell(
0,
3,
__('Last update:') . ' ' . $update_time,
0,
1
);
$break = true;
}
if (! empty($check_time)) {
$this->diagram->Cell(
0,
3,
__('Last check:') . ' ' . $check_time,
0,
1
);
$break = true;
}
if ($break == true) {
$this->diagram->Cell(0, 3, '', 0, 1);
$this->diagram->Ln();
}
$this->diagram->setFont($this->ff, 'B');
if (isset($this->orientation) && $this->orientation === 'L') {
$this->diagram->Cell(25, 8, __('Column'), 1, 0, 'C');
$this->diagram->Cell(20, 8, __('Type'), 1, 0, 'C');
$this->diagram->Cell(20, 8, __('Attributes'), 1, 0, 'C');
$this->diagram->Cell(10, 8, __('Null'), 1, 0, 'C');
$this->diagram->Cell(20, 8, __('Default'), 1, 0, 'C');
$this->diagram->Cell(25, 8, __('Extra'), 1, 0, 'C');
$this->diagram->Cell(45, 8, __('Links to'), 1, 0, 'C');
if ($this->paper === 'A4') {
$comments_width = 67;
} else {
// this is really intended for 'letter'
/**
* @todo find optimal width for all formats
*/
$comments_width = 50;
}
$this->diagram->Cell($comments_width, 8, __('Comments'), 1, 0, 'C');
$this->diagram->Cell(45, 8, 'MIME', 1, 1, 'C');
$this->diagram->setWidths(
[
25,
20,
20,
10,
20,
25,
45,
$comments_width,
45,
]
);
} else {
$this->diagram->Cell(20, 8, __('Column'), 1, 0, 'C');
$this->diagram->Cell(20, 8, __('Type'), 1, 0, 'C');
$this->diagram->Cell(20, 8, __('Attributes'), 1, 0, 'C');
$this->diagram->Cell(10, 8, __('Null'), 1, 0, 'C');
$this->diagram->Cell(15, 8, __('Default'), 1, 0, 'C');
$this->diagram->Cell(15, 8, __('Extra'), 1, 0, 'C');
$this->diagram->Cell(30, 8, __('Links to'), 1, 0, 'C');
$this->diagram->Cell(30, 8, __('Comments'), 1, 0, 'C');
$this->diagram->Cell(30, 8, 'MIME', 1, 1, 'C');
$this->diagram->setWidths([20, 20, 20, 10, 15, 15, 30, 30, 30]);
}
$this->diagram->setFont($this->ff, '');
foreach ($columns as $row) {
$extracted_columnspec = Util::extractColumnSpec($row['Type']);
$type = $extracted_columnspec['print_type'];
$attribute = $extracted_columnspec['attribute'];
if (! isset($row['Default'])) {
if ($row['Null'] != '' && $row['Null'] !== 'NO') {
$row['Default'] = 'NULL';
}
}
$field_name = $row['Field'];
// $this->diagram->Ln();
$this->diagram->customLinks['RT'][$table][$field_name] = $this->diagram->AddLink();
$this->diagram->Bookmark($field_name, 1, -1);
$this->diagram->setLink($this->diagram->customLinks['doc'][$table][$field_name], -1);
$foreigner = $this->relation->searchColumnInForeigners($res_rel, $field_name);
$linksTo = '';
if ($foreigner) {
$linksTo = '-> ';
if ($foreigner['foreign_db'] != $this->db) {
$linksTo .= $foreigner['foreign_db'] . '.';
}
$linksTo .= $foreigner['foreign_table']
. '.' . $foreigner['foreign_field'];
if (isset($foreigner['on_update'])) { // not set for internal
$linksTo .= "\n" . 'ON UPDATE ' . $foreigner['on_update'];
$linksTo .= "\n" . 'ON DELETE ' . $foreigner['on_delete'];
}
}
$diagram_row = [
$field_name,
$type,
$attribute,
$row['Null'] == '' || $row['Null'] === 'NO'
? __('No')
: __('Yes'),
$row['Default'] ?? '',
$row['Extra'],
$linksTo,
$comments[$field_name] ?? '',
isset($mime_map, $mime_map[$field_name])
? str_replace('_', '/', $mime_map[$field_name]['mimetype'])
: '',
];
$links = [];
$links[0] = $this->diagram->customLinks['RT'][$table][$field_name];
if (
$foreigner
&& isset(
$this->diagram->customLinks['doc'][$foreigner['foreign_table']][$foreigner['foreign_field']]
)
) {
$foreignTable = $this->diagram->customLinks['doc'][$foreigner['foreign_table']];
$links[6] = $foreignTable[$foreigner['foreign_field']];
}
$this->diagram->row($diagram_row, $links);
}
$this->diagram->setFont($this->ff, '', 14);
}
}
}

View file

@ -1,146 +0,0 @@
<?php
/**
* Contains PhpMyAdmin\Plugins\Schema\Pdf\RelationStatsPdf class
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Schema\Pdf;
use PhpMyAdmin\Plugins\Schema\RelationStats;
use function sqrt;
/**
* Relation preferences/statistics
*
* This class fetches the table master and foreign fields positions
* and helps in generating the Table references and then connects
* master table's master field to foreign table's foreign key
* in PDF document.
*
* @see Schema\Pdf::setDrawColor
* @see Schema\Pdf::setLineWidthScale
* @see Pdf::lineScale
*/
class RelationStatsPdf extends RelationStats
{
/**
* @param Pdf $diagram The PDF diagram
* @param string $master_table The master table name
* @param string $master_field The relation field in the master table
* @param string $foreign_table The foreign table name
* @param string $foreign_field The relation field in the foreign table
*/
public function __construct(
$diagram,
$master_table,
$master_field,
$foreign_table,
$foreign_field
) {
$this->wTick = 5;
parent::__construct($diagram, $master_table, $master_field, $foreign_table, $foreign_field);
}
/**
* draws relation links and arrows shows foreign key relations
*
* @see Pdf
*
* @param bool $showColor Whether to use one color per relation or not
* @param int $i The id of the link to draw
*/
public function relationDraw($showColor, $i): void
{
if ($showColor) {
$d = $i % 6;
$j = ($i - $d) / 6;
$j %= 4;
$j++;
$case = [
[
1,
0,
0,
],
[
0,
1,
0,
],
[
0,
0,
1,
],
[
1,
1,
0,
],
[
1,
0,
1,
],
[
0,
1,
1,
],
];
[$a, $b, $c] = $case[$d];
$e = 1 - ($j - 1) / 6;
$this->diagram->setDrawColor($a * 255 * $e, $b * 255 * $e, $c * 255 * $e);
} else {
$this->diagram->setDrawColor(0);
}
$this->diagram->setLineWidthScale(0.2);
$this->diagram->lineScale($this->xSrc, $this->ySrc, $this->xSrc + $this->srcDir * $this->wTick, $this->ySrc);
$this->diagram->lineScale(
$this->xDest + $this->destDir * $this->wTick,
$this->yDest,
$this->xDest,
$this->yDest
);
$this->diagram->setLineWidthScale(0.1);
$this->diagram->lineScale(
$this->xSrc + $this->srcDir * $this->wTick,
$this->ySrc,
$this->xDest + $this->destDir * $this->wTick,
$this->yDest
);
/*
* Draws arrows ->
*/
$root2 = 2 * sqrt(2);
$this->diagram->lineScale(
$this->xSrc + $this->srcDir * $this->wTick * 0.75,
$this->ySrc,
$this->xSrc + $this->srcDir * (0.75 - 1 / $root2) * $this->wTick,
$this->ySrc + $this->wTick / $root2
);
$this->diagram->lineScale(
$this->xSrc + $this->srcDir * $this->wTick * 0.75,
$this->ySrc,
$this->xSrc + $this->srcDir * (0.75 - 1 / $root2) * $this->wTick,
$this->ySrc - $this->wTick / $root2
);
$this->diagram->lineScale(
$this->xDest + $this->destDir * $this->wTick / 2,
$this->yDest,
$this->xDest + $this->destDir * (0.5 + 1 / $root2) * $this->wTick,
$this->yDest + $this->wTick / $root2
);
$this->diagram->lineScale(
$this->xDest + $this->destDir * $this->wTick / 2,
$this->yDest,
$this->xDest + $this->destDir * (0.5 + 1 / $root2) * $this->wTick,
$this->yDest - $this->wTick / $root2
);
$this->diagram->setDrawColor(0);
}
}

View file

@ -1,214 +0,0 @@
<?php
/**
* Contains PhpMyAdmin\Plugins\Schema\Pdf\TableStatsPdf class
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Schema\Pdf;
use PhpMyAdmin\Pdf as PdfLib;
use PhpMyAdmin\Plugins\Schema\ExportRelationSchema;
use PhpMyAdmin\Plugins\Schema\TableStats;
use function __;
use function count;
use function in_array;
use function max;
use function sprintf;
/**
* Table preferences/statistics
*
* This class preserves the table co-ordinates,fields
* and helps in drawing/generating the Tables in PDF document.
*
* @see Schema\Pdf
*
* @property Pdf $diagram
*/
class TableStatsPdf extends TableStats
{
/** @var int */
public $height;
/** @var string */
private $ff = PdfLib::PMA_PDF_FONT;
/**
* @see PMA_Schema_PDF
* @see TableStatsPdf::setWidthTable
* @see PhpMyAdmin\Plugins\Schema\Pdf\TableStatsPdf::setHeightTable
*
* @param Pdf $diagram The PDF diagram
* @param string $db The database name
* @param string $tableName The table name
* @param int $fontSize The font size
* @param int $pageNumber The current page number (from the
* $cfg['Servers'][$i]['table_coords'] table)
* @param int $sameWideWidth The max. width among tables
* @param bool $showKeys Whether to display keys or not
* @param bool $tableDimension Whether to display table position or not
* @param bool $offline Whether the coordinates are sent
* from the browser
*/
public function __construct(
$diagram,
$db,
$tableName,
$fontSize,
$pageNumber,
&$sameWideWidth,
$showKeys = false,
$tableDimension = false,
$offline = false
) {
parent::__construct($diagram, $db, $pageNumber, $tableName, $showKeys, $tableDimension, $offline);
$this->heightCell = 6;
$this->setHeight();
/*
* setWidth must me after setHeight, because title
* can include table height which changes table width
*/
$this->setWidth($fontSize);
if ($sameWideWidth >= $this->width) {
return;
}
$sameWideWidth = $this->width;
}
/**
* Displays an error when the table cannot be found.
*/
protected function showMissingTableError(): void
{
ExportRelationSchema::dieSchema(
$this->pageNumber,
'PDF',
sprintf(__('The %s table doesn\'t exist!'), $this->tableName)
);
}
/**
* Returns title of the current table,
* title can have the dimensions of the table
*
* @return string
*/
protected function getTitle()
{
$ret = '';
if ($this->tableDimension) {
$ret = sprintf('%.0fx%0.f', $this->width, $this->height);
}
return $ret . ' ' . $this->tableName;
}
/**
* Sets the width of the table
*
* @see PMA_Schema_PDF
*
* @param int $fontSize The font size
*/
private function setWidth($fontSize): void
{
foreach ($this->fields as $field) {
$this->width = max($this->width, $this->diagram->GetStringWidth($field));
}
$this->width += $this->diagram->GetStringWidth(' ');
$this->diagram->setFont($this->ff, 'B', $fontSize);
/*
* it is unknown what value must be added, because
* table title is affected by the table width value
*/
while ($this->width < $this->diagram->GetStringWidth($this->getTitle())) {
$this->width += 5;
}
$this->diagram->setFont($this->ff, '', $fontSize);
}
/**
* Sets the height of the table
*/
private function setHeight(): void
{
$this->height = (count($this->fields) + 1) * $this->heightCell;
}
/**
* Do draw the table
*
* @see Schema\Pdf
*
* @param int|null $fontSize The font size or null to use the default value
* @param bool $withDoc Whether to include links to documentation
* @param bool $setColor Whether to display color
*/
public function tableDraw(?int $fontSize, bool $withDoc, bool $setColor = false): void
{
$this->diagram->setXyScale($this->x, $this->y);
$this->diagram->setFont($this->ff, 'B', $fontSize);
if ($setColor) {
$this->diagram->setTextColor(200);
$this->diagram->setFillColor(0, 0, 128);
}
if ($withDoc) {
$this->diagram->setLink($this->diagram->customLinks['RT'][$this->tableName]['-'], -1);
} else {
$this->diagram->customLinks['doc'][$this->tableName]['-'] = '';
}
$this->diagram->cellScale(
$this->width,
$this->heightCell,
$this->getTitle(),
1,
1,
'C',
$setColor,
$this->diagram->customLinks['doc'][$this->tableName]['-']
);
$this->diagram->setXScale($this->x);
$this->diagram->setFont($this->ff, '', $fontSize);
$this->diagram->setTextColor(0);
$this->diagram->setFillColor(255);
foreach ($this->fields as $field) {
if ($setColor) {
if (in_array($field, $this->primary)) {
$this->diagram->setFillColor(215, 121, 123);
}
if ($field == $this->displayfield) {
$this->diagram->setFillColor(142, 159, 224);
}
}
if ($withDoc) {
$this->diagram->setLink($this->diagram->customLinks['RT'][$this->tableName][$field], -1);
} else {
$this->diagram->customLinks['doc'][$this->tableName][$field] = '';
}
$this->diagram->cellScale(
$this->width,
$this->heightCell,
' ' . $field,
1,
1,
'L',
$setColor,
$this->diagram->customLinks['doc'][$this->tableName][$field]
);
$this->diagram->setXScale($this->x);
$this->diagram->setFillColor(255);
}
}
}

View file

@ -1,128 +0,0 @@
<?php
/**
* Contains abstract class to hold relation preferences/statistics
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Schema;
use function abs;
use function array_search;
use function min;
/**
* Relations preferences/statistics
*
* This class fetches the table master and foreign fields positions
* and helps in generating the Table references and then connects
* master table's master field to foreign table's foreign key.
*
* @abstract
*/
abstract class RelationStats
{
/** @var object */
protected $diagram;
/** @var mixed */
public $xSrc;
/** @var mixed */
public $ySrc;
/** @var int */
public $srcDir;
/** @var int */
public $destDir;
/** @var mixed */
public $xDest;
/** @var mixed */
public $yDest;
/** @var int */
public $wTick = 0;
/**
* @param object $diagram The diagram
* @param string $master_table The master table name
* @param string $master_field The relation field in the master table
* @param string $foreign_table The foreign table name
* @param string $foreign_field The relation field in the foreign table
*/
public function __construct(
$diagram,
$master_table,
$master_field,
$foreign_table,
$foreign_field
) {
$this->diagram = $diagram;
$src_pos = $this->getXy($master_table, $master_field);
$dest_pos = $this->getXy($foreign_table, $foreign_field);
/*
* [0] is x-left
* [1] is x-right
* [2] is y
*/
$src_left = $src_pos[0] - $this->wTick;
$src_right = $src_pos[1] + $this->wTick;
$dest_left = $dest_pos[0] - $this->wTick;
$dest_right = $dest_pos[1] + $this->wTick;
$d1 = abs($src_left - $dest_left);
$d2 = abs($src_right - $dest_left);
$d3 = abs($src_left - $dest_right);
$d4 = abs($src_right - $dest_right);
$d = min($d1, $d2, $d3, $d4);
if ($d == $d1) {
$this->xSrc = $src_pos[0];
$this->srcDir = -1;
$this->xDest = $dest_pos[0];
$this->destDir = -1;
} elseif ($d == $d2) {
$this->xSrc = $src_pos[1];
$this->srcDir = 1;
$this->xDest = $dest_pos[0];
$this->destDir = -1;
} elseif ($d == $d3) {
$this->xSrc = $src_pos[0];
$this->srcDir = -1;
$this->xDest = $dest_pos[1];
$this->destDir = 1;
} else {
$this->xSrc = $src_pos[1];
$this->srcDir = 1;
$this->xDest = $dest_pos[1];
$this->destDir = 1;
}
$this->ySrc = $src_pos[2];
$this->yDest = $dest_pos[2];
}
/**
* Gets arrows coordinates
*
* @param TableStats $table The table
* @param string $column The relation column name
*
* @return array Arrows coordinates
*/
private function getXy($table, $column)
{
$pos = array_search($column, $table->fields);
// x_left, x_right, y
return [
$table->x,
$table->x + $table->width,
$table->y + ($pos + 1.5) * $table->heightCell,
];
}
}

View file

@ -1,92 +0,0 @@
<?php
/**
* Dia schema export code
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Schema;
use PhpMyAdmin\Plugins\Schema\Dia\DiaRelationSchema;
use PhpMyAdmin\Plugins\SchemaPlugin;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyMainGroup;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyRootGroup;
use PhpMyAdmin\Properties\Options\Items\SelectPropertyItem;
use PhpMyAdmin\Properties\Plugins\SchemaPluginProperties;
use function __;
/**
* Handles the schema export for the Dia format
*/
class SchemaDia extends SchemaPlugin
{
/**
* @psalm-return non-empty-lowercase-string
*/
public function getName(): string
{
return 'dia';
}
/**
* Sets the schema export Dia properties
*/
protected function setProperties(): SchemaPluginProperties
{
$schemaPluginProperties = new SchemaPluginProperties();
$schemaPluginProperties->setText('Dia');
$schemaPluginProperties->setExtension('dia');
$schemaPluginProperties->setMimeType('application/dia');
// create the root group that will be the options field for
// $schemaPluginProperties
// this will be shown as "Format specific options"
$exportSpecificOptions = new OptionsPropertyRootGroup('Format Specific Options');
// specific options main group
$specificOptions = new OptionsPropertyMainGroup('general_opts');
// add options common to all plugins
$this->addCommonOptions($specificOptions);
$leaf = new SelectPropertyItem(
'orientation',
__('Orientation')
);
$leaf->setValues(
[
'L' => __('Landscape'),
'P' => __('Portrait'),
]
);
$specificOptions->addProperty($leaf);
$leaf = new SelectPropertyItem(
'paper',
__('Paper size')
);
$leaf->setValues($this->getPaperSizeArray());
$specificOptions->addProperty($leaf);
// add the main group to the root group
$exportSpecificOptions->addProperty($specificOptions);
// set the options for the schema export plugin property item
$schemaPluginProperties->setOptions($exportSpecificOptions);
return $schemaPluginProperties;
}
/**
* Exports the schema into DIA format.
*
* @param string $db database name
*/
public function exportSchema($db): bool
{
$export = new DiaRelationSchema($db);
$export->showOutput();
return true;
}
}

View file

@ -1,93 +0,0 @@
<?php
/**
* PDF schema export code
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Schema;
use PhpMyAdmin\Plugins\Schema\Eps\EpsRelationSchema;
use PhpMyAdmin\Plugins\SchemaPlugin;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyMainGroup;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyRootGroup;
use PhpMyAdmin\Properties\Options\Items\BoolPropertyItem;
use PhpMyAdmin\Properties\Options\Items\SelectPropertyItem;
use PhpMyAdmin\Properties\Plugins\SchemaPluginProperties;
use function __;
/**
* Handles the schema export for the EPS format
*/
class SchemaEps extends SchemaPlugin
{
/**
* @psalm-return non-empty-lowercase-string
*/
public function getName(): string
{
return 'eps';
}
/**
* Sets the schema export EPS properties
*/
protected function setProperties(): SchemaPluginProperties
{
$schemaPluginProperties = new SchemaPluginProperties();
$schemaPluginProperties->setText('EPS');
$schemaPluginProperties->setExtension('eps');
$schemaPluginProperties->setMimeType('application/eps');
// create the root group that will be the options field for
// $schemaPluginProperties
// this will be shown as "Format specific options"
$exportSpecificOptions = new OptionsPropertyRootGroup('Format Specific Options');
// specific options main group
$specificOptions = new OptionsPropertyMainGroup('general_opts');
// add options common to all plugins
$this->addCommonOptions($specificOptions);
// create leaf items and add them to the group
$leaf = new BoolPropertyItem(
'all_tables_same_width',
__('Same width for all tables')
);
$specificOptions->addProperty($leaf);
$leaf = new SelectPropertyItem(
'orientation',
__('Orientation')
);
$leaf->setValues(
[
'L' => __('Landscape'),
'P' => __('Portrait'),
]
);
$specificOptions->addProperty($leaf);
// add the main group to the root group
$exportSpecificOptions->addProperty($specificOptions);
// set the options for the schema export plugin property item
$schemaPluginProperties->setOptions($exportSpecificOptions);
return $schemaPluginProperties;
}
/**
* Exports the schema into EPS format.
*
* @param string $db database name
*/
public function exportSchema($db): bool
{
$export = new EpsRelationSchema($db);
$export->showOutput();
return true;
}
}

View file

@ -1,132 +0,0 @@
<?php
/**
* PDF schema export code
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Schema;
use PhpMyAdmin\Plugins\Schema\Pdf\PdfRelationSchema;
use PhpMyAdmin\Plugins\SchemaPlugin;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyMainGroup;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyRootGroup;
use PhpMyAdmin\Properties\Options\Items\BoolPropertyItem;
use PhpMyAdmin\Properties\Options\Items\SelectPropertyItem;
use PhpMyAdmin\Properties\Plugins\SchemaPluginProperties;
use TCPDF;
use function __;
use function class_exists;
/**
* Handles the schema export for the PDF format
*/
class SchemaPdf extends SchemaPlugin
{
/**
* @psalm-return non-empty-lowercase-string
*/
public function getName(): string
{
return 'pdf';
}
/**
* Sets the schema export PDF properties
*/
protected function setProperties(): SchemaPluginProperties
{
$schemaPluginProperties = new SchemaPluginProperties();
$schemaPluginProperties->setText('PDF');
$schemaPluginProperties->setExtension('pdf');
$schemaPluginProperties->setMimeType('application/pdf');
// create the root group that will be the options field for
// $schemaPluginProperties
// this will be shown as "Format specific options"
$exportSpecificOptions = new OptionsPropertyRootGroup('Format Specific Options');
// specific options main group
$specificOptions = new OptionsPropertyMainGroup('general_opts');
// add options common to all plugins
$this->addCommonOptions($specificOptions);
// create leaf items and add them to the group
$leaf = new BoolPropertyItem(
'all_tables_same_width',
__('Same width for all tables')
);
$specificOptions->addProperty($leaf);
$leaf = new SelectPropertyItem(
'orientation',
__('Orientation')
);
$leaf->setValues(
[
'L' => __('Landscape'),
'P' => __('Portrait'),
]
);
$specificOptions->addProperty($leaf);
$leaf = new SelectPropertyItem(
'paper',
__('Paper size')
);
$leaf->setValues($this->getPaperSizeArray());
$specificOptions->addProperty($leaf);
$leaf = new BoolPropertyItem(
'show_grid',
__('Show grid')
);
$specificOptions->addProperty($leaf);
$leaf = new BoolPropertyItem(
'with_doc',
__('Data dictionary')
);
$specificOptions->addProperty($leaf);
$leaf = new SelectPropertyItem(
'table_order',
__('Order of the tables')
);
$leaf->setValues(
[
'' => __('None'),
'name_asc' => __('Name (Ascending)'),
'name_desc' => __('Name (Descending)'),
]
);
$specificOptions->addProperty($leaf);
// add the main group to the root group
$exportSpecificOptions->addProperty($specificOptions);
// set the options for the schema export plugin property item
$schemaPluginProperties->setOptions($exportSpecificOptions);
return $schemaPluginProperties;
}
/**
* Exports the schema into PDF format.
*
* @param string $db database name
*/
public function exportSchema($db): bool
{
$export = new PdfRelationSchema($db);
$export->showOutput();
return true;
}
public static function isAvailable(): bool
{
return class_exists(TCPDF::class);
}
}

View file

@ -1,80 +0,0 @@
<?php
/**
* PDF schema export code
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Schema;
use PhpMyAdmin\Plugins\Schema\Svg\SvgRelationSchema;
use PhpMyAdmin\Plugins\SchemaPlugin;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyMainGroup;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyRootGroup;
use PhpMyAdmin\Properties\Options\Items\BoolPropertyItem;
use PhpMyAdmin\Properties\Plugins\SchemaPluginProperties;
use function __;
/**
* Handles the schema export for the SVG format
*/
class SchemaSvg extends SchemaPlugin
{
/**
* @psalm-return non-empty-lowercase-string
*/
public function getName(): string
{
return 'svg';
}
/**
* Sets the schema export SVG properties
*/
protected function setProperties(): SchemaPluginProperties
{
$schemaPluginProperties = new SchemaPluginProperties();
$schemaPluginProperties->setText('SVG');
$schemaPluginProperties->setExtension('svg');
$schemaPluginProperties->setMimeType('application/svg');
// create the root group that will be the options field for
// $schemaPluginProperties
// this will be shown as "Format specific options"
$exportSpecificOptions = new OptionsPropertyRootGroup('Format Specific Options');
// specific options main group
$specificOptions = new OptionsPropertyMainGroup('general_opts');
// add options common to all plugins
$this->addCommonOptions($specificOptions);
// create leaf items and add them to the group
$leaf = new BoolPropertyItem(
'all_tables_same_width',
__('Same width for all tables')
);
$specificOptions->addProperty($leaf);
// add the main group to the root group
$exportSpecificOptions->addProperty($specificOptions);
// set the options for the schema export plugin property item
$schemaPluginProperties->setOptions($exportSpecificOptions);
return $schemaPluginProperties;
}
/**
* Exports the schema into SVG format.
*
* @param string $db database name
*/
public function exportSchema($db): bool
{
$export = new SvgRelationSchema($db);
$export->showOutput();
return true;
}
}

View file

@ -1,128 +0,0 @@
<?php
/**
* Contains PhpMyAdmin\Plugins\Schema\Svg\RelationStatsSvg class
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Schema\Svg;
use PhpMyAdmin\Plugins\Schema\RelationStats;
use function shuffle;
use function sqrt;
/**
* Relation preferences/statistics
*
* This class fetches the table master and foreign fields positions
* and helps in generating the Table references and then connects
* master table's master field to foreign table's foreign key
* in SVG XML document.
*
* @see Svg::printElementLine
*/
class RelationStatsSvg extends RelationStats
{
/**
* @param Svg $diagram The SVG diagram
* @param string $master_table The master table name
* @param string $master_field The relation field in the master table
* @param string $foreign_table The foreign table name
* @param string $foreign_field The relation field in the foreign table
*/
public function __construct(
$diagram,
$master_table,
$master_field,
$foreign_table,
$foreign_field
) {
$this->wTick = 10;
parent::__construct($diagram, $master_table, $master_field, $foreign_table, $foreign_field);
}
/**
* draws relation links and arrows shows foreign key relations
*
* @see PMA_SVG
*
* @param bool $showColor Whether to use one color per relation or not
*/
public function relationDraw($showColor): void
{
if ($showColor) {
$listOfColors = [
'#c00',
'#bbb',
'#333',
'#cb0',
'#0b0',
'#0bf',
'#b0b',
];
shuffle($listOfColors);
$color = $listOfColors[0];
} else {
$color = '#333';
}
$this->diagram->printElementLine(
'line',
$this->xSrc,
$this->ySrc,
$this->xSrc + $this->srcDir * $this->wTick,
$this->ySrc,
'stroke:' . $color . ';stroke-width:1;'
);
$this->diagram->printElementLine(
'line',
$this->xDest + $this->destDir * $this->wTick,
$this->yDest,
$this->xDest,
$this->yDest,
'stroke:' . $color . ';stroke-width:1;'
);
$this->diagram->printElementLine(
'line',
$this->xSrc + $this->srcDir * $this->wTick,
$this->ySrc,
$this->xDest + $this->destDir * $this->wTick,
$this->yDest,
'stroke:' . $color . ';stroke-width:1;'
);
$root2 = 2 * sqrt(2);
$this->diagram->printElementLine(
'line',
$this->xSrc + $this->srcDir * $this->wTick * 0.75,
$this->ySrc,
$this->xSrc + $this->srcDir * (0.75 - 1 / $root2) * $this->wTick,
$this->ySrc + $this->wTick / $root2,
'stroke:' . $color . ';stroke-width:2;'
);
$this->diagram->printElementLine(
'line',
$this->xSrc + $this->srcDir * $this->wTick * 0.75,
$this->ySrc,
$this->xSrc + $this->srcDir * (0.75 - 1 / $root2) * $this->wTick,
$this->ySrc - $this->wTick / $root2,
'stroke:' . $color . ';stroke-width:2;'
);
$this->diagram->printElementLine(
'line',
$this->xDest + $this->destDir * $this->wTick / 2,
$this->yDest,
$this->xDest + $this->destDir * (0.5 + 1 / $root2) * $this->wTick,
$this->yDest + $this->wTick / $root2,
'stroke:' . $color . ';stroke-width:2;'
);
$this->diagram->printElementLine(
'line',
$this->xDest + $this->destDir * $this->wTick / 2,
$this->yDest,
$this->xDest + $this->destDir * (0.5 + 1 / $root2) * $this->wTick,
$this->yDest - $this->wTick / $root2,
'stroke:' . $color . ';stroke-width:2;'
);
}
}

View file

@ -1,277 +0,0 @@
<?php
/**
* Classes to create relation schema in SVG format.
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Schema\Svg;
use PhpMyAdmin\Core;
use PhpMyAdmin\ResponseRenderer;
use XMLWriter;
use function intval;
use function is_int;
use function sprintf;
use function strlen;
/**
* This Class inherits the XMLwriter class and
* helps in developing structure of SVG Schema Export
*
* @see https://www.php.net/manual/en/book.xmlwriter.php
*/
class Svg extends XMLWriter
{
/** @var string */
public $title = '';
/** @var string */
public $author = 'phpMyAdmin';
/** @var string */
public $font = 'Arial';
/** @var int */
public $fontSize = 12;
/**
* Upon instantiation This starts writing the RelationStatsSvg XML document
*
* @see XMLWriter::openMemory()
* @see XMLWriter::setIndent()
* @see XMLWriter::startDocument()
*/
public function __construct()
{
$this->openMemory();
/*
* Set indenting using three spaces,
* so output is formatted
*/
$this->setIndent(true);
$this->setIndentString(' ');
/*
* Create the XML document
*/
$this->startDocument('1.0', 'UTF-8');
$this->startDtd('svg', '-//W3C//DTD SVG 1.1//EN', 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd');
$this->endDtd();
}
/**
* Set document title
*
* @param string $value sets the title text
*/
public function setTitle($value): void
{
$this->title = $value;
}
/**
* Set document author
*
* @param string $value sets the author
*/
public function setAuthor($value): void
{
$this->author = $value;
}
/**
* Set document font
*
* @param string $value sets the font e.g Arial, Sans-serif etc
*/
public function setFont(string $value): void
{
$this->font = $value;
}
/**
* Get document font
*
* @return string returns the font name
*/
public function getFont(): string
{
return $this->font;
}
/**
* Set document font size
*
* @param int $value sets the font size in pixels
*/
public function setFontSize(int $value): void
{
$this->fontSize = $value;
}
/**
* Get document font size
*
* @return int returns the font size
*/
public function getFontSize(): int
{
return $this->fontSize;
}
/**
* Starts RelationStatsSvg Document
*
* svg document starts by first initializing svg tag
* which contains all the attributes and namespace that needed
* to define the svg document
*
* @see XMLWriter::startElement()
* @see XMLWriter::writeAttribute()
*
* @param int $width total width of the RelationStatsSvg document
* @param int $height total height of the RelationStatsSvg document
* @param int $x min-x of the view box
* @param int $y min-y of the view box
*/
public function startSvgDoc($width, $height, $x = 0, $y = 0): void
{
$this->startElement('svg');
if (! is_int($width)) {
$width = intval($width);
}
if (! is_int($height)) {
$height = intval($height);
}
if ($x != 0 || $y != 0) {
$this->writeAttribute('viewBox', sprintf('%d %d %d %d', $x, $y, $width, $height));
}
$this->writeAttribute('width', ($width - $x) . 'px');
$this->writeAttribute('height', ($height - $y) . 'px');
$this->writeAttribute('xmlns', 'http://www.w3.org/2000/svg');
$this->writeAttribute('version', '1.1');
}
/**
* Ends RelationStatsSvg Document
*
* @see XMLWriter::endElement()
* @see XMLWriter::endDocument()
*/
public function endSvgDoc(): void
{
$this->endElement();
$this->endDocument();
}
/**
* output RelationStatsSvg Document
*
* svg document prompted to the user for download
* RelationStatsSvg document saved in .svg extension and can be
* easily changeable by using any svg IDE
*
* @see XMLWriter::startElement()
* @see XMLWriter::writeAttribute()
*
* @param string $fileName file name
*/
public function showOutput($fileName): void
{
//ob_get_clean();
$output = $this->flush();
ResponseRenderer::getInstance()->disable();
Core::downloadHeader(
$fileName,
'image/svg+xml',
strlen($output)
);
print $output;
}
/**
* Draws RelationStatsSvg elements
*
* SVG has some predefined shape elements like rectangle & text
* and other elements who have x,y co-ordinates are drawn.
* specify their width and height and can give styles too.
*
* @see XMLWriter::startElement()
* @see XMLWriter::writeAttribute()
* @see XMLWriter::text()
* @see XMLWriter::endElement()
*
* @param string $name RelationStatsSvg element name
* @param int $x The x attr defines the left position of the element
* (e.g. x="0" places the element 0 pixels from the
* left of the browser window)
* @param int $y The y attribute defines the top position of the
* element (e.g. y="0" places the element 0 pixels
* from the top of the browser window)
* @param int|string $width The width attribute defines the width the element
* @param int|string $height The height attribute defines the height the element
* @param string|null $text The text attribute defines the text the element
* @param string $styles The style attribute defines the style the element
* styles can be defined like CSS styles
*/
public function printElement(
$name,
$x,
$y,
$width = '',
$height = '',
?string $text = '',
$styles = ''
): void {
$this->startElement($name);
$this->writeAttribute('width', (string) $width);
$this->writeAttribute('height', (string) $height);
$this->writeAttribute('x', (string) $x);
$this->writeAttribute('y', (string) $y);
$this->writeAttribute('style', (string) $styles);
if (isset($text)) {
$this->writeAttribute('font-family', (string) $this->font);
$this->writeAttribute('font-size', $this->fontSize . 'px');
$this->text($text);
}
$this->endElement();
}
/**
* Draws RelationStatsSvg Line element
*
* RelationStatsSvg line element is drawn for connecting the tables.
* arrows are also drawn by specify its start and ending
* co-ordinates
*
* @see XMLWriter::startElement()
* @see XMLWriter::writeAttribute()
* @see XMLWriter::endElement()
*
* @param string $name RelationStatsSvg element name i.e line
* @param int $x1 Defines the start of the line on the x-axis
* @param int $y1 Defines the start of the line on the y-axis
* @param int $x2 Defines the end of the line on the x-axis
* @param int $y2 Defines the end of the line on the y-axis
* @param string $styles The style attribute defines the style the element
* styles can be defined like CSS styles
*/
public function printElementLine($name, $x1, $y1, $x2, $y2, $styles): void
{
$this->startElement($name);
$this->writeAttribute('x1', (string) $x1);
$this->writeAttribute('y1', (string) $y1);
$this->writeAttribute('x2', (string) $x2);
$this->writeAttribute('y2', (string) $y2);
$this->writeAttribute('style', (string) $styles);
$this->endElement();
}
}

View file

@ -1,286 +0,0 @@
<?php
/**
* Contains PhpMyAdmin\Plugins\Schema\Svg\RelationStatsSvg class
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Schema\Svg;
use PhpMyAdmin\Plugins\Schema\Dia\TableStatsDia;
use PhpMyAdmin\Plugins\Schema\Eps\TableStatsEps;
use PhpMyAdmin\Plugins\Schema\ExportRelationSchema;
use PhpMyAdmin\Plugins\Schema\Pdf\TableStatsPdf;
use PhpMyAdmin\Version;
use function __;
use function in_array;
use function max;
use function min;
use function sprintf;
/**
* RelationStatsSvg Relation Schema Class
*
* Purpose of this class is to generate the SVG XML Document because
* SVG defines the graphics in XML format which is used for representing
* the database diagrams as vector image. This class actually helps
* in preparing SVG XML format.
*
* SVG XML is generated by using XMLWriter php extension and this class
* inherits ExportRelationSchema class has common functionality added
* to this class
*
* @property Svg $diagram
*/
class SvgRelationSchema extends ExportRelationSchema
{
/** @var TableStatsDia[]|TableStatsEps[]|TableStatsPdf[]|TableStatsSvg[] */
private $tables = [];
/** @var RelationStatsSvg[] Relations */
private $relations = [];
/** @var int|float */
private $xMax = 0;
/** @var int|float */
private $yMax = 0;
/** @var int|float */
private $xMin = 100000;
/** @var int|float */
private $yMin = 100000;
/** @var int */
private $tablewidth = 0;
/**
* Upon instantiation This starts writing the SVG XML document
* user will be prompted for download as .svg extension
*
* @see PMA_SVG
*
* @param string $db database name
*/
public function __construct($db)
{
parent::__construct($db, new Svg());
$this->setShowColor(isset($_REQUEST['svg_show_color']));
$this->setShowKeys(isset($_REQUEST['svg_show_keys']));
$this->setTableDimension(isset($_REQUEST['svg_show_table_dimension']));
$this->setAllTablesSameWidth(isset($_REQUEST['svg_all_tables_same_width']));
$this->diagram->setTitle(
sprintf(
__('Schema of the %s database - Page %s'),
$this->db,
$this->pageNumber
)
);
$this->diagram->setAuthor('phpMyAdmin ' . Version::VERSION);
$this->diagram->setFont('Arial');
$this->diagram->setFontSize(16);
$alltables = $this->getTablesFromRequest();
foreach ($alltables as $table) {
if (! isset($this->tables[$table])) {
$this->tables[$table] = new TableStatsSvg(
$this->diagram,
$this->db,
$table,
$this->diagram->getFont(),
$this->diagram->getFontSize(),
$this->pageNumber,
$this->tablewidth,
$this->showKeys,
$this->tableDimension,
$this->offline
);
}
if ($this->sameWide) {
$this->tables[$table]->width = &$this->tablewidth;
}
$this->setMinMax($this->tables[$table]);
}
$border = 15;
$this->diagram->startSvgDoc(
$this->xMax + $border,
$this->yMax + $border,
$this->xMin - $border,
$this->yMin - $border
);
$seen_a_relation = false;
foreach ($alltables as $one_table) {
$exist_rel = $this->relation->getForeigners($this->db, $one_table, '', 'both');
if (! $exist_rel) {
continue;
}
$seen_a_relation = true;
foreach ($exist_rel as $master_field => $rel) {
/* put the foreign table on the schema only if selected
* by the user
* (do not use array_search() because we would have to
* to do a === false and this is not PHP3 compatible)
*/
if ($master_field !== 'foreign_keys_data') {
if (in_array($rel['foreign_table'], $alltables)) {
$this->addRelation(
$one_table,
$this->diagram->getFont(),
$this->diagram->getFontSize(),
$master_field,
$rel['foreign_table'],
$rel['foreign_field'],
$this->tableDimension
);
}
continue;
}
foreach ($rel as $one_key) {
if (! in_array($one_key['ref_table_name'], $alltables)) {
continue;
}
foreach ($one_key['index_list'] as $index => $one_field) {
$this->addRelation(
$one_table,
$this->diagram->getFont(),
$this->diagram->getFontSize(),
$one_field,
$one_key['ref_table_name'],
$one_key['ref_index_list'][$index],
$this->tableDimension
);
}
}
}
}
if ($seen_a_relation) {
$this->drawRelations();
}
$this->drawTables();
$this->diagram->endSvgDoc();
}
/**
* Output RelationStatsSvg Document for download
*/
public function showOutput(): void
{
$this->diagram->showOutput($this->getFileName('.svg'));
}
/**
* Sets X and Y minimum and maximum for a table cell
*
* @param TableStatsSvg $table The table
*/
private function setMinMax($table): void
{
$this->xMax = max($this->xMax, $table->x + $table->width);
$this->yMax = max($this->yMax, $table->y + $table->height);
$this->xMin = min($this->xMin, $table->x);
$this->yMin = min($this->yMin, $table->y);
}
/**
* Defines relation objects
*
* @see setMinMax,TableStatsSvg::__construct(),
* PhpMyAdmin\Plugins\Schema\Svg\RelationStatsSvg::__construct()
*
* @param string $masterTable The master table name
* @param string $font The font face
* @param int $fontSize Font size
* @param string $masterField The relation field in the master table
* @param string $foreignTable The foreign table name
* @param string $foreignField The relation field in the foreign table
* @param bool $tableDimension Whether to display table position or not
*/
private function addRelation(
$masterTable,
$font,
$fontSize,
$masterField,
$foreignTable,
$foreignField,
$tableDimension
): void {
if (! isset($this->tables[$masterTable])) {
$this->tables[$masterTable] = new TableStatsSvg(
$this->diagram,
$this->db,
$masterTable,
$font,
$fontSize,
$this->pageNumber,
$this->tablewidth,
false,
$tableDimension
);
$this->setMinMax($this->tables[$masterTable]);
}
if (! isset($this->tables[$foreignTable])) {
$this->tables[$foreignTable] = new TableStatsSvg(
$this->diagram,
$this->db,
$foreignTable,
$font,
$fontSize,
$this->pageNumber,
$this->tablewidth,
false,
$tableDimension
);
$this->setMinMax($this->tables[$foreignTable]);
}
$this->relations[] = new RelationStatsSvg(
$this->diagram,
$this->tables[$masterTable],
$masterField,
$this->tables[$foreignTable],
$foreignField
);
}
/**
* Draws relation arrows and lines
* connects master table's master field to
* foreign table's foreign field
*
* @see Relation_Stats_Svg::relationDraw()
*/
private function drawRelations(): void
{
foreach ($this->relations as $relation) {
$relation->relationDraw($this->showColor);
}
}
/**
* Draws tables
*
* @see TableStatsSvg::Table_Stats_tableDraw()
*/
private function drawTables(): void
{
foreach ($this->tables as $table) {
$table->tableDraw($this->showColor);
}
}
}

View file

@ -1,190 +0,0 @@
<?php
/**
* Contains PhpMyAdmin\Plugins\Schema\Svg\TableStatsSvg class
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Schema\Svg;
use PhpMyAdmin\Plugins\Schema\ExportRelationSchema;
use PhpMyAdmin\Plugins\Schema\TableStats;
use function __;
use function count;
use function in_array;
use function max;
use function sprintf;
/**
* Table preferences/statistics
*
* This class preserves the table co-ordinates,fields
* and helps in drawing/generating the Tables in SVG XML document.
*
* @see Svg
*
* @property Svg $diagram
*/
class TableStatsSvg extends TableStats
{
/** @var int */
public $height;
/** @var int */
public $currentCell = 0;
/**
* @see Svg
* @see TableStatsSvg::setWidthTable
* @see TableStatsSvg::setHeightTable
*
* @param Svg $diagram The current SVG image document
* @param string $db The database name
* @param string $tableName The table name
* @param string $font Font face
* @param int $fontSize The font size
* @param int $pageNumber Page number
* @param int $same_wide_width The max. width among tables
* @param bool $showKeys Whether to display keys or not
* @param bool $tableDimension Whether to display table position or not
* @param bool $offline Whether the coordinates are sent
*/
public function __construct(
$diagram,
$db,
$tableName,
$font,
$fontSize,
$pageNumber,
&$same_wide_width,
$showKeys = false,
$tableDimension = false,
$offline = false
) {
parent::__construct($diagram, $db, $pageNumber, $tableName, $showKeys, $tableDimension, $offline);
// height and width
$this->setHeightTable($fontSize);
// setWidth must me after setHeight, because title
// can include table height which changes table width
$this->setWidthTable($font, $fontSize);
if ($same_wide_width >= $this->width) {
return;
}
$same_wide_width = $this->width;
}
/**
* Displays an error when the table cannot be found.
*/
protected function showMissingTableError(): void
{
ExportRelationSchema::dieSchema(
$this->pageNumber,
'SVG',
sprintf(__('The %s table doesn\'t exist!'), $this->tableName)
);
}
/**
* Sets the width of the table
*
* @see PMA_SVG
*
* @param string $font The font size
* @param int $fontSize The font size
*/
private function setWidthTable($font, $fontSize): void
{
foreach ($this->fields as $field) {
$this->width = max(
$this->width,
$this->font->getStringWidth($field, $font, $fontSize)
);
}
$this->width += $this->font->getStringWidth(' ', $font, $fontSize);
/*
* it is unknown what value must be added, because
* table title is affected by the table width value
*/
while ($this->width < $this->font->getStringWidth($this->getTitle(), $font, $fontSize)) {
$this->width += 7;
}
}
/**
* Sets the height of the table
*
* @param int $fontSize font size
*/
private function setHeightTable($fontSize): void
{
$this->heightCell = $fontSize + 4;
$this->height = (count($this->fields) + 1) * $this->heightCell;
}
/**
* draw the table
*
* @see Svg::printElement
*
* @param bool $showColor Whether to display color
*/
public function tableDraw($showColor): void
{
$this->diagram->printElement(
'rect',
$this->x,
$this->y,
$this->width,
$this->heightCell,
null,
'fill:#007;stroke:black;'
);
$this->diagram->printElement(
'text',
$this->x + 5,
$this->y + 14,
$this->width,
$this->heightCell,
$this->getTitle(),
'fill:#fff;'
);
foreach ($this->fields as $field) {
$this->currentCell += $this->heightCell;
$fillColor = 'none';
if ($showColor) {
if (in_array($field, $this->primary)) {
$fillColor = '#aea';
}
if ($field == $this->displayfield) {
$fillColor = 'none';
}
}
$this->diagram->printElement(
'rect',
$this->x,
$this->y + $this->currentCell,
$this->width,
$this->heightCell,
null,
'fill:' . $fillColor . ';stroke:black;'
);
$this->diagram->printElement(
'text',
$this->x + 5,
$this->y + 14 + $this->currentCell,
$this->width,
$this->heightCell,
$field,
'fill:black;'
);
}
}
}

View file

@ -1,225 +0,0 @@
<?php
/**
* Contains abstract class to hold table preferences/statistics
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Schema;
use PhpMyAdmin\ConfigStorage\Relation;
use PhpMyAdmin\Font;
use PhpMyAdmin\Index;
use PhpMyAdmin\Util;
use function array_flip;
use function array_keys;
use function array_merge;
use function is_array;
use function rawurldecode;
use function sprintf;
/**
* Table preferences/statistics
*
* This class preserves the table co-ordinates,fields
* and helps in drawing/generating the tables.
*
* @abstract
*/
abstract class TableStats
{
/** @var Dia\Dia|Eps\Eps|Pdf\Pdf|Svg\Svg */
protected $diagram;
/** @var string */
protected $db;
/** @var int */
protected $pageNumber;
/** @var string */
protected $tableName;
/** @var bool */
protected $showKeys;
/** @var bool */
protected $tableDimension;
/** @var mixed */
public $displayfield;
/** @var array */
public $fields = [];
/** @var array */
public $primary = [];
/** @var int|float */
public $x = 0;
/** @var int|float */
public $y = 0;
/** @var int */
public $width = 0;
/** @var int */
public $heightCell = 0;
/** @var bool */
protected $offline;
/** @var Relation */
protected $relation;
/** @var Font */
protected $font;
/**
* @param Pdf\Pdf|Svg\Svg|Eps\Eps|Dia\Dia $diagram schema diagram
* @param string $db current db name
* @param int $pageNumber current page number (from the
* $cfg['Servers'][$i]['table_coords'] table)
* @param string $tableName table name
* @param bool $showKeys whether to display keys or not
* @param bool $tableDimension whether to display table position or not
* @param bool $offline whether the coordinates are sent from the browser
*/
public function __construct(
$diagram,
$db,
$pageNumber,
$tableName,
$showKeys,
$tableDimension,
$offline
) {
global $dbi;
$this->diagram = $diagram;
$this->db = $db;
$this->pageNumber = $pageNumber;
$this->tableName = $tableName;
$this->showKeys = $showKeys;
$this->tableDimension = $tableDimension;
$this->offline = $offline;
$this->relation = new Relation($dbi);
$this->font = new Font();
// checks whether the table exists
// and loads fields
$this->validateTableAndLoadFields();
// load table coordinates
$this->loadCoordinates();
// loads display field
$this->loadDisplayField();
// loads primary keys
$this->loadPrimaryKey();
}
/**
* Validate whether the table exists.
*/
protected function validateTableAndLoadFields(): void
{
global $dbi;
$sql = 'DESCRIBE ' . Util::backquote($this->tableName);
$result = $dbi->tryQuery($sql);
if (! $result || ! $result->numRows()) {
$this->showMissingTableError();
exit;
}
if ($this->showKeys) {
$indexes = Index::getFromTable($this->tableName, $this->db);
$all_columns = [];
foreach ($indexes as $index) {
$all_columns = array_merge(
$all_columns,
array_flip(array_keys($index->getColumns()))
);
}
$this->fields = array_keys($all_columns);
} else {
$this->fields = $result->fetchAllColumn();
}
}
/**
* Displays an error when the table cannot be found.
*
* @abstract
*/
abstract protected function showMissingTableError(): void;
/**
* Loads coordinates of a table
*/
protected function loadCoordinates(): void
{
if (! isset($_POST['t_h']) || ! is_array($_POST['t_h'])) {
return;
}
foreach (array_keys($_POST['t_h']) as $key) {
$db = rawurldecode($_POST['t_db'][$key]);
$tbl = rawurldecode($_POST['t_tbl'][$key]);
if ($this->db . '.' . $this->tableName === $db . '.' . $tbl) {
$this->x = (float) $_POST['t_x'][$key];
$this->y = (float) $_POST['t_y'][$key];
break;
}
}
}
/**
* Loads the table's display field
*/
protected function loadDisplayField(): void
{
$this->displayfield = $this->relation->getDisplayField($this->db, $this->tableName);
}
/**
* Loads the PRIMARY key.
*/
protected function loadPrimaryKey(): void
{
global $dbi;
$result = $dbi->query('SHOW INDEX FROM ' . Util::backquote($this->tableName) . ';');
if ($result->numRows() <= 0) {
return;
}
while ($row = $result->fetchAssoc()) {
if ($row['Key_name'] !== 'PRIMARY') {
continue;
}
$this->primary[] = $row['Column_name'];
}
}
/**
* Returns title of the current table,
* title can have the dimensions/co-ordinates of the table
*
* @return string title of the current table
*/
protected function getTitle()
{
return ($this->tableDimension
? sprintf('%.0fx%0.f', $this->width, $this->heightCell)
: ''
)
. ' ' . $this->tableName;
}
}

View file

@ -1,99 +0,0 @@
<?php
/**
* Abstract class for the schema export plugins
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins;
use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyMainGroup;
use PhpMyAdmin\Properties\Options\Items\BoolPropertyItem;
use PhpMyAdmin\Properties\Plugins\PluginPropertyItem;
use PhpMyAdmin\Properties\Plugins\SchemaPluginProperties;
use function __;
/**
* Provides a common interface that will have to be implemented by all of the
* schema export plugins. Some of the plugins will also implement other public
* methods, but those are not declared here, because they are not implemented
* by all export plugins.
*/
abstract class SchemaPlugin implements Plugin
{
/**
* Object containing the specific schema export plugin type properties.
*
* @var SchemaPluginProperties
*/
protected $properties;
final public function __construct()
{
$this->init();
$this->properties = $this->setProperties();
}
/**
* Plugin specific initializations.
*/
protected function init(): void
{
}
/**
* Gets the export specific format plugin properties
*
* @return SchemaPluginProperties
*/
public function getProperties(): PluginPropertyItem
{
return $this->properties;
}
/**
* Sets the export plugins properties and is implemented by each schema export plugin.
*/
abstract protected function setProperties(): SchemaPluginProperties;
/**
* Exports the schema into the specified format.
*
* @param string $db database name
*/
abstract public function exportSchema($db): bool;
/**
* Adds export options common to all plugins.
*
* @param OptionsPropertyMainGroup $propertyGroup property group
*/
protected function addCommonOptions(OptionsPropertyMainGroup $propertyGroup): void
{
$leaf = new BoolPropertyItem('show_color', __('Show color'));
$propertyGroup->addProperty($leaf);
$leaf = new BoolPropertyItem('show_keys', __('Only show keys'));
$propertyGroup->addProperty($leaf);
}
/**
* Returns the array of paper sizes
*
* @return array array of paper sizes
*/
protected function getPaperSizeArray()
{
$ret = [];
foreach ($GLOBALS['cfg']['PDFPageSizes'] as $val) {
$ret[$val] = $val;
}
return $ret;
}
public static function isAvailable(): bool
{
return true;
}
}

View file

@ -1,65 +0,0 @@
<?php
/**
* Abstract class for the Bool2Text transformations plugins
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Transformations\Abs;
use PhpMyAdmin\FieldMetadata;
use PhpMyAdmin\Plugins\TransformationsPlugin;
use function __;
/**
* Provides common methods for all of the Bool2Text transformations plugins.
*/
abstract class Bool2TextTransformationsPlugin extends TransformationsPlugin
{
/**
* Gets the transformation description of the specific plugin
*
* @return string
*/
public static function getInfo()
{
return __(
'Converts Boolean values to text (default \'T\' and \'F\').'
. ' First option is for TRUE, second for FALSE. Nonzero=true.'
);
}
/**
* Does the actual work of each specific transformations plugin.
*
* @param string $buffer text to be transformed
* @param array $options transformation options
* @param FieldMetadata|null $meta meta information
*
* @return string
*/
public function applyTransformation($buffer, array $options = [], ?FieldMetadata $meta = null)
{
$cfg = $GLOBALS['cfg'];
$options = $this->getOptions($options, $cfg['DefaultTransformations']['Bool2Text']);
if ($buffer == '0') {
return $options[1]; // return false label
}
return $options[0]; // or true one if nonzero
}
/* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */
/**
* Gets the transformation name of the specific plugin
*
* @return string
*/
public static function getName()
{
return 'Bool2Text';
}
}

View file

@ -1,74 +0,0 @@
<?php
/**
* Abstract class for syntax highlighted editors using CodeMirror
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Transformations\Abs;
use PhpMyAdmin\FieldMetadata;
use PhpMyAdmin\Plugins\IOTransformationsPlugin;
use function htmlspecialchars;
use function strtolower;
/**
* Provides common methods for all the CodeMirror syntax highlighted editors
*/
abstract class CodeMirrorEditorTransformationPlugin extends IOTransformationsPlugin
{
/**
* Does the actual work of each specific transformations plugin.
*
* @param string $buffer text to be transformed
* @param array $options transformation options
* @param FieldMetadata|null $meta meta information
*
* @return string
*/
public function applyTransformation($buffer, array $options = [], ?FieldMetadata $meta = null)
{
return $buffer;
}
/**
* Returns the html for input field to override default textarea.
* Note: Return empty string if default textarea is required.
*
* @param array $column column details
* @param int $row_id row number
* @param string $column_name_appendix the name attribute
* @param array $options transformation options
* @param string $value Current field value
* @param string $text_dir text direction
* @param int $tabindex tab index
* @param int $tabindex_for_value offset for the values tabindex
* @param int $idindex id index
*
* @return string the html for input field
*/
public function getInputHtml(
array $column,
$row_id,
$column_name_appendix,
array $options,
$value,
$text_dir,
$tabindex,
$tabindex_for_value,
$idindex
) {
$html = '';
if (! empty($value)) {
$html = '<input type="hidden" name="fields_prev' . $column_name_appendix
. '" value="' . htmlspecialchars($value) . '">';
}
$class = 'transform_' . strtolower(static::getName()) . '_editor';
return $html . '<textarea name="fields' . $column_name_appendix . '"'
. ' dir="' . $text_dir . '" class="' . $class . '">'
. htmlspecialchars($value) . '</textarea>';
}
}

View file

@ -1,163 +0,0 @@
<?php
/**
* Abstract class for the date format transformations plugins
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Transformations\Abs;
use PhpMyAdmin\FieldMetadata;
use PhpMyAdmin\Plugins\TransformationsPlugin;
use PhpMyAdmin\Sanitize;
use PhpMyAdmin\Util;
use function __;
use function checkdate;
use function gmdate;
use function htmlspecialchars;
use function mb_strlen;
use function mb_strtolower;
use function mb_substr;
use function mktime;
use function preg_match;
use function strtotime;
/**
* Provides common methods for all of the date format transformations plugins.
*/
abstract class DateFormatTransformationsPlugin extends TransformationsPlugin
{
/**
* Gets the transformation description of the specific plugin
*
* @return string
*/
public static function getInfo()
{
return __(
'Displays a TIME, TIMESTAMP, DATETIME or numeric unix timestamp'
. ' column as formatted date. The first option is the offset (in'
. ' hours) which will be added to the timestamp (Default: 0). Use'
. ' second option to specify a different date/time format string.'
. ' Third option determines whether you want to see local date or'
. ' UTC one (use "local" or "utc" strings) for that. According to'
. ' that, date format has different value - for "local" see the'
. ' documentation for PHP\'s strftime() function and for "utc" it'
. ' is done using gmdate() function.'
);
}
/**
* Does the actual work of each specific transformations plugin.
*
* @param string $buffer text to be transformed
* @param array $options transformation options
* @param FieldMetadata|null $meta meta information
*
* @return string
*/
public function applyTransformation($buffer, array $options = [], ?FieldMetadata $meta = null)
{
$buffer = (string) $buffer;
// possibly use a global transform and feed it with special options
$cfg = $GLOBALS['cfg'];
$options = $this->getOptions($options, $cfg['DefaultTransformations']['DateFormat']);
// further operations on $buffer using the $options[] array.
$options[2] = mb_strtolower($options[2]);
if (empty($options[1])) {
if ($options[2] === 'local') {
$options[1] = __('%B %d, %Y at %I:%M %p');
} else {
$options[1] = 'Y-m-d H:i:s';
}
}
$timestamp = -1;
// INT columns will be treated as UNIX timestamps
// and need to be detected before the verification for
// MySQL TIMESTAMP
if ($meta !== null && $meta->isType(FieldMetadata::TYPE_INT)) {
$timestamp = $buffer;
// Detect TIMESTAMP(6 | 8 | 10 | 12 | 14)
// TIMESTAMP (2 | 4) not supported here.
// (Note: prior to MySQL 4.1, TIMESTAMP has a display size
// for example TIMESTAMP(8) means YYYYMMDD)
} else {
if (preg_match('/^(\d{2}){3,7}$/', $buffer)) {
if (mb_strlen($buffer) == 14 || mb_strlen($buffer) == 8) {
$offset = 4;
} else {
$offset = 2;
}
$aDate = [];
$aDate['year'] = (int) mb_substr($buffer, 0, $offset);
$aDate['month'] = (int) mb_substr($buffer, $offset, 2);
$aDate['day'] = (int) mb_substr($buffer, $offset + 2, 2);
$aDate['hour'] = (int) mb_substr($buffer, $offset + 4, 2);
$aDate['minute'] = (int) mb_substr($buffer, $offset + 6, 2);
$aDate['second'] = (int) mb_substr($buffer, $offset + 8, 2);
if (checkdate($aDate['month'], $aDate['day'], $aDate['year'])) {
$timestamp = mktime(
$aDate['hour'],
$aDate['minute'],
$aDate['second'],
$aDate['month'],
$aDate['day'],
$aDate['year']
);
}
// If all fails, assume one of the dozens of valid strtime() syntaxes
// (https://www.gnu.org/manual/tar-1.12/html_chapter/tar_7.html)
} else {
if (preg_match('/^[0-9]\d{1,9}$/', $buffer)) {
$timestamp = (int) $buffer;
} else {
$timestamp = strtotime($buffer);
}
}
}
// If all above failed, maybe it's a Unix timestamp already?
if ($timestamp < 0 && preg_match('/^[1-9]\d{1,9}$/', $buffer)) {
$timestamp = $buffer;
}
// Reformat a valid timestamp
if ($timestamp >= 0) {
$timestamp -= (int) $options[0] * 60 * 60;
$source = $buffer;
if ($options[2] === 'local') {
$text = Util::localisedDate($timestamp, $options[1]);
} elseif ($options[2] === 'utc') {
$text = gmdate($options[1], $timestamp);
} else {
$text = 'INVALID DATE TYPE';
}
return '<dfn onclick="alert(\'' . Sanitize::jsFormat($source, false) . '\');" title="'
. htmlspecialchars((string) $source) . '">' . htmlspecialchars((string) $text) . '</dfn>';
}
return htmlspecialchars((string) $buffer);
}
/* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */
/**
* Gets the transformation name of the specific plugin
*
* @return string
*/
public static function getName()
{
return 'Date Format';
}
}

View file

@ -1,98 +0,0 @@
<?php
/**
* Abstract class for the download transformations plugins
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Transformations\Abs;
use PhpMyAdmin\FieldMetadata;
use PhpMyAdmin\Plugins\TransformationsPlugin;
use PhpMyAdmin\Url;
use function __;
use function array_merge;
use function htmlspecialchars;
/**
* Provides common methods for all of the download transformations plugins.
*/
abstract class DownloadTransformationsPlugin extends TransformationsPlugin
{
/**
* Gets the transformation description of the specific plugin
*
* @return string
*/
public static function getInfo()
{
return __(
'Displays a link to download the binary data of the column. You can'
. ' use the first option to specify the filename, or use the second'
. ' option as the name of a column which contains the filename. If'
. ' you use the second option, you need to set the first option to'
. ' the empty string.'
);
}
/**
* Does the actual work of each specific transformations plugin.
*
* @param string $buffer text to be transformed
* @param array $options transformation options
* @param FieldMetadata|null $meta meta information
*
* @return string
*/
public function applyTransformation($buffer, array $options = [], ?FieldMetadata $meta = null)
{
global $row, $fields_meta;
if (isset($options[0]) && ! empty($options[0])) {
$cn = $options[0]; // filename
} else {
if (isset($options[1]) && ! empty($options[1])) {
foreach ($fields_meta as $key => $val) {
if ($val->name == $options[1]) {
$pos = $key;
break;
}
}
if (isset($pos)) {
$cn = $row[$pos];
}
}
if (empty($cn)) {
$cn = 'binary_file.dat';
}
}
$link = '<a href="' . Url::getFromRoute(
'/transformation/wrapper',
array_merge($options['wrapper_params'], [
'ct' => 'application/octet-stream',
'cn' => $cn,
])
);
$link .= '" title="' . htmlspecialchars($cn);
$link .= '" class="disableAjax">' . htmlspecialchars($cn);
$link .= '</a>';
return $link;
}
/* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */
/**
* Gets the transformation name of the specific plugin
*
* @return string
*/
public static function getName()
{
return 'Download';
}
}

View file

@ -1,176 +0,0 @@
<?php
/**
* Abstract class for the external transformations plugins
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Transformations\Abs;
use PhpMyAdmin\FieldMetadata;
use PhpMyAdmin\Plugins\TransformationsPlugin;
use function __;
use function count;
use function fclose;
use function feof;
use function fgets;
use function fwrite;
use function htmlspecialchars;
use function is_resource;
use function proc_close;
use function proc_open;
use function sprintf;
use function strlen;
use function trigger_error;
use const E_USER_DEPRECATED;
/**
* Provides common methods for all of the external transformations plugins.
*/
abstract class ExternalTransformationsPlugin extends TransformationsPlugin
{
/**
* Gets the transformation description of the specific plugin
*
* @return string
*/
public static function getInfo()
{
return __(
'LINUX ONLY: Launches an external application and feeds it the column'
. ' data via standard input. Returns the standard output of the'
. ' application. The default is Tidy, to pretty-print HTML code.'
. ' For security reasons, you have to manually edit the file'
. ' libraries/classes/Plugins/Transformations/Abs/ExternalTransformationsPlugin.php'
. ' and list the tools you want to make available.'
. ' The first option is then the number of the program you want to'
. ' use. The second option should be blank for historical reasons.'
. ' The third option, if set to 1, will convert the output using'
. ' htmlspecialchars() (Default 1). The fourth option, if set to 1,'
. ' will prevent wrapping and ensure that the output appears all on'
. ' one line (Default 1).'
);
}
/**
* Enables no-wrapping
*
* @param array $options transformation options
*/
public function applyTransformationNoWrap(array $options = []): bool
{
if (! isset($options[3]) || $options[3] == '') {
$nowrap = true;
} elseif ($options[3] == '1' || $options[3] == 1) {
$nowrap = true;
} else {
$nowrap = false;
}
return $nowrap;
}
/**
* Does the actual work of each specific transformations plugin.
*
* @param string $buffer text to be transformed
* @param array $options transformation options
* @param FieldMetadata|null $meta meta information
*
* @return string
*/
public function applyTransformation($buffer, array $options = [], ?FieldMetadata $meta = null)
{
// possibly use a global transform and feed it with special options
// further operations on $buffer using the $options[] array.
$allowed_programs = [];
// WARNING:
//
// It's up to administrator to allow anything here. Note that users may
// specify any parameters, so when programs allow output redirection or
// any other possibly dangerous operations, you should write wrapper
// script that will publish only functions you really want.
//
// Add here program definitions like (note that these are NOT safe
// programs):
//
//$allowed_programs[0] = '/usr/local/bin/tidy';
//$allowed_programs[1] = '/usr/local/bin/validate';
// no-op when no allowed programs
if (count($allowed_programs) === 0) {
return $buffer;
}
$cfg = $GLOBALS['cfg'];
$options = $this->getOptions($options, $cfg['DefaultTransformations']['External']);
if (isset($allowed_programs[$options[0]])) {
$program = $allowed_programs[$options[0]];
} else {
$program = $allowed_programs[0];
}
if (isset($options[1]) && strlen((string) $options[1]) > 0) {
trigger_error(sprintf(
__(
'You are using the external transformation command line'
. ' options field, which has been deprecated for security reasons.'
. ' Add all command line options directly to the definition in %s.'
),
'[code]libraries/classes/Plugins/Transformations/Abs/ExternalTransformationsPlugin.php[/code]'
), E_USER_DEPRECATED);
}
// needs PHP >= 4.3.0
$newstring = '';
$descriptorspec = [
0 => [
'pipe',
'r',
],
1 => [
'pipe',
'w',
],
];
$process = proc_open($program . ' ' . $options[1], $descriptorspec, $pipes);
if (is_resource($process)) {
fwrite($pipes[0], $buffer);
fclose($pipes[0]);
while (! feof($pipes[1])) {
$newstring .= fgets($pipes[1], 1024);
}
fclose($pipes[1]);
// we don't currently use the return value
proc_close($process);
}
if ($options[2] == 1 || $options[2] == '2') {
$retstring = htmlspecialchars($newstring);
} else {
$retstring = $newstring;
}
return $retstring;
}
/* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */
/**
* Gets the transformation name of the specific plugin
*
* @return string
*/
public static function getName()
{
return 'External';
}
}

View file

@ -1,62 +0,0 @@
<?php
/**
* Abstract class for the formatted transformations plugins
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Transformations\Abs;
use PhpMyAdmin\FieldMetadata;
use PhpMyAdmin\Plugins\TransformationsPlugin;
use function __;
use function strtr;
/**
* Provides common methods for all of the formatted transformations plugins.
*/
abstract class FormattedTransformationsPlugin extends TransformationsPlugin
{
/**
* Gets the transformation description of the specific plugin
*
* @return string
*/
public static function getInfo()
{
return __(
'Displays the contents of the column as-is, without running it'
. ' through htmlspecialchars(). That is, the column is assumed'
. ' to contain valid HTML.'
);
}
/**
* Does the actual work of each specific transformations plugin.
*
* @param string $buffer text to be transformed
* @param array $options transformation options
* @param FieldMetadata|null $meta meta information
*
* @return string
*/
public function applyTransformation($buffer, array $options = [], ?FieldMetadata $meta = null)
{
return '<iframe srcdoc="'
. strtr($buffer, '"', '\'')
. '" sandbox=""></iframe>';
}
/* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */
/**
* Gets the transformation name of the specific plugin
*
* @return string
*/
public static function getName()
{
return 'Formatted';
}
}

View file

@ -1,71 +0,0 @@
<?php
/**
* Abstract class for the hex transformations plugins
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Transformations\Abs;
use PhpMyAdmin\FieldMetadata;
use PhpMyAdmin\Plugins\TransformationsPlugin;
use function __;
use function bin2hex;
use function chunk_split;
use function intval;
/**
* Provides common methods for all of the hex transformations plugins.
*/
abstract class HexTransformationsPlugin extends TransformationsPlugin
{
/**
* Gets the transformation description of the specific plugin
*
* @return string
*/
public static function getInfo()
{
return __(
'Displays hexadecimal representation of data. Optional first'
. ' parameter specifies how often space will be added (defaults'
. ' to 2 nibbles).'
);
}
/**
* Does the actual work of each specific transformations plugin.
*
* @param string $buffer text to be transformed
* @param array $options transformation options
* @param FieldMetadata|null $meta meta information
*
* @return string
*/
public function applyTransformation($buffer, array $options = [], ?FieldMetadata $meta = null)
{
// possibly use a global transform and feed it with special options
$cfg = $GLOBALS['cfg'];
$options = $this->getOptions($options, $cfg['DefaultTransformations']['Hex']);
$options[0] = intval($options[0]);
if ($options[0] < 1) {
return bin2hex($buffer);
}
return chunk_split(bin2hex($buffer), $options[0], ' ');
}
/* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */
/**
* Gets the transformation name of the specific plugin
*
* @return string
*/
public static function getName()
{
return 'Hex';
}
}

View file

@ -1,64 +0,0 @@
<?php
/**
* Abstract class for the link transformations plugins
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Transformations\Abs;
use PhpMyAdmin\FieldMetadata;
use PhpMyAdmin\Plugins\TransformationsPlugin;
use PhpMyAdmin\Url;
use function __;
use function htmlspecialchars;
/**
* Provides common methods for all of the link transformations plugins.
*/
abstract class ImageLinkTransformationsPlugin extends TransformationsPlugin
{
/**
* Gets the transformation description of the specific plugin
*
* @return string
*/
public static function getInfo()
{
return __('Displays a link to download this image.');
}
/**
* Does the actual work of each specific transformations plugin.
*
* @param string $buffer text to be transformed
* @param array $options transformation options
* @param FieldMetadata|null $meta meta information
*
* @return string
*/
public function applyTransformation($buffer, array $options = [], ?FieldMetadata $meta = null)
{
// must disable the page loader, see
// https://wiki.phpmyadmin.net/pma/Page_loader#Bypassing_the_page_loader
$link = '<a class="disableAjax" target="_blank" rel="noopener noreferrer" href="';
$link .= Url::getFromRoute('/transformation/wrapper', $options['wrapper_params']);
$link .= '" alt="[' . htmlspecialchars($buffer);
$link .= ']">[BLOB]</a>';
return $link;
}
/* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */
/**
* Gets the transformation name of the specific plugin
*
* @return string
*/
public static function getName()
{
return 'ImageLink';
}
}

View file

@ -1,120 +0,0 @@
<?php
/**
* Abstract class for the image upload input transformations plugins
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Transformations\Abs;
use PhpMyAdmin\FieldMetadata;
use PhpMyAdmin\Plugins\IOTransformationsPlugin;
use PhpMyAdmin\Url;
use function __;
use function bin2hex;
use function intval;
/**
* Provides common methods for all of the image upload transformations plugins.
*/
abstract class ImageUploadTransformationsPlugin extends IOTransformationsPlugin
{
/**
* Gets the transformation description of the specific plugin
*
* @return string
*/
public static function getInfo()
{
return __(
'Image upload functionality which also displays a thumbnail.'
. ' The options are the width and height of the thumbnail'
. ' in pixels. Defaults to 100 X 100.'
);
}
/**
* Does the actual work of each specific transformations plugin.
*
* @param string $buffer text to be transformed
* @param array $options transformation options
* @param FieldMetadata|null $meta meta information
*
* @return string
*/
public function applyTransformation($buffer, array $options = [], ?FieldMetadata $meta = null)
{
return $buffer;
}
/**
* Returns the html for input field to override default textarea.
* Note: Return empty string if default textarea is required.
*
* @param array $column column details
* @param int $row_id row number
* @param string $column_name_appendix the name attribute
* @param array $options transformation options
* @param string $value Current field value
* @param string $text_dir text direction
* @param int $tabindex tab index
* @param int $tabindex_for_value offset for the values tabindex
* @param int $idindex id index
*
* @return string the html for input field
*/
public function getInputHtml(
array $column,
$row_id,
$column_name_appendix,
array $options,
$value,
$text_dir,
$tabindex,
$tabindex_for_value,
$idindex
) {
$html = '';
$src = '';
if (! empty($value)) {
$html = '<input type="hidden" name="fields_prev' . $column_name_appendix
. '" value="' . bin2hex($value) . '">';
$html .= '<input type="hidden" name="fields' . $column_name_appendix
. '" value="' . bin2hex($value) . '">';
$src = Url::getFromRoute('/transformation/wrapper', $options['wrapper_params']);
}
$html .= '<img src="' . $src . '" width="'
. (isset($options[0]) ? intval($options[0]) : '100') . '" height="'
. (isset($options[1]) ? intval($options[1]) : '100') . '" alt="'
. __('Image preview here') . '">';
$html .= '<br><input type="file" name="fields_upload'
. $column_name_appendix . '" accept="image/*" class="image-upload">';
return $html;
}
/**
* Returns the array of scripts (filename) required for plugin
* initialization and handling
*
* @return array javascripts to be included
*/
public function getScripts()
{
return ['transformations/image_upload.js'];
}
/* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */
/**
* Gets the transformation name of the specific plugin
*
* @return string
*/
public static function getName()
{
return 'Image upload';
}
}

View file

@ -1,76 +0,0 @@
<?php
/**
* Abstract class for the inline transformations plugins
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Transformations\Abs;
use PhpMyAdmin\FieldMetadata;
use PhpMyAdmin\Plugins\TransformationsPlugin;
use PhpMyAdmin\Url;
use function __;
use function array_merge;
use function htmlspecialchars;
/**
* Provides common methods for all of the inline transformations plugins.
*/
abstract class InlineTransformationsPlugin extends TransformationsPlugin
{
/**
* Gets the transformation description of the specific plugin
*
* @return string
*/
public static function getInfo()
{
return __(
'Displays a clickable thumbnail. The options are the maximum width'
. ' and height in pixels. The original aspect ratio is preserved.'
);
}
/**
* Does the actual work of each specific transformations plugin.
*
* @param string $buffer text to be transformed
* @param array $options transformation options
* @param FieldMetadata|null $meta meta information
*
* @return string
*/
public function applyTransformation($buffer, array $options = [], ?FieldMetadata $meta = null)
{
$cfg = $GLOBALS['cfg'];
$options = $this->getOptions($options, $cfg['DefaultTransformations']['Inline']);
if ($GLOBALS['config']->get('PMA_IS_GD2') === 1) {
return '<a href="' . Url::getFromRoute('/transformation/wrapper', $options['wrapper_params'])
. '" rel="noopener noreferrer" target="_blank"><img src="'
. Url::getFromRoute('/transformation/wrapper', array_merge($options['wrapper_params'], [
'resize' => 'jpeg',
'newWidth' => (int) $options[0],
'newHeight' => (int) $options[1],
]))
. '" alt="[' . htmlspecialchars($buffer) . ']" border="0"></a>';
}
return '<img src="' . Url::getFromRoute('/transformation/wrapper', $options['wrapper_params'])
. '" alt="[' . htmlspecialchars($buffer) . ']" width="320" height="240">';
}
/* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */
/**
* Gets the transformation name of the specific plugin
*
* @return string
*/
public static function getName()
{
return 'Inline';
}
}

View file

@ -1,60 +0,0 @@
<?php
/**
* Abstract class for the long to IPv4 transformations plugins
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Transformations\Abs;
use PhpMyAdmin\FieldMetadata;
use PhpMyAdmin\Plugins\TransformationsPlugin;
use PhpMyAdmin\Utils\FormatConverter;
use function __;
use function htmlspecialchars;
/**
* Provides common methods for all of the long to IPv4 transformations plugins.
*/
abstract class LongToIPv4TransformationsPlugin extends TransformationsPlugin
{
/**
* Gets the transformation description of the specific plugin
*
* @return string
*/
public static function getInfo()
{
return __(
'Converts an (IPv4) Internet network address stored as a BIGINT'
. ' into a string in Internet standard dotted format.'
);
}
/**
* Does the actual work of each specific transformations plugin.
*
* @param string $buffer text to be transformed
* @param array $options transformation options
* @param FieldMetadata|null $meta meta information
*
* @return string
*/
public function applyTransformation($buffer, array $options = [], ?FieldMetadata $meta = null)
{
return htmlspecialchars(FormatConverter::longToIp($buffer));
}
/* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */
/**
* Gets the transformation name of the specific plugin
*
* @return string
*/
public static function getName()
{
return 'Long To IPv4';
}
}

View file

@ -1,65 +0,0 @@
<?php
/**
* Abstract class for the prepend/append transformations plugins
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Transformations\Abs;
use PhpMyAdmin\FieldMetadata;
use PhpMyAdmin\Plugins\TransformationsPlugin;
use function __;
use function htmlspecialchars;
/**
* Provides common methods for all of the prepend/append transformations plugins.
*/
abstract class PreApPendTransformationsPlugin extends TransformationsPlugin
{
/**
* Gets the transformation description of the specific plugin
*
* @return string
*/
public static function getInfo()
{
return __(
'Prepends and/or Appends text to a string. First option is text'
. ' to be prepended, second is appended (enclosed in single'
. ' quotes, default empty string).'
);
}
/**
* Does the actual work of each specific transformations plugin.
*
* @param string $buffer text to be transformed
* @param array $options transformation options
* @param FieldMetadata|null $meta meta information
*
* @return string
*/
public function applyTransformation($buffer, array $options = [], ?FieldMetadata $meta = null)
{
$cfg = $GLOBALS['cfg'];
$options = $this->getOptions($options, $cfg['DefaultTransformations']['PreApPend']);
//just prepend and/or append the options to the original text
return htmlspecialchars($options[0]) . htmlspecialchars($buffer)
. htmlspecialchars($options[1]);
}
/* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */
/**
* Gets the transformation name of the specific plugin
*
* @return string
*/
public static function getName()
{
return 'PreApPend';
}
}

View file

@ -1,73 +0,0 @@
<?php
/**
* Abstract class for the regex validation input transformations plugins
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Transformations\Abs;
use PhpMyAdmin\FieldMetadata;
use PhpMyAdmin\Plugins\IOTransformationsPlugin;
use function __;
use function htmlspecialchars;
use function preg_match;
use function sprintf;
/**
* Provides common methods for all of the regex validation
* input transformations plugins.
*/
abstract class RegexValidationTransformationsPlugin extends IOTransformationsPlugin
{
/**
* Gets the transformation description of the specific plugin
*
* @return string
*/
public static function getInfo()
{
return __(
'Validates the string using regular expression '
. 'and performs insert only if string matches it. '
. 'The first option is the Regular Expression.'
);
}
/**
* Does the actual work of each specific transformations plugin.
*
* @param string $buffer text to be transformed
* @param array $options transformation options
* @param FieldMetadata|null $meta meta information
*
* @return string
*/
public function applyTransformation($buffer, array $options = [], ?FieldMetadata $meta = null)
{
// reset properties of object
$this->reset();
if (! empty($options[0]) && ! preg_match($options[0], $buffer)) {
$this->success = false;
$this->error = sprintf(
__('Validation failed for the input string %s.'),
htmlspecialchars($buffer)
);
}
return $buffer;
}
/* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */
/**
* Gets the transformation name of the specific plugin
*
* @return string
*/
public static function getName()
{
return 'Regex Validation';
}
}

View file

@ -1,56 +0,0 @@
<?php
/**
* Abstract class for the SQL transformations plugins
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Transformations\Abs;
use PhpMyAdmin\FieldMetadata;
use PhpMyAdmin\Html\Generator;
use PhpMyAdmin\Plugins\TransformationsPlugin;
use function __;
/**
* Provides common methods for all of the SQL transformations plugins.
*/
abstract class SQLTransformationsPlugin extends TransformationsPlugin
{
/**
* Gets the transformation description of the specific plugin
*
* @return string
*/
public static function getInfo()
{
return __('Formats text as SQL query with syntax highlighting.');
}
/**
* Does the actual work of each specific transformations plugin.
*
* @param string $buffer text to be transformed
* @param array $options transformation options
* @param FieldMetadata|null $meta meta information
*
* @return string
*/
public function applyTransformation($buffer, array $options = [], ?FieldMetadata $meta = null)
{
return Generator::formatSql($buffer);
}
/* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */
/**
* Gets the transformation name of the specific plugin
*
* @return string
*/
public static function getName()
{
return 'SQL';
}
}

View file

@ -1,90 +0,0 @@
<?php
/**
* Abstract class for the substring transformations plugins
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Transformations\Abs;
use PhpMyAdmin\FieldMetadata;
use PhpMyAdmin\Plugins\TransformationsPlugin;
use function __;
use function htmlspecialchars;
use function mb_strlen;
use function mb_substr;
/**
* Provides common methods for all of the substring transformations plugins.
*/
abstract class SubstringTransformationsPlugin extends TransformationsPlugin
{
/**
* Gets the transformation description of the specific plugin
*
* @return string
*/
public static function getInfo()
{
return __(
'Displays a part of a string. The first option is the number of'
. ' characters to skip from the beginning of the string (Default 0).'
. ' The second option is the number of characters to return (Default:'
. ' until end of string). The third option is the string to append'
. ' and/or prepend when truncation occurs (Default: "…").'
);
}
/**
* Does the actual work of each specific transformations plugin.
*
* @param string $buffer text to be transformed
* @param array $options transformation options
* @param FieldMetadata|null $meta meta information
*
* @return string
*/
public function applyTransformation($buffer, array $options = [], ?FieldMetadata $meta = null)
{
// possibly use a global transform and feed it with special options
// further operations on $buffer using the $options[] array.
$cfg = $GLOBALS['cfg'];
$options = $this->getOptions($options, $cfg['DefaultTransformations']['Substring']);
$optionZero = (int) $options[0];
if ($options[1] !== 'all') {
$newtext = mb_substr((string) $buffer, $optionZero, (int) $options[1]);
} else {
$newtext = mb_substr((string) $buffer, $optionZero);
}
$length = mb_strlen($newtext);
$baselength = mb_strlen((string) $buffer);
if ($length != $baselength) {
if ($optionZero !== 0) {
$newtext = $options[2] . $newtext;
}
if ($length + $optionZero != $baselength) {
$newtext .= $options[2];
}
}
return htmlspecialchars($newtext);
}
/* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */
/**
* Gets the transformation name of the specific plugin
*
* @return string
*/
public static function getName()
{
return 'Substring';
}
}

View file

@ -1,98 +0,0 @@
<?php
/**
* Abstract class for the text file upload input transformations plugins
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Transformations\Abs;
use PhpMyAdmin\FieldMetadata;
use PhpMyAdmin\Plugins\IOTransformationsPlugin;
use function __;
use function htmlspecialchars;
/**
* Provides common methods for all of the text file upload
* input transformations plugins.
*/
abstract class TextFileUploadTransformationsPlugin extends IOTransformationsPlugin
{
/**
* Gets the transformation description of the specific plugin
*
* @return string
*/
public static function getInfo()
{
return __('File upload functionality for TEXT columns. It does not have a textarea for input.');
}
/**
* Does the actual work of each specific transformations plugin.
*
* @param string $buffer text to be transformed
* @param array $options transformation options
* @param FieldMetadata|null $meta meta information
*
* @return string
*/
public function applyTransformation($buffer, array $options = [], ?FieldMetadata $meta = null)
{
return $buffer;
}
/**
* Returns the html for input field to override default textarea.
* Note: Return empty string if default textarea is required.
*
* @param array $column column details
* @param int $row_id row number
* @param string $column_name_appendix the name attribute
* @param array $options transformation options
* @param string $value Current field value
* @param string $text_dir text direction
* @param int $tabindex tab index
* @param int $tabindex_for_value offset for the values tabindex
* @param int $idindex id index
*
* @return string the html for input field
*/
public function getInputHtml(
array $column,
$row_id,
$column_name_appendix,
array $options,
$value,
$text_dir,
$tabindex,
$tabindex_for_value,
$idindex
) {
$html = '';
if (! empty($value)) {
$html = '<input type="hidden" name="fields_prev' . $column_name_appendix
. '" value="' . htmlspecialchars($value) . '">';
$html .= '<input type="hidden" name="fields' . $column_name_appendix
. '" value="' . htmlspecialchars($value) . '">';
}
$html .= '<input type="file" name="fields_upload'
. $column_name_appendix . '">';
return $html;
}
/* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */
/**
* Gets the transformation name of the specific plugin
*
* @return string
*/
public static function getName()
{
return 'Text file upload';
}
}

View file

@ -1,77 +0,0 @@
<?php
/**
* Abstract class for the image link transformations plugins
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Transformations\Abs;
use PhpMyAdmin\FieldMetadata;
use PhpMyAdmin\Plugins\TransformationsPlugin;
use PhpMyAdmin\Sanitize;
use PhpMyAdmin\Template;
use function __;
use function htmlspecialchars;
/**
* Provides common methods for all of the image link transformations plugins.
*/
abstract class TextImageLinkTransformationsPlugin extends TransformationsPlugin
{
/**
* Gets the transformation description of the specific plugin
*
* @return string
*/
public static function getInfo()
{
return __(
'Displays an image and a link; the column contains the filename. The'
. ' first option is a URL prefix like "https://www.example.com/". The'
. ' second and third options are the width and the height in pixels.'
);
}
/**
* Does the actual work of each specific transformations plugin.
*
* @param string $buffer text to be transformed
* @param array $options transformation options
* @param FieldMetadata|null $meta meta information
*
* @return string
*/
public function applyTransformation($buffer, array $options = [], ?FieldMetadata $meta = null)
{
$cfg = $GLOBALS['cfg'];
$options = $this->getOptions($options, $cfg['DefaultTransformations']['TextImageLink']);
$url = $options[0] . $buffer;
/* Do not allow javascript links */
if (! Sanitize::checkLink($url, true, true)) {
return htmlspecialchars($url);
}
$template = new Template();
return $template->render('plugins/text_image_link_transformations', [
'url' => $url,
'width' => (int) $options[1],
'height' => (int) $options[2],
'buffer' => $buffer,
]);
}
/* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */
/**
* Gets the transformation name of the specific plugin
*
* @return string
*/
public static function getName()
{
return 'Image Link';
}
}

View file

@ -1,75 +0,0 @@
<?php
/**
* Abstract class for the link transformations plugins
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Transformations\Abs;
use PhpMyAdmin\FieldMetadata;
use PhpMyAdmin\Plugins\TransformationsPlugin;
use PhpMyAdmin\Sanitize;
use function __;
use function htmlspecialchars;
/**
* Provides common methods for all of the link transformations plugins.
*/
abstract class TextLinkTransformationsPlugin extends TransformationsPlugin
{
/**
* Gets the transformation description of the specific plugin
*
* @return string
*/
public static function getInfo()
{
return __(
'Displays a link; the column contains the filename. The first option'
. ' is a URL prefix like "https://www.example.com/". The second option'
. ' is a title for the link.'
);
}
/**
* Does the actual work of each specific transformations plugin.
*
* @param string $buffer text to be transformed
* @param array $options transformation options
* @param FieldMetadata|null $meta meta information
*
* @return string
*/
public function applyTransformation($buffer, array $options = [], ?FieldMetadata $meta = null)
{
$cfg = $GLOBALS['cfg'];
$options = $this->getOptions($options, $cfg['DefaultTransformations']['TextLink']);
$url = ($options[0] ?? '') . (isset($options[2]) && $options[2] ? '' : $buffer);
/* Do not allow javascript links */
if (! Sanitize::checkLink($url, true, true)) {
return htmlspecialchars($url);
}
return '<a href="'
. htmlspecialchars($url)
. '" title="'
. htmlspecialchars($options[1] ?? '')
. '" target="_blank" rel="noopener noreferrer">'
. htmlspecialchars($options[1] ?? $buffer)
. '</a>';
}
/* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */
/**
* Gets the transformation name of the specific plugin
*
* @return string
*/
public static function getName()
{
return 'TextLink';
}
}

View file

@ -1,37 +0,0 @@
<?php
/**
* Image JPEG Upload Input Transformations plugin for phpMyAdmin
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Transformations\Input;
use PhpMyAdmin\Plugins\Transformations\Abs\ImageUploadTransformationsPlugin;
/**
* Handles the image upload input transformation for JPEG.
* Has two option: width & height of the thumbnail
*/
class Image_JPEG_Upload extends ImageUploadTransformationsPlugin
{
/**
* Gets the plugin`s MIME type
*
* @return string
*/
public static function getMIMEType()
{
return 'Image';
}
/**
* Gets the plugin`s MIME subtype
*
* @return string
*/
public static function getMIMESubtype()
{
return 'JPEG';
}
}

View file

@ -1,36 +0,0 @@
<?php
/**
* Text Plain File Upload Input Transformations plugin for phpMyAdmin
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Transformations\Input;
use PhpMyAdmin\Plugins\Transformations\Abs\TextFileUploadTransformationsPlugin;
/**
* Handles the input text file upload transformation for text plain.
*/
class Text_Plain_FileUpload extends TextFileUploadTransformationsPlugin
{
/**
* Gets the plugin`s MIME type
*
* @return string
*/
public static function getMIMEType()
{
return 'Text';
}
/**
* Gets the plugin`s MIME subtype
*
* @return string
*/
public static function getMIMESubtype()
{
return 'Plain';
}
}

View file

@ -1,135 +0,0 @@
<?php
/**
* Handles the IPv4/IPv6 to binary transformation for text plain
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Transformations\Input;
use PhpMyAdmin\FieldMetadata;
use PhpMyAdmin\Plugins\IOTransformationsPlugin;
use PhpMyAdmin\Utils\FormatConverter;
use function __;
use function htmlspecialchars;
use function inet_ntop;
use function pack;
use function strlen;
/**
* Handles the IPv4/IPv6 to binary transformation for text plain
*/
class Text_Plain_Iptobinary extends IOTransformationsPlugin
{
/**
* Gets the transformation description of the plugin
*
* @return string
*/
public static function getInfo()
{
return __('Converts an Internet network address in (IPv4/IPv6) format to binary');
}
/**
* Does the actual work of each specific transformations plugin.
*
* @param string $buffer text to be transformed. a binary string containing
* an IP address, as returned from MySQL's INET6_ATON
* function
* @param array $options transformation options
* @param FieldMetadata|null $meta meta information
*
* @return string IP address
*/
public function applyTransformation($buffer, array $options = [], ?FieldMetadata $meta = null)
{
return FormatConverter::ipToBinary($buffer);
}
/**
* Returns the html for input field to override default textarea.
* Note: Return empty string if default textarea is required.
*
* @param array $column column details
* @param int $row_id row number
* @param string $column_name_appendix the name attribute
* @param array $options transformation options
* @param string $value Current field value
* @param string $text_dir text direction
* @param int $tabindex tab index
* @param int $tabindex_for_value offset for the values tabindex
* @param int $idindex id index
*
* @return string the html for input field
*/
public function getInputHtml(
array $column,
$row_id,
$column_name_appendix,
array $options,
$value,
$text_dir,
$tabindex,
$tabindex_for_value,
$idindex
) {
$html = '';
$val = '';
if (! empty($value)) {
$length = strlen($value);
if ($length == 4 || $length == 16) {
$ip = @inet_ntop(pack('A' . $length, $value));
if ($ip !== false) {
$val = $ip;
}
}
$html = '<input type="hidden" name="fields_prev' . $column_name_appendix
. '" value="' . htmlspecialchars($val) . '">';
}
$class = 'transform_IPToBin';
return $html . '<input type="text" name="fields' . $column_name_appendix . '"'
. ' value="' . htmlspecialchars($val) . '"'
. ' size="40"'
. ' dir="' . $text_dir . '"'
. ' class="' . $class . '"'
. ' id="field_' . $idindex . '_3"'
. ' tabindex="' . ($tabindex + $tabindex_for_value) . '">';
}
/* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */
/**
* Gets the transformation name of the plugin
*
* @return string
*/
public static function getName()
{
return 'IPv4/IPv6 To Binary';
}
/**
* Gets the plugin`s MIME type
*
* @return string
*/
public static function getMIMEType()
{
return 'Text';
}
/**
* Gets the plugin`s MIME subtype
*
* @return string
*/
public static function getMIMESubtype()
{
return 'Plain';
}
}

View file

@ -1,127 +0,0 @@
<?php
/**
* Handles the IPv4/IPv6 to long transformation for text plain
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Transformations\Input;
use PhpMyAdmin\FieldMetadata;
use PhpMyAdmin\Plugins\IOTransformationsPlugin;
use PhpMyAdmin\Utils\FormatConverter;
use function __;
use function htmlspecialchars;
/**
* Handles the IPv4/IPv6 to long transformation for text plain
*/
class Text_Plain_Iptolong extends IOTransformationsPlugin
{
/**
* Gets the transformation description of the plugin
*
* @return string
*/
public static function getInfo()
{
return __('Converts an Internet network address in (IPv4/IPv6) format into a long integer.');
}
/**
* Does the actual work of each specific transformations plugin.
*
* @param string $buffer text to be transformed. a binary string containing
* an IP address, as returned from MySQL's INET6_ATON
* function
* @param array $options transformation options
* @param FieldMetadata $meta meta information
*
* @return string IP address
*/
public function applyTransformation($buffer, array $options = [], ?FieldMetadata $meta = null)
{
return (string) FormatConverter::ipToLong($buffer);
}
/**
* Returns the html for input field to override default textarea.
* Note: Return empty string if default textarea is required.
*
* @param array $column column details
* @param int $row_id row number
* @param string $column_name_appendix the name attribute
* @param array $options transformation options
* @param string $value Current field value
* @param string $text_dir text direction
* @param int $tabindex tab index
* @param int $tabindex_for_value offset for the values tabindex
* @param int $idindex id index
*
* @return string the html for input field
*/
public function getInputHtml(
array $column,
$row_id,
$column_name_appendix,
array $options,
$value,
$text_dir,
$tabindex,
$tabindex_for_value,
$idindex
) {
$html = '';
$val = '';
if (! empty($value)) {
$val = FormatConverter::longToIp($value);
if ($value !== $val) {
$html = '<input type="hidden" name="fields_prev' . $column_name_appendix
. '" value="' . htmlspecialchars($val) . '"/>';
}
}
return $html . '<input type="text" name="fields' . $column_name_appendix . '"'
. ' value="' . htmlspecialchars($val) . '"'
. ' size="40"'
. ' dir="' . $text_dir . '"'
. ' class="transform_IPToLong"'
. ' id="field_' . $idindex . '_3"'
. ' tabindex="' . ($tabindex + $tabindex_for_value) . '" />';
}
/* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */
/**
* Gets the transformation name of the plugin
*
* @return string
*/
public static function getName()
{
return 'IPv4/IPv6 To Long';
}
/**
* Gets the plugin`s MIME type
*
* @return string
*/
public static function getMIMEType()
{
return 'Text';
}
/**
* Gets the plugin`s MIME subtype
*
* @return string
*/
public static function getMIMESubtype()
{
return 'Plain';
}
}

View file

@ -1,78 +0,0 @@
<?php
/**
* JSON editing with syntax highlighted CodeMirror editor
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Transformations\Input;
use PhpMyAdmin\Plugins\Transformations\Abs\CodeMirrorEditorTransformationPlugin;
use function __;
/**
* JSON editing with syntax highlighted CodeMirror editor
*/
class Text_Plain_JsonEditor extends CodeMirrorEditorTransformationPlugin
{
/**
* Gets the transformation description of the specific plugin
*
* @return string
*/
public static function getInfo()
{
return __('Syntax highlighted CodeMirror editor for JSON.');
}
/**
* Returns the array of scripts (filename) required for plugin
* initialization and handling
*
* @return array javascripts to be included
*/
public function getScripts()
{
$scripts = [];
if ($GLOBALS['cfg']['CodemirrorEnable']) {
$scripts[] = 'vendor/codemirror/lib/codemirror.js';
$scripts[] = 'vendor/codemirror/mode/javascript/javascript.js';
$scripts[] = 'transformations/json_editor.js';
}
return $scripts;
}
/* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */
/**
* Gets the transformation name of the specific plugin
*
* @return string
*/
public static function getName()
{
return 'JSON';
}
/**
* Gets the plugin`s MIME type
*
* @return string
*/
public static function getMIMEType()
{
return 'Text';
}
/**
* Gets the plugin`s MIME subtype
*
* @return string
*/
public static function getMIMESubtype()
{
return 'Plain';
}
}

View file

@ -1,37 +0,0 @@
<?php
/**
* Text Plain Regex Validation Input Transformations plugin for phpMyAdmin
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Transformations\Input;
use PhpMyAdmin\Plugins\Transformations\Abs\RegexValidationTransformationsPlugin;
/**
* Handles the input regex validation transformation for text plain.
* Has one option: the regular expression
*/
class Text_Plain_RegexValidation extends RegexValidationTransformationsPlugin
{
/**
* Gets the plugin`s MIME type
*
* @return string
*/
public static function getMIMEType()
{
return 'Text';
}
/**
* Gets the plugin`s MIME subtype
*
* @return string
*/
public static function getMIMESubtype()
{
return 'Plain';
}
}

View file

@ -1,78 +0,0 @@
<?php
/**
* SQL editing with syntax highlighted CodeMirror editor
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Transformations\Input;
use PhpMyAdmin\Plugins\Transformations\Abs\CodeMirrorEditorTransformationPlugin;
use function __;
/**
* SQL editing with syntax highlighted CodeMirror editor
*/
class Text_Plain_SqlEditor extends CodeMirrorEditorTransformationPlugin
{
/**
* Gets the transformation description of the specific plugin
*
* @return string
*/
public static function getInfo()
{
return __('Syntax highlighted CodeMirror editor for SQL.');
}
/**
* Returns the array of scripts (filename) required for plugin
* initialization and handling
*
* @return array javascripts to be included
*/
public function getScripts()
{
$scripts = [];
if ($GLOBALS['cfg']['CodemirrorEnable']) {
$scripts[] = 'vendor/codemirror/lib/codemirror.js';
$scripts[] = 'vendor/codemirror/mode/sql/sql.js';
$scripts[] = 'transformations/sql_editor.js';
}
return $scripts;
}
/* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */
/**
* Gets the transformation name of the specific plugin
*
* @return string
*/
public static function getName()
{
return 'SQL';
}
/**
* Gets the plugin`s MIME type
*
* @return string
*/
public static function getMIMEType()
{
return 'Text';
}
/**
* Gets the plugin`s MIME subtype
*
* @return string
*/
public static function getMIMESubtype()
{
return 'Plain';
}
}

View file

@ -1,78 +0,0 @@
<?php
/**
* XML (and HTML) editing with syntax highlighted CodeMirror editor
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Transformations\Input;
use PhpMyAdmin\Plugins\Transformations\Abs\CodeMirrorEditorTransformationPlugin;
use function __;
/**
* XML (and HTML) editing with syntax highlighted CodeMirror editor
*/
class Text_Plain_XmlEditor extends CodeMirrorEditorTransformationPlugin
{
/**
* Gets the transformation description of the specific plugin
*
* @return string
*/
public static function getInfo()
{
return __('Syntax highlighted CodeMirror editor for XML (and HTML).');
}
/**
* Returns the array of scripts (filename) required for plugin
* initialization and handling
*
* @return array javascripts to be included
*/
public function getScripts()
{
$scripts = [];
if ($GLOBALS['cfg']['CodemirrorEnable']) {
$scripts[] = 'vendor/codemirror/lib/codemirror.js';
$scripts[] = 'vendor/codemirror/mode/xml/xml.js';
$scripts[] = 'transformations/xml_editor.js';
}
return $scripts;
}
/* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */
/**
* Gets the transformation name of the specific plugin
*
* @return string
*/
public static function getName()
{
return 'XML';
}
/**
* Gets the plugin`s MIME type
*
* @return string
*/
public static function getMIMEType()
{
return 'Text';
}
/**
* Gets the plugin`s MIME subtype
*
* @return string
*/
public static function getMIMESubtype()
{
return 'Plain';
}
}

View file

@ -1,36 +0,0 @@
<?php
/**
* Application OctetStream Download Transformations plugin for phpMyAdmin
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Transformations\Output;
use PhpMyAdmin\Plugins\Transformations\Abs\DownloadTransformationsPlugin;
/**
* Handles the download transformation for application octetstream
*/
class Application_Octetstream_Download extends DownloadTransformationsPlugin
{
/**
* Gets the plugin`s MIME type
*
* @return string
*/
public static function getMIMEType()
{
return 'Application';
}
/**
* Gets the plugin`s MIME subtype
*
* @return string
*/
public static function getMIMESubtype()
{
return 'OctetStream';
}
}

View file

@ -1,36 +0,0 @@
<?php
/**
* Application OctetStream Hex Transformations plugin for phpMyAdmin
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Transformations\Output;
use PhpMyAdmin\Plugins\Transformations\Abs\HexTransformationsPlugin;
/**
* Handles the hex transformation for application octetstream
*/
class Application_Octetstream_Hex extends HexTransformationsPlugin
{
/**
* Gets the plugin`s MIME type
*
* @return string
*/
public static function getMIMEType()
{
return 'Application';
}
/**
* Gets the plugin`s MIME subtype
*
* @return string
*/
public static function getMIMESubtype()
{
return 'OctetStream';
}
}

View file

@ -1,36 +0,0 @@
<?php
/**
* Image JPEG Inline Transformations plugin for phpMyAdmin
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Transformations\Output;
use PhpMyAdmin\Plugins\Transformations\Abs\InlineTransformationsPlugin;
/**
* Handles the inline transformation for image jpeg
*/
class Image_JPEG_Inline extends InlineTransformationsPlugin
{
/**
* Gets the plugin`s MIME type
*
* @return string
*/
public static function getMIMEType()
{
return 'Image';
}
/**
* Gets the plugin`s MIME subtype
*
* @return string
*/
public static function getMIMESubtype()
{
return 'JPEG';
}
}

View file

@ -1,36 +0,0 @@
<?php
/**
* Image JPEG Link Transformations plugin for phpMyAdmin
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Transformations\Output;
use PhpMyAdmin\Plugins\Transformations\Abs\ImageLinkTransformationsPlugin;
/**
* Handles the link transformation for image jpeg
*/
class Image_JPEG_Link extends ImageLinkTransformationsPlugin
{
/**
* Gets the plugin`s MIME type
*
* @return string
*/
public static function getMIMEType()
{
return 'Image';
}
/**
* Gets the plugin`s MIME subtype
*
* @return string
*/
public static function getMIMESubtype()
{
return 'JPEG';
}
}

View file

@ -1,36 +0,0 @@
<?php
/**
* Image PNG Inline Transformations plugin for phpMyAdmin
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Transformations\Output;
use PhpMyAdmin\Plugins\Transformations\Abs\InlineTransformationsPlugin;
/**
* Handles the inline transformation for image png
*/
class Image_PNG_Inline extends InlineTransformationsPlugin
{
/**
* Gets the plugin`s MIME type
*
* @return string
*/
public static function getMIMEType()
{
return 'Image';
}
/**
* Gets the plugin`s MIME subtype
*
* @return string
*/
public static function getMIMESubtype()
{
return 'PNG';
}
}

View file

@ -1,36 +0,0 @@
<?php
/**
* Blob SQL Transformations plugin for phpMyAdmin
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Transformations\Output;
use PhpMyAdmin\Plugins\Transformations\Abs\SQLTransformationsPlugin;
/**
* Handles the sql transformation for blob data
*/
class Text_Octetstream_Sql extends SQLTransformationsPlugin
{
/**
* Gets the plugin`s MIME type
*
* @return string
*/
public static function getMIMEType()
{
return 'Text';
}
/**
* Gets the plugin`s MIME subtype
*
* @return string
*/
public static function getMIMESubtype()
{
return 'Octetstream';
}
}

View file

@ -1,83 +0,0 @@
<?php
/**
* Handles the binary to IPv4/IPv6 transformation for text plain
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Transformations\Output;
use PhpMyAdmin\FieldMetadata;
use PhpMyAdmin\Plugins\TransformationsPlugin;
use PhpMyAdmin\Utils\FormatConverter;
use function __;
/**
* Handles the binary to IPv4/IPv6 transformation for text plain
*/
class Text_Plain_Binarytoip extends TransformationsPlugin
{
/**
* Gets the transformation description of the plugin
*
* @return string
*/
public static function getInfo()
{
return __(
'Converts an Internet network address stored as a binary string'
. ' into a string in Internet standard (IPv4/IPv6) format.'
);
}
/**
* Does the actual work of each specific transformations plugin.
*
* @param string $buffer text to be transformed. a binary string containing
* an IP address, as returned from MySQL's INET6_ATON
* function
* @param array $options transformation options
* @param FieldMetadata|null $meta meta information
*
* @return string IP address
*/
public function applyTransformation($buffer, array $options = [], ?FieldMetadata $meta = null)
{
$isBinary = ($meta !== null && $meta->isBinary);
return FormatConverter::binaryToIp($buffer, $isBinary);
}
/* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */
/**
* Gets the transformation name of the plugin
*
* @return string
*/
public static function getName()
{
return 'Binary To IPv4/IPv6';
}
/**
* Gets the plugin`s MIME type
*
* @return string
*/
public static function getMIMEType()
{
return 'Text';
}
/**
* Gets the plugin`s MIME subtype
*
* @return string
*/
public static function getMIMESubtype()
{
return 'Plain';
}
}

View file

@ -1,38 +0,0 @@
<?php
/**
* Text Plain Bool2Text Transformations plugin for phpMyAdmin
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Transformations\Output;
use PhpMyAdmin\Plugins\Transformations\Abs\Bool2TextTransformationsPlugin;
/**
* Handles the Boolean to Text transformation for text plain.
* Has one option: the output format (default 'T/F')
* or 'Y/N'
*/
class Text_Plain_Bool2Text extends Bool2TextTransformationsPlugin
{
/**
* Gets the plugin`s MIME type
*
* @return string
*/
public static function getMIMEType()
{
return 'Text';
}
/**
* Gets the plugin`s MIME subtype
*
* @return string
*/
public static function getMIMESubtype()
{
return 'Plain';
}
}

View file

@ -1,36 +0,0 @@
<?php
/**
* Text Plain Date Format Transformations plugin for phpMyAdmin
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Transformations\Output;
use PhpMyAdmin\Plugins\Transformations\Abs\DateFormatTransformationsPlugin;
/**
* Handles the date format transformation for text plain
*/
class Text_Plain_Dateformat extends DateFormatTransformationsPlugin
{
/**
* Gets the plugin`s MIME type
*
* @return string
*/
public static function getMIMEType()
{
return 'Text';
}
/**
* Gets the plugin`s MIME subtype
*
* @return string
*/
public static function getMIMESubtype()
{
return 'Plain';
}
}

View file

@ -1,36 +0,0 @@
<?php
/**
* Text Plain External Transformations plugin for phpMyAdmin
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Transformations\Output;
use PhpMyAdmin\Plugins\Transformations\Abs\ExternalTransformationsPlugin;
/**
* Handles the external transformation for text plain
*/
class Text_Plain_External extends ExternalTransformationsPlugin
{
/**
* Gets the plugin`s MIME type
*
* @return string
*/
public static function getMIMEType()
{
return 'Text';
}
/**
* Gets the plugin`s MIME subtype
*
* @return string
*/
public static function getMIMESubtype()
{
return 'Plain';
}
}

Some files were not shown because too many files have changed in this diff Show more