Update website
This commit is contained in:
parent
a0b0d3dae7
commit
ae7ef6ad45
3151 changed files with 566766 additions and 48 deletions
|
@ -0,0 +1,175 @@
|
|||
<?php
|
||||
/**
|
||||
* Config Authentication plugin for phpMyAdmin
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpMyAdmin\Plugins\Auth;
|
||||
|
||||
use PhpMyAdmin\Html\Generator;
|
||||
use PhpMyAdmin\Plugins\AuthenticationPlugin;
|
||||
use PhpMyAdmin\Response;
|
||||
use PhpMyAdmin\Server\Select;
|
||||
use PhpMyAdmin\Util;
|
||||
use const E_USER_NOTICE;
|
||||
use const E_USER_WARNING;
|
||||
use function count;
|
||||
use function defined;
|
||||
use function sprintf;
|
||||
use function trigger_error;
|
||||
|
||||
/**
|
||||
* Handles the config authentication method
|
||||
*/
|
||||
class AuthenticationConfig extends AuthenticationPlugin
|
||||
{
|
||||
/**
|
||||
* Displays authentication form
|
||||
*
|
||||
* @return bool always true
|
||||
*/
|
||||
public function showLoginForm()
|
||||
{
|
||||
$response = Response::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()
|
||||
{
|
||||
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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function showFailure($failure)
|
||||
{
|
||||
global $dbi;
|
||||
|
||||
parent::showFailure($failure);
|
||||
$conn_error = $dbi->getError();
|
||||
if (! $conn_error) {
|
||||
$conn_error = __('Cannot connect: invalid settings.');
|
||||
}
|
||||
|
||||
/* HTML header */
|
||||
$response = Response::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 cellpadding="0" cellspacing="3" class= "pma-table auth_config_tbl" width="80%">
|
||||
<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['PMA_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['error_handler']->dispUserErrors();
|
||||
echo '</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>' , "\n";
|
||||
echo '<a href="'
|
||||
, Util::getScriptNameForOption(
|
||||
$GLOBALS['cfg']['DefaultTabServer'],
|
||||
'server'
|
||||
)
|
||||
, '" class="btn button mt-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;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,958 @@
|
|||
<?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\Response;
|
||||
use PhpMyAdmin\Server\Select;
|
||||
use PhpMyAdmin\Session;
|
||||
use PhpMyAdmin\Template;
|
||||
use PhpMyAdmin\Url;
|
||||
use PhpMyAdmin\Util;
|
||||
use PhpMyAdmin\Utils\SessionCache;
|
||||
use phpseclib\Crypt;
|
||||
use phpseclib\Crypt\Random;
|
||||
use ReCaptcha;
|
||||
use function base64_decode;
|
||||
use function base64_encode;
|
||||
use function class_exists;
|
||||
use function count;
|
||||
use function defined;
|
||||
use function explode;
|
||||
use function function_exists;
|
||||
use function hash_equals;
|
||||
use function hash_hmac;
|
||||
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 openssl_cipher_iv_length;
|
||||
use function openssl_decrypt;
|
||||
use function openssl_encrypt;
|
||||
use function openssl_error_string;
|
||||
use function openssl_random_pseudo_bytes;
|
||||
use function preg_match;
|
||||
use function session_id;
|
||||
use function strlen;
|
||||
use function substr;
|
||||
use function time;
|
||||
|
||||
/**
|
||||
* Handles the cookie authentication method
|
||||
*/
|
||||
class AuthenticationCookie extends AuthenticationPlugin
|
||||
{
|
||||
/**
|
||||
* IV for encryption
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
private $cookieIv = null;
|
||||
|
||||
/**
|
||||
* Whether to use OpenSSL directly
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
private $useOpenSsl;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
$this->useOpenSsl = ! class_exists(Random::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Forces (not)using of openSSL
|
||||
*
|
||||
* @param bool $use The flag
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function setUseOpenSSL($use)
|
||||
{
|
||||
$this->useOpenSsl = $use;
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays authentication form
|
||||
*
|
||||
* this function MUST exit/quit the application
|
||||
*
|
||||
* @return bool|void
|
||||
*
|
||||
* @global string $conn_error the last connection error
|
||||
*/
|
||||
public function showLoginForm()
|
||||
{
|
||||
global $conn_error, $route;
|
||||
|
||||
$response = Response::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', [
|
||||
'theme' => $GLOBALS['PMA_Theme'],
|
||||
'add_class' => ' modal_form',
|
||||
'session_expired' => 1,
|
||||
]);
|
||||
} else {
|
||||
$loginHeader = $this->template->render('login/header', [
|
||||
'theme' => $GLOBALS['PMA_Theme'],
|
||||
'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();
|
||||
}
|
||||
|
||||
$language_manager = LanguageManager::getInstance();
|
||||
$languageSelector = '';
|
||||
$hasLanguages = empty($GLOBALS['cfg']['Lang']) && $language_manager->hasChoice();
|
||||
if ($hasLanguages) {
|
||||
$languageSelector = $language_manager->getSelectorDisplay(new Template(), true, false);
|
||||
}
|
||||
|
||||
$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['error_handler']->hasDisplayErrors()) {
|
||||
$errors = $GLOBALS['error_handler']->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,
|
||||
'has_languages' => $hasLanguages,
|
||||
'language_selector' => $languageSelector,
|
||||
'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
|
||||
*
|
||||
* @return bool whether we get authentication settings or not
|
||||
*/
|
||||
public function readCredentials()
|
||||
{
|
||||
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['PMA_Config']->getCookie('pmaUser-' . $GLOBALS['server']);
|
||||
if (empty($serverCookie)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$value = $this->cookieDecrypt(
|
||||
$serverCookie,
|
||||
$this->getEncryptionSecret()
|
||||
);
|
||||
|
||||
if ($value === false) {
|
||||
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['PMA_Config']->getCookie('pmaAuth-' . $GLOBALS['server']);
|
||||
|
||||
if (empty($serverCookie)) {
|
||||
return false;
|
||||
}
|
||||
$value = $this->cookieDecrypt(
|
||||
$serverCookie,
|
||||
$this->getSessionEncryptionSecret()
|
||||
);
|
||||
if ($value === false) {
|
||||
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()
|
||||
{
|
||||
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.
|
||||
*
|
||||
* @return void|bool
|
||||
*/
|
||||
public function rememberCredentials()
|
||||
{
|
||||
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 = Response::getInstance();
|
||||
$response->addJSON(
|
||||
'logged_in',
|
||||
1
|
||||
);
|
||||
$response->addJSON(
|
||||
'success',
|
||||
1
|
||||
);
|
||||
$response->addJSON(
|
||||
'new_token',
|
||||
$_SESSION[' PMA_token ']
|
||||
);
|
||||
|
||||
if (! defined('TESTSUITE')) {
|
||||
exit;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
// Set server cookies if required (once per session) and, in this case,
|
||||
// force reload to ensure the client accepts cookies
|
||||
if (! $GLOBALS['from_cookie']) {
|
||||
|
||||
/**
|
||||
* Clear user cache.
|
||||
*/
|
||||
Util::clearUserCache();
|
||||
|
||||
Response::getInstance()
|
||||
->disable();
|
||||
|
||||
Core::sendHeaderLocation(
|
||||
'./index.php?route=/' . Url::getCommonRaw($url_params, '&'),
|
||||
true
|
||||
);
|
||||
if (! defined('TESTSUITE')) {
|
||||
exit;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores username in a cookie.
|
||||
*
|
||||
* @param string $username User name
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function storeUsernameCookie($username)
|
||||
{
|
||||
// Name and password cookies need to be refreshed each time
|
||||
// Duration = one month for username
|
||||
$GLOBALS['PMA_Config']->setCookie(
|
||||
'pmaUser-' . $GLOBALS['server'],
|
||||
$this->cookieEncrypt(
|
||||
$username,
|
||||
$this->getEncryptionSecret()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores password in a cookie.
|
||||
*
|
||||
* @param string $password Password
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function storePasswordCookie($password)
|
||||
{
|
||||
$payload = ['password' => $password];
|
||||
if ($GLOBALS['cfg']['AllowArbitraryServer'] && ! empty($GLOBALS['pma_auth_server'])) {
|
||||
$payload['server'] = $GLOBALS['pma_auth_server'];
|
||||
}
|
||||
// Duration = as configured
|
||||
$GLOBALS['PMA_Config']->setCookie(
|
||||
'pmaAuth-' . $GLOBALS['server'],
|
||||
$this->cookieEncrypt(
|
||||
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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function showFailure($failure)
|
||||
{
|
||||
global $conn_error;
|
||||
|
||||
parent::showFailure($failure);
|
||||
|
||||
// Deletes password cookie and displays the login form
|
||||
$GLOBALS['PMA_Config']->removeCookie('pmaAuth-' . $GLOBALS['server']);
|
||||
|
||||
$conn_error = $this->getErrorMessage($failure);
|
||||
|
||||
$response = Response::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.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function getEncryptionSecret()
|
||||
{
|
||||
if (empty($GLOBALS['cfg']['blowfish_secret'])) {
|
||||
return $this->getSessionEncryptionSecret();
|
||||
}
|
||||
|
||||
return $GLOBALS['cfg']['blowfish_secret'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns blowfish secret or generates one if needed.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function getSessionEncryptionSecret()
|
||||
{
|
||||
if (empty($_SESSION['encryption_key'])) {
|
||||
if ($this->useOpenSsl) {
|
||||
$_SESSION['encryption_key'] = openssl_random_pseudo_bytes(32);
|
||||
} else {
|
||||
$_SESSION['encryption_key'] = Crypt\Random::string(32);
|
||||
}
|
||||
}
|
||||
|
||||
return $_SESSION['encryption_key'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Concatenates secret in order to make it 16 bytes log
|
||||
*
|
||||
* This doesn't add any security, just ensures the secret
|
||||
* is long enough by copying it.
|
||||
*
|
||||
* @param string $secret Original secret
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function enlargeSecret($secret)
|
||||
{
|
||||
while (strlen($secret) < 16) {
|
||||
$secret .= $secret;
|
||||
}
|
||||
|
||||
return substr($secret, 0, 16);
|
||||
}
|
||||
|
||||
/**
|
||||
* Derives MAC secret from encryption secret.
|
||||
*
|
||||
* @param string $secret the secret
|
||||
*
|
||||
* @return string the MAC secret
|
||||
*/
|
||||
public function getMACSecret($secret)
|
||||
{
|
||||
// Grab first part, up to 16 chars
|
||||
// The MAC and AES secrets can overlap if original secret is short
|
||||
$length = strlen($secret);
|
||||
if ($length > 16) {
|
||||
return substr($secret, 0, 16);
|
||||
}
|
||||
|
||||
return $this->enlargeSecret(
|
||||
$length == 1 ? $secret : substr($secret, 0, -1)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Derives AES secret from encryption secret.
|
||||
*
|
||||
* @param string $secret the secret
|
||||
*
|
||||
* @return string the AES secret
|
||||
*/
|
||||
public function getAESSecret($secret)
|
||||
{
|
||||
// Grab second part, up to 16 chars
|
||||
// The MAC and AES secrets can overlap if original secret is short
|
||||
$length = strlen($secret);
|
||||
if ($length > 16) {
|
||||
return substr($secret, -16);
|
||||
}
|
||||
|
||||
return $this->enlargeSecret(
|
||||
$length == 1 ? $secret : substr($secret, 1)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleans any SSL errors
|
||||
*
|
||||
* This can happen from corrupted cookies, by invalid encryption
|
||||
* parameters used in older phpMyAdmin versions or by wrong openSSL
|
||||
* configuration.
|
||||
*
|
||||
* In neither case the error is useful to user, but we need to clear
|
||||
* the error buffer as otherwise the errors would pop up later, for
|
||||
* example during MySQL SSL setup.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function cleanSSLErrors()
|
||||
{
|
||||
if (! function_exists('openssl_error_string')) {
|
||||
return;
|
||||
}
|
||||
|
||||
do {
|
||||
$hasSslErrors = openssl_error_string();
|
||||
} while ($hasSslErrors !== false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Encryption using openssl's AES or phpseclib's AES
|
||||
* (phpseclib uses another extension when it is available)
|
||||
*
|
||||
* @param string $data original data
|
||||
* @param string $secret the secret
|
||||
*
|
||||
* @return string the encrypted result
|
||||
*/
|
||||
public function cookieEncrypt($data, $secret)
|
||||
{
|
||||
$mac_secret = $this->getMACSecret($secret);
|
||||
$aes_secret = $this->getAESSecret($secret);
|
||||
$iv = $this->createIV();
|
||||
if ($this->useOpenSsl) {
|
||||
$result = openssl_encrypt(
|
||||
$data,
|
||||
'AES-128-CBC',
|
||||
$aes_secret,
|
||||
0,
|
||||
$iv
|
||||
);
|
||||
} else {
|
||||
$cipher = new Crypt\AES(Crypt\Base::MODE_CBC);
|
||||
$cipher->setIV($iv);
|
||||
$cipher->setKey($aes_secret);
|
||||
$result = base64_encode($cipher->encrypt($data));
|
||||
}
|
||||
$this->cleanSSLErrors();
|
||||
$iv = base64_encode($iv);
|
||||
|
||||
return json_encode(
|
||||
[
|
||||
'iv' => $iv,
|
||||
'mac' => hash_hmac('sha1', $iv . $result, $mac_secret),
|
||||
'payload' => $result,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decryption using openssl's AES or phpseclib's AES
|
||||
* (phpseclib uses another extension when it is available)
|
||||
*
|
||||
* @param string $encdata encrypted data
|
||||
* @param string $secret the secret
|
||||
*
|
||||
* @return string|false original data, false on error
|
||||
*/
|
||||
public function cookieDecrypt($encdata, $secret)
|
||||
{
|
||||
$data = json_decode($encdata, true);
|
||||
|
||||
if (! isset($data['mac'], $data['iv'], $data['payload'])
|
||||
|| ! is_array($data)
|
||||
|| ! is_string($data['mac'])
|
||||
|| ! is_string($data['iv'])
|
||||
|| ! is_string($data['payload'])
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$mac_secret = $this->getMACSecret($secret);
|
||||
$aes_secret = $this->getAESSecret($secret);
|
||||
$newmac = hash_hmac('sha1', $data['iv'] . $data['payload'], $mac_secret);
|
||||
|
||||
if (! hash_equals($data['mac'], $newmac)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($this->useOpenSsl) {
|
||||
$result = openssl_decrypt(
|
||||
$data['payload'],
|
||||
'AES-128-CBC',
|
||||
$aes_secret,
|
||||
0,
|
||||
base64_decode($data['iv'])
|
||||
);
|
||||
} else {
|
||||
$cipher = new Crypt\AES(Crypt\Base::MODE_CBC);
|
||||
$cipher->setIV(base64_decode($data['iv']));
|
||||
$cipher->setKey($aes_secret);
|
||||
$result = $cipher->decrypt(base64_decode($data['payload']));
|
||||
}
|
||||
$this->cleanSSLErrors();
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns size of IV for encryption.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function getIVSize()
|
||||
{
|
||||
if ($this->useOpenSsl) {
|
||||
return openssl_cipher_iv_length('AES-128-CBC');
|
||||
}
|
||||
|
||||
return (new Crypt\AES(Crypt\Base::MODE_CBC))->block_size;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialization
|
||||
* Store the initialization vector because it will be needed for
|
||||
* further decryption. I don't think necessary to have one iv
|
||||
* per server so I don't put the server number in the cookie name.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function createIV()
|
||||
{
|
||||
/* Testsuite shortcut only to allow predictable IV */
|
||||
if ($this->cookieIv !== null) {
|
||||
return $this->cookieIv;
|
||||
}
|
||||
if ($this->useOpenSsl) {
|
||||
return openssl_random_pseudo_bytes(
|
||||
$this->getIVSize()
|
||||
);
|
||||
}
|
||||
|
||||
return Crypt\Random::string(
|
||||
$this->getIVSize()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets encryption IV to use
|
||||
*
|
||||
* This is for testing only!
|
||||
*
|
||||
* @param string $vector The IV
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function setIV($vector)
|
||||
{
|
||||
$this->cookieIv = $vector;
|
||||
}
|
||||
|
||||
/**
|
||||
* Callback when user changes password.
|
||||
*
|
||||
* @param string $password New password to set
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function handlePasswordChange($password)
|
||||
{
|
||||
$this->storePasswordCookie($password);
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform logout
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function logOut()
|
||||
{
|
||||
global $PMA_Config;
|
||||
|
||||
// -> delete password cookie(s)
|
||||
if ($GLOBALS['cfg']['LoginCookieDeleteAll']) {
|
||||
foreach ($GLOBALS['cfg']['Servers'] as $key => $val) {
|
||||
$PMA_Config->removeCookie('pmaAuth-' . $key);
|
||||
if (! $PMA_Config->issetCookie('pmaAuth-' . $key)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$PMA_Config->removeCookie('pmaAuth-' . $key);
|
||||
}
|
||||
} else {
|
||||
$cookieName = 'pmaAuth-' . $GLOBALS['server'];
|
||||
$PMA_Config->removeCookie($cookieName);
|
||||
if ($PMA_Config->issetCookie($cookieName)) {
|
||||
$PMA_Config->removeCookie($cookieName);
|
||||
}
|
||||
}
|
||||
parent::logOut();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,218 @@
|
|||
<?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\Response;
|
||||
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()
|
||||
{
|
||||
$response = Response::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
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function authForm()
|
||||
{
|
||||
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 = Response::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.')
|
||||
)
|
||||
);
|
||||
$response->addHTML('</h3>');
|
||||
|
||||
$response->addHTML(Config::renderFooter());
|
||||
|
||||
if (! defined('TESTSUITE')) {
|
||||
exit;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets authentication credentials
|
||||
*
|
||||
* @return bool whether we get authentication settings or not
|
||||
*/
|
||||
public function readCredentials()
|
||||
{
|
||||
// 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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function showFailure($failure)
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,299 @@
|
|||
<?php
|
||||
/**
|
||||
* SignOn Authentication plugin for phpMyAdmin
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpMyAdmin\Plugins\Auth;
|
||||
|
||||
use PhpMyAdmin\Core;
|
||||
use PhpMyAdmin\Plugins\AuthenticationPlugin;
|
||||
use PhpMyAdmin\Util;
|
||||
use const PHP_VERSION;
|
||||
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;
|
||||
|
||||
/**
|
||||
* Handles the SignOn authentication method
|
||||
*/
|
||||
class AuthenticationSignon extends AuthenticationPlugin
|
||||
{
|
||||
/**
|
||||
* Displays authentication form
|
||||
*
|
||||
* @return bool always true (no return indeed)
|
||||
*/
|
||||
public function showLoginForm()
|
||||
{
|
||||
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 = static function (string $key) {
|
||||
switch ($key) {
|
||||
case 'lifetime':
|
||||
return 0;
|
||||
case 'path':
|
||||
return '/';
|
||||
case 'domain':
|
||||
return '';
|
||||
case 'secure':
|
||||
return false;
|
||||
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', '>=')) {
|
||||
session_set_cookie_params($sessionCookieParams);
|
||||
} else {
|
||||
session_set_cookie_params(
|
||||
$sessionCookieParams['lifetime'],
|
||||
$sessionCookieParams['path'],
|
||||
$sessionCookieParams['domain'],
|
||||
$sessionCookieParams['secure'],
|
||||
$sessionCookieParams['httponly']
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets authentication credentials
|
||||
*
|
||||
* @return bool whether we get authentication settings or not
|
||||
*/
|
||||
public function readCredentials()
|
||||
{
|
||||
/* 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'];
|
||||
|
||||
/* Login URL */
|
||||
$signon_url = $GLOBALS['cfg']['Server']['SignonURL'];
|
||||
|
||||
/* 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 (! empty($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 !== null) {
|
||||
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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function showFailure($failure)
|
||||
{
|
||||
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'];
|
||||
}
|
||||
}
|
|
@ -0,0 +1,376 @@
|
|||
<?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\Response;
|
||||
use PhpMyAdmin\Session;
|
||||
use PhpMyAdmin\Template;
|
||||
use PhpMyAdmin\TwoFactor;
|
||||
use PhpMyAdmin\Url;
|
||||
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
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
abstract public function showLoginForm();
|
||||
|
||||
/**
|
||||
* Gets authentication credentials
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
abstract public function readCredentials();
|
||||
|
||||
/**
|
||||
* Set the user and password after last checkings if required
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function storeCredentials()
|
||||
{
|
||||
global $cfg;
|
||||
|
||||
$this->setSessionAccessTime();
|
||||
|
||||
$cfg['Server']['user'] = $this->user;
|
||||
$cfg['Server']['password'] = $this->password;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores user credentials after successful login.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function rememberCredentials()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* User is not allowed to login to MySQL -> authentication failed
|
||||
*
|
||||
* @param string $failure String describing why authentication has failed
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function showFailure($failure)
|
||||
{
|
||||
Logging::logUser($this->user, $failure);
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform logout
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function logOut()
|
||||
{
|
||||
global $PMA_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 ($GLOBALS['cfg']['Servers'] as $key => $val) {
|
||||
if (! $PMA_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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function handlePasswordChange($password)
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Store session access time in session.
|
||||
*
|
||||
* Tries to workaround PHP 5 session garbage collection which
|
||||
* looks at the session file's last modified time
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function setSessionAccessTime()
|
||||
{
|
||||
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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function authenticate()
|
||||
{
|
||||
$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();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check configuration defined restrictions for authentication
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function checkRules()
|
||||
{
|
||||
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 = Response::getInstance();
|
||||
if ($response->loginPage()) {
|
||||
if (defined('TESTSUITE')) {
|
||||
return;
|
||||
}
|
||||
|
||||
exit;
|
||||
}
|
||||
echo $this->template->render('login/header', ['theme' => $GLOBALS['PMA_Theme']]);
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,411 @@
|
|||
<?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 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;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
// initialize the specific export CodeGen variables
|
||||
$this->initSpecificVariables();
|
||||
$this->setProperties();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the local variables that are used for export CodeGen
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function initSpecificVariables()
|
||||
{
|
||||
$this->setCgFormats([
|
||||
self::HANDLER_NHIBERNATE_CS => 'NHibernate C# DO',
|
||||
self::HANDLER_NHIBERNATE_XML => 'NHibernate XML',
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the export CodeGen properties
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function setProperties()
|
||||
{
|
||||
$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);
|
||||
$this->properties = $exportPluginProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs export header
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportHeader()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs export footer
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportFooter()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs database header
|
||||
*
|
||||
* @param string $db Database name
|
||||
* @param string $db_alias Aliases of db
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBHeader($db, $db_alias = '')
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs database footer
|
||||
*
|
||||
* @param string $db Database name
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBFooter($db)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs CREATE DATABASE statement
|
||||
*
|
||||
* @param string $db Database name
|
||||
* @param string $export_type 'server', 'database', 'table'
|
||||
* @param string $db_alias Aliases of db
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBCreate($db, $export_type, $db_alias = '')
|
||||
{
|
||||
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 $error_url the url to go back in case of error
|
||||
* @param string $sql_query SQL query for obtaining data
|
||||
* @param array $aliases Aliases of db/table/columns
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportData(
|
||||
$db,
|
||||
$table,
|
||||
$crlf,
|
||||
$error_url,
|
||||
$sql_query,
|
||||
array $aliases = []
|
||||
) {
|
||||
$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);
|
||||
$lines = [];
|
||||
|
||||
$result = $dbi->query(
|
||||
sprintf(
|
||||
'DESC %s.%s',
|
||||
Util::backquote($db),
|
||||
Util::backquote($table)
|
||||
)
|
||||
);
|
||||
if ($result) {
|
||||
/** @var TableProperty[] $tableProperties */
|
||||
$tableProperties = [];
|
||||
while ($row = $dbi->fetchRow($result)) {
|
||||
$col_as = $this->getAlias($aliases, $row[0], 'col', $db, $table);
|
||||
if (! empty($col_as)) {
|
||||
$row[0] = $col_as;
|
||||
}
|
||||
$tableProperties[] = new TableProperty($row);
|
||||
}
|
||||
$dbi->freeResult($result);
|
||||
$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)
|
||||
)
|
||||
);
|
||||
if ($result) {
|
||||
while ($row = $dbi->fetchRow($result)) {
|
||||
$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>'
|
||||
);
|
||||
}
|
||||
}
|
||||
$dbi->freeResult($result);
|
||||
}
|
||||
$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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function setCgFormats(array $CG_FORMATS)
|
||||
{
|
||||
$this->cgFormats = $CG_FORMATS;
|
||||
}
|
||||
}
|
358
admin/phpMyAdmin/libraries/classes/Plugins/Export/ExportCsv.php
Normal file
358
admin/phpMyAdmin/libraries/classes/Plugins/Export/ExportCsv.php
Normal file
|
@ -0,0 +1,358 @@
|
|||
<?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 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
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
$this->setProperties();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the export CSV properties
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function setProperties()
|
||||
{
|
||||
$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);
|
||||
$this->properties = $exportPluginProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs export header
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportHeader()
|
||||
{
|
||||
global $what, $csv_terminated, $csv_separator, $csv_enclosed, $csv_escaped;
|
||||
//Enable columns names by default for CSV
|
||||
if ($what === 'csv') {
|
||||
$GLOBALS['csv_columns'] = 'yes';
|
||||
}
|
||||
// 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'] = 'yes';
|
||||
}
|
||||
} 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
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportFooter()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs database header
|
||||
*
|
||||
* @param string $db Database name
|
||||
* @param string $db_alias Alias of db
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBHeader($db, $db_alias = '')
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs database footer
|
||||
*
|
||||
* @param string $db Database name
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBFooter($db)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs CREATE DATABASE statement
|
||||
*
|
||||
* @param string $db Database name
|
||||
* @param string $export_type 'server', 'database', 'table'
|
||||
* @param string $db_alias Aliases of db
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBCreate($db, $export_type, $db_alias = '')
|
||||
{
|
||||
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 $error_url the url to go back in case of error
|
||||
* @param string $sql_query SQL query for obtaining data
|
||||
* @param array $aliases Aliases of db/table/columns
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportData(
|
||||
$db,
|
||||
$table,
|
||||
$crlf,
|
||||
$error_url,
|
||||
$sql_query,
|
||||
array $aliases = []
|
||||
) {
|
||||
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(
|
||||
$sql_query,
|
||||
DatabaseInterface::CONNECT_USER,
|
||||
DatabaseInterface::QUERY_UNBUFFERED
|
||||
);
|
||||
$fields_cnt = $dbi->numFields($result);
|
||||
|
||||
// If required, get fields name at the first line
|
||||
if (isset($GLOBALS['csv_columns'])) {
|
||||
$schema_insert = '';
|
||||
for ($i = 0; $i < $fields_cnt; $i++) {
|
||||
$col_as = $dbi->fieldName($result, $i);
|
||||
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 = $dbi->fetchRow($result)) {
|
||||
$schema_insert = '';
|
||||
for ($j = 0; $j < $fields_cnt; $j++) {
|
||||
if (! isset($row[$j]) || $row[$j] === null) {
|
||||
$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;
|
||||
}
|
||||
}
|
||||
$dbi->freeResult($result);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs result of raw query in CSV format
|
||||
*
|
||||
* @param string $err_url the url to go back in case of error
|
||||
* @param string $sql_query the rawquery to output
|
||||
* @param string $crlf the end of line sequence
|
||||
*
|
||||
* @return bool if succeeded
|
||||
*/
|
||||
public function exportRawQuery(string $err_url, string $sql_query, string $crlf): bool
|
||||
{
|
||||
return $this->exportData('', '', $crlf, $err_url, $sql_query);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,84 @@
|
|||
<?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;
|
||||
|
||||
/**
|
||||
* Handles the export for the CSV-Excel format
|
||||
*/
|
||||
class ExportExcel extends ExportCsv
|
||||
{
|
||||
/**
|
||||
* Sets the export CSV for Excel properties
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function setProperties()
|
||||
{
|
||||
$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);
|
||||
$this->properties = $exportPluginProperties;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,674 @@
|
|||
<?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 htmlspecialchars;
|
||||
use function in_array;
|
||||
use function str_replace;
|
||||
use function stripslashes;
|
||||
|
||||
/**
|
||||
* Handles the export for the HTML-Word format
|
||||
*/
|
||||
class ExportHtmlword extends ExportPlugin
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
$this->setProperties();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the export HTML-Word properties
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function setProperties()
|
||||
{
|
||||
$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);
|
||||
$this->properties = $exportPluginProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs export header
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportHeader()
|
||||
{
|
||||
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
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportFooter()
|
||||
{
|
||||
return $this->export->outputHandler('</body></html>');
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs database header
|
||||
*
|
||||
* @param string $db Database name
|
||||
* @param string $db_alias Aliases of db
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBHeader($db, $db_alias = '')
|
||||
{
|
||||
if (empty($db_alias)) {
|
||||
$db_alias = $db;
|
||||
}
|
||||
|
||||
return $this->export->outputHandler(
|
||||
'<h1>' . __('Database') . ' ' . htmlspecialchars($db_alias) . '</h1>'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs database footer
|
||||
*
|
||||
* @param string $db Database name
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBFooter($db)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs CREATE DATABASE statement
|
||||
*
|
||||
* @param string $db Database name
|
||||
* @param string $export_type 'server', 'database', 'table'
|
||||
* @param string $db_alias Aliases of db
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBCreate($db, $export_type, $db_alias = '')
|
||||
{
|
||||
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 $error_url the url to go back in case of error
|
||||
* @param string $sql_query SQL query for obtaining data
|
||||
* @param array $aliases Aliases of db/table/columns
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportData(
|
||||
$db,
|
||||
$table,
|
||||
$crlf,
|
||||
$error_url,
|
||||
$sql_query,
|
||||
array $aliases = []
|
||||
) {
|
||||
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 class="pma-table w-100" cellspacing="1">'
|
||||
)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Gets the data from the database
|
||||
$result = $dbi->query(
|
||||
$sql_query,
|
||||
DatabaseInterface::CONNECT_USER,
|
||||
DatabaseInterface::QUERY_UNBUFFERED
|
||||
);
|
||||
$fields_cnt = $dbi->numFields($result);
|
||||
|
||||
// If required, get fields name at the first line
|
||||
if (isset($GLOBALS['htmlword_columns'])) {
|
||||
$schema_insert = '<tr class="print-category">';
|
||||
for ($i = 0; $i < $fields_cnt; $i++) {
|
||||
$col_as = $dbi->fieldName($result, $i);
|
||||
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 = $dbi->fetchRow($result)) {
|
||||
$schema_insert = '<tr class="print-category">';
|
||||
for ($j = 0; $j < $fields_cnt; $j++) {
|
||||
if (! isset($row[$j]) || $row[$j] === null) {
|
||||
$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;
|
||||
}
|
||||
}
|
||||
$dbi->freeResult($result);
|
||||
|
||||
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 class="pma-table w-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;
|
||||
|
||||
// set $cfgRelation here, because there is a chance that it's modified
|
||||
// since the class initialization
|
||||
global $cfgRelation;
|
||||
|
||||
$schema_insert = '';
|
||||
|
||||
/**
|
||||
* Gets fields properties
|
||||
*/
|
||||
$dbi->selectDb($db);
|
||||
|
||||
// Check if we can use Relations
|
||||
[$res_rel, $have_rel] = $this->relation->getRelationsAndStatus(
|
||||
$do_relation && ! empty($cfgRelation['relation']),
|
||||
$db,
|
||||
$table
|
||||
);
|
||||
|
||||
/**
|
||||
* Displays the table structure
|
||||
*/
|
||||
$schema_insert .= '<table class="pma-table w-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 && $cfgRelation['mimework']) {
|
||||
$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 && $cfgRelation['commwork']) {
|
||||
$schema_insert .= '<td class="print">'
|
||||
. (isset($comments[$field_name])
|
||||
? htmlspecialchars($comments[$field_name])
|
||||
: '') . '</td>';
|
||||
}
|
||||
if ($do_mime && $cfgRelation['mimework']) {
|
||||
$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 class="pma-table w-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 $error_url the url to go back in case of error
|
||||
* @param string $export_mode 'create_table', 'triggers', 'create_view',
|
||||
* 'stand_in'
|
||||
* @param string $export_type '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
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportStructure(
|
||||
$db,
|
||||
$table,
|
||||
$crlf,
|
||||
$error_url,
|
||||
$export_mode,
|
||||
$export_type,
|
||||
$do_relation = false,
|
||||
$do_comments = false,
|
||||
$do_mime = false,
|
||||
$dates = false,
|
||||
array $aliases = []
|
||||
) {
|
||||
global $dbi;
|
||||
|
||||
$db_alias = $db;
|
||||
$table_alias = $table;
|
||||
$this->initAlias($aliases, $db_alias, $table_alias);
|
||||
|
||||
$dump = '';
|
||||
|
||||
switch ($export_mode) {
|
||||
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 = ' ';
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
375
admin/phpMyAdmin/libraries/classes/Plugins/Export/ExportJson.php
Normal file
375
admin/phpMyAdmin/libraries/classes/Plugins/Export/ExportJson.php
Normal file
|
@ -0,0 +1,375 @@
|
|||
<?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\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 const JSON_PRETTY_PRINT;
|
||||
use const JSON_UNESCAPED_UNICODE;
|
||||
use function bin2hex;
|
||||
use function explode;
|
||||
use function json_encode;
|
||||
use function stripslashes;
|
||||
|
||||
/**
|
||||
* Handles the export for the JSON format
|
||||
*/
|
||||
class ExportJson extends ExportPlugin
|
||||
{
|
||||
/** @var bool */
|
||||
private $first = true;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
$this->setProperties();
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes the data into JSON
|
||||
*
|
||||
* @param mixed $data Data to encode
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the export JSON properties
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function setProperties()
|
||||
{
|
||||
$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);
|
||||
$this->properties = $exportPluginProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs export header
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportHeader()
|
||||
{
|
||||
global $crlf;
|
||||
|
||||
$meta = [
|
||||
'type' => 'header',
|
||||
'version' => PMA_VERSION,
|
||||
'comment' => 'Export to JSON plugin for PHPMyAdmin',
|
||||
];
|
||||
|
||||
return $this->export->outputHandler(
|
||||
'[' . $crlf . $this->encode($meta) . ',' . $crlf
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs export footer
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportFooter()
|
||||
{
|
||||
global $crlf;
|
||||
|
||||
return $this->export->outputHandler(']' . $crlf);
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs database header
|
||||
*
|
||||
* @param string $db Database name
|
||||
* @param string $db_alias Aliases of db
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBHeader($db, $db_alias = '')
|
||||
{
|
||||
global $crlf;
|
||||
|
||||
if (empty($db_alias)) {
|
||||
$db_alias = $db;
|
||||
}
|
||||
|
||||
$meta = [
|
||||
'type' => 'database',
|
||||
'name' => $db_alias,
|
||||
];
|
||||
|
||||
return $this->export->outputHandler(
|
||||
$this->encode($meta) . ',' . $crlf
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs database footer
|
||||
*
|
||||
* @param string $db Database name
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBFooter($db)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs CREATE DATABASE statement
|
||||
*
|
||||
* @param string $db Database name
|
||||
* @param string $export_type 'server', 'database', 'table'
|
||||
* @param string $db_alias Aliases of db
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBCreate($db, $export_type, $db_alias = '')
|
||||
{
|
||||
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 $error_url the url to go back in case of error
|
||||
* @param string $sql_query SQL query for obtaining data
|
||||
* @param array $aliases Aliases of db/table/columns
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportData(
|
||||
$db,
|
||||
$table,
|
||||
$crlf,
|
||||
$error_url,
|
||||
$sql_query,
|
||||
array $aliases = []
|
||||
) {
|
||||
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@@',
|
||||
]
|
||||
);
|
||||
|
||||
return $this->doExportForQuery(
|
||||
$dbi,
|
||||
$sql_query,
|
||||
$buffer,
|
||||
$crlf,
|
||||
$aliases,
|
||||
$db,
|
||||
$table
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Export to JSON
|
||||
*
|
||||
* @return bool False on export fail and true on export end success
|
||||
*
|
||||
* @phpstan-param array{
|
||||
* string: array{
|
||||
* 'tables': array{
|
||||
* string: array{
|
||||
* 'columns': array{string: string}
|
||||
* }
|
||||
* }
|
||||
* }
|
||||
* }|array|null $aliases
|
||||
*/
|
||||
protected function doExportForQuery(
|
||||
DatabaseInterface $dbi,
|
||||
string $sql_query,
|
||||
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(
|
||||
$sql_query,
|
||||
DatabaseInterface::CONNECT_USER,
|
||||
DatabaseInterface::QUERY_UNBUFFERED
|
||||
);
|
||||
$columns_cnt = $dbi->numFields($result);
|
||||
$fieldsMeta = $dbi->getFieldsMeta($result);
|
||||
|
||||
$columns = [];
|
||||
for ($i = 0; $i < $columns_cnt; $i++) {
|
||||
$col_as = $dbi->fieldName($result, $i);
|
||||
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 = $dbi->fetchRow($result)) {
|
||||
$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 = $fieldsMeta[$i]->type === 'blob' && $fieldsMeta[$i]->charsetnr === 63;
|
||||
// This can occur for binary fields
|
||||
$isBinaryString = $fieldsMeta[$i]->type === 'string' && $fieldsMeta[$i]->charsetnr === 63;
|
||||
if (
|
||||
(
|
||||
$fieldsMeta[$i]->type === 'geometry'
|
||||
|| $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;
|
||||
}
|
||||
}
|
||||
|
||||
if (! $this->export->outputHandler($crlf . ']' . $crlf . $footer . $crlf)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$dbi->freeResult($result);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs result raw query in JSON format
|
||||
*
|
||||
* @param string $err_url the url to go back in case of error
|
||||
* @param string $sql_query the rawquery to output
|
||||
* @param string $crlf the end of line sequence
|
||||
*
|
||||
* @return bool if succeeded
|
||||
*/
|
||||
public function exportRawQuery(string $err_url, string $sql_query, string $crlf): bool
|
||||
{
|
||||
global $dbi;
|
||||
|
||||
$buffer = $this->encode(
|
||||
[
|
||||
'type' => 'raw',
|
||||
'data' => '@@DATA@@',
|
||||
]
|
||||
);
|
||||
|
||||
return $this->doExportForQuery(
|
||||
$dbi,
|
||||
$sql_query,
|
||||
$buffer,
|
||||
$crlf,
|
||||
null,
|
||||
null,
|
||||
null
|
||||
);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,723 @@
|
|||
<?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 const PHP_VERSION;
|
||||
use function count;
|
||||
use function in_array;
|
||||
use function mb_strpos;
|
||||
use function mb_substr;
|
||||
use function str_replace;
|
||||
use function stripslashes;
|
||||
|
||||
/**
|
||||
* Handles the export for the Latex format
|
||||
*/
|
||||
class ExportLatex extends ExportPlugin
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
// initialize the specific export sql variables
|
||||
$this->initSpecificVariables();
|
||||
$this->setProperties();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the local variables that are used for export Latex
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function initSpecificVariables()
|
||||
{
|
||||
/* Messages used in default captions */
|
||||
$GLOBALS['strLatexContent'] = __('Content of table @TABLE@');
|
||||
$GLOBALS['strLatexContinued'] = __('(continued)');
|
||||
$GLOBALS['strLatexStructure'] = __('Structure of table @TABLE@');
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the export Latex properties
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function setProperties()
|
||||
{
|
||||
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);
|
||||
if (! empty($GLOBALS['cfgRelation']['relation'])) {
|
||||
$leaf = new BoolPropertyItem(
|
||||
'relation',
|
||||
__('Display foreign key relationships')
|
||||
);
|
||||
$structureOptions->addProperty($leaf);
|
||||
}
|
||||
$leaf = new BoolPropertyItem(
|
||||
'comments',
|
||||
__('Display comments')
|
||||
);
|
||||
$structureOptions->addProperty($leaf);
|
||||
if (! empty($GLOBALS['cfgRelation']['mimework'])) {
|
||||
$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);
|
||||
$this->properties = $exportPluginProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs export header
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportHeader()
|
||||
{
|
||||
global $crlf, $cfg, $dbi;
|
||||
|
||||
$head = '% phpMyAdmin LaTeX Dump' . $crlf
|
||||
. '% version ' . PMA_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
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportFooter()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs database header
|
||||
*
|
||||
* @param string $db Database name
|
||||
* @param string $db_alias Aliases of db
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBHeader($db, $db_alias = '')
|
||||
{
|
||||
if (empty($db_alias)) {
|
||||
$db_alias = $db;
|
||||
}
|
||||
global $crlf;
|
||||
$head = '% ' . $crlf
|
||||
. '% ' . __('Database:') . ' \'' . $db_alias . '\'' . $crlf
|
||||
. '% ' . $crlf;
|
||||
|
||||
return $this->export->outputHandler($head);
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs database footer
|
||||
*
|
||||
* @param string $db Database name
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBFooter($db)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs CREATE DATABASE statement
|
||||
*
|
||||
* @param string $db Database name
|
||||
* @param string $export_type 'server', 'database', 'table'
|
||||
* @param string $db_alias Aliases of db
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBCreate($db, $export_type, $db_alias = '')
|
||||
{
|
||||
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 $error_url the url to go back in case of error
|
||||
* @param string $sql_query SQL query for obtaining data
|
||||
* @param array $aliases Aliases of db/table/columns
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportData(
|
||||
$db,
|
||||
$table,
|
||||
$crlf,
|
||||
$error_url,
|
||||
$sql_query,
|
||||
array $aliases = []
|
||||
) {
|
||||
global $dbi;
|
||||
|
||||
$db_alias = $db;
|
||||
$table_alias = $table;
|
||||
$this->initAlias($aliases, $db_alias, $table_alias);
|
||||
|
||||
$result = $dbi->tryQuery(
|
||||
$sql_query,
|
||||
DatabaseInterface::CONNECT_USER,
|
||||
DatabaseInterface::QUERY_UNBUFFERED
|
||||
);
|
||||
|
||||
$columns_cnt = $dbi->numFields($result);
|
||||
$columns = [];
|
||||
$columns_alias = [];
|
||||
for ($i = 0; $i < $columns_cnt; $i++) {
|
||||
$columns[$i] = $col_as = $dbi->fieldName($result, $i);
|
||||
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 = $dbi->fetchAssoc($result)) {
|
||||
$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;
|
||||
if (! $this->export->outputHandler($buffer)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$dbi->freeResult($result);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs result raw query
|
||||
*
|
||||
* @param string $err_url the url to go back in case of error
|
||||
* @param string $sql_query the rawquery to output
|
||||
* @param string $crlf the seperator for a file
|
||||
*
|
||||
* @return bool if succeeded
|
||||
*/
|
||||
public function exportRawQuery(string $err_url, string $sql_query, string $crlf): bool
|
||||
{
|
||||
return $this->exportData('', '', $crlf, $err_url, $sql_query);
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs table's structure
|
||||
*
|
||||
* @param string $db database name
|
||||
* @param string $table table name
|
||||
* @param string $crlf the end of line sequence
|
||||
* @param string $error_url the url to go back in case of error
|
||||
* @param string $export_mode 'create_table', 'triggers', 'create_view',
|
||||
* 'stand_in'
|
||||
* @param string $export_type '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
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportStructure(
|
||||
$db,
|
||||
$table,
|
||||
$crlf,
|
||||
$error_url,
|
||||
$export_mode,
|
||||
$export_type,
|
||||
$do_relation = false,
|
||||
$do_comments = false,
|
||||
$do_mime = false,
|
||||
$dates = false,
|
||||
array $aliases = []
|
||||
) {
|
||||
global $dbi;
|
||||
|
||||
$db_alias = $db;
|
||||
$table_alias = $table;
|
||||
$this->initAlias($aliases, $db_alias, $table_alias);
|
||||
|
||||
global $cfgRelation;
|
||||
|
||||
/* We do not export triggers */
|
||||
if ($export_mode === '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 && ! empty($cfgRelation['relation']),
|
||||
$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 && $cfgRelation['mimework']) {
|
||||
$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 && $cfgRelation['mimework']) {
|
||||
$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 && $cfgRelation['commwork']) {
|
||||
$local_buffer .= "\000";
|
||||
if (isset($comments[$field_name])) {
|
||||
$local_buffer .= $comments[$field_name];
|
||||
}
|
||||
}
|
||||
if ($do_mime && $cfgRelation['mimework']) {
|
||||
$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;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,400 @@
|
|||
<?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 array_values;
|
||||
use function count;
|
||||
use function htmlspecialchars;
|
||||
use function str_repeat;
|
||||
|
||||
/**
|
||||
* Handles the export for the MediaWiki class
|
||||
*/
|
||||
class ExportMediawiki extends ExportPlugin
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
$this->setProperties();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the export MediaWiki properties
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function setProperties()
|
||||
{
|
||||
$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);
|
||||
$this->properties = $exportPluginProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs export header
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportHeader()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs export footer
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportFooter()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs database header
|
||||
*
|
||||
* @param string $db Database name
|
||||
* @param string $db_alias Alias of db
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBHeader($db, $db_alias = '')
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs database footer
|
||||
*
|
||||
* @param string $db Database name
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBFooter($db)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs CREATE DATABASE statement
|
||||
*
|
||||
* @param string $db Database name
|
||||
* @param string $export_type 'server', 'database', 'table'
|
||||
* @param string $db_alias Aliases of db
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBCreate($db, $export_type, $db_alias = '')
|
||||
{
|
||||
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 $error_url the url to go back in case of error
|
||||
* @param string $export_mode 'create_table','triggers','create_view',
|
||||
* 'stand_in'
|
||||
* @param string $export_type '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
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportStructure(
|
||||
$db,
|
||||
$table,
|
||||
$crlf,
|
||||
$error_url,
|
||||
$export_mode,
|
||||
$export_type,
|
||||
$do_relation = false,
|
||||
$do_comments = false,
|
||||
$do_mime = false,
|
||||
$dates = false,
|
||||
array $aliases = []
|
||||
) {
|
||||
global $dbi;
|
||||
|
||||
$db_alias = $db;
|
||||
$table_alias = $table;
|
||||
$this->initAlias($aliases, $db_alias, $table_alias);
|
||||
|
||||
$output = '';
|
||||
switch ($export_mode) {
|
||||
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 $error_url the url to go back in case of error
|
||||
* @param string $sql_query SQL query for obtaining data
|
||||
* @param array $aliases Aliases of db/table/columns
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportData(
|
||||
$db,
|
||||
$table,
|
||||
$crlf,
|
||||
$error_url,
|
||||
$sql_query,
|
||||
array $aliases = []
|
||||
) {
|
||||
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 !== null) {
|
||||
// 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(
|
||||
$sql_query,
|
||||
DatabaseInterface::CONNECT_USER,
|
||||
DatabaseInterface::QUERY_UNBUFFERED
|
||||
);
|
||||
$fields_cnt = $dbi->numFields($result);
|
||||
|
||||
while ($row = $dbi->fetchRow($result)) {
|
||||
$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 $err_url the url to go back in case of error
|
||||
* @param string $sql_query the rawquery to output
|
||||
* @param string $crlf the end of line sequence
|
||||
*
|
||||
* @return bool if succeeded
|
||||
*/
|
||||
public function exportRawQuery(string $err_url, string $sql_query, string $crlf): bool
|
||||
{
|
||||
return $this->exportData('', '', $crlf, $err_url, $sql_query);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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";
|
||||
}
|
||||
}
|
355
admin/phpMyAdmin/libraries/classes/Plugins/Export/ExportOds.php
Normal file
355
admin/phpMyAdmin/libraries/classes/Plugins/Export/ExportOds.php
Normal file
|
@ -0,0 +1,355 @@
|
|||
<?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\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 bin2hex;
|
||||
use function date;
|
||||
use function htmlspecialchars;
|
||||
use function stripos;
|
||||
use function stripslashes;
|
||||
use function strtotime;
|
||||
|
||||
/**
|
||||
* Handles the export for the ODS class
|
||||
*/
|
||||
class ExportOds extends ExportPlugin
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
$GLOBALS['ods_buffer'] = '';
|
||||
$this->setProperties();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the export ODS properties
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function setProperties()
|
||||
{
|
||||
$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);
|
||||
$this->properties = $exportPluginProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs export header
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportHeader()
|
||||
{
|
||||
$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
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportFooter()
|
||||
{
|
||||
$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 $db_alias Aliases of db
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBHeader($db, $db_alias = '')
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs database footer
|
||||
*
|
||||
* @param string $db Database name
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBFooter($db)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs CREATE DATABASE statement
|
||||
*
|
||||
* @param string $db Database name
|
||||
* @param string $export_type 'server', 'database', 'table'
|
||||
* @param string $db_alias Aliases of db
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBCreate($db, $export_type, $db_alias = '')
|
||||
{
|
||||
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 $error_url the url to go back in case of error
|
||||
* @param string $sql_query SQL query for obtaining data
|
||||
* @param array $aliases Aliases of db/table/columns
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportData(
|
||||
$db,
|
||||
$table,
|
||||
$crlf,
|
||||
$error_url,
|
||||
$sql_query,
|
||||
array $aliases = []
|
||||
) {
|
||||
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(
|
||||
$sql_query,
|
||||
DatabaseInterface::CONNECT_USER,
|
||||
DatabaseInterface::QUERY_UNBUFFERED
|
||||
);
|
||||
$fields_cnt = $dbi->numFields($result);
|
||||
$fields_meta = $dbi->getFieldsMeta($result);
|
||||
$field_flags = [];
|
||||
for ($j = 0; $j < $fields_cnt; $j++) {
|
||||
$field_flags[$j] = $dbi->fieldFlags($result, $j);
|
||||
}
|
||||
|
||||
$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>';
|
||||
for ($i = 0; $i < $fields_cnt; $i++) {
|
||||
$col_as = $dbi->fieldName($result, $i);
|
||||
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 = $dbi->fetchRow($result)) {
|
||||
$GLOBALS['ods_buffer'] .= '<table:table-row>';
|
||||
for ($j = 0; $j < $fields_cnt; $j++) {
|
||||
if ($fields_meta[$j]->type === 'geometry') {
|
||||
// export GIS types as hex
|
||||
$row[$j] = '0x' . bin2hex($row[$j]);
|
||||
}
|
||||
if (! isset($row[$j]) || $row[$j] === null) {
|
||||
$GLOBALS['ods_buffer']
|
||||
.= '<table:table-cell office:value-type="string">'
|
||||
. '<text:p>'
|
||||
. htmlspecialchars($GLOBALS[$what . '_null'])
|
||||
. '</text:p>'
|
||||
. '</table:table-cell>';
|
||||
} elseif (stripos($field_flags[$j], 'BINARY') !== false
|
||||
&& $fields_meta[$j]->blob
|
||||
) {
|
||||
// ignore BLOB
|
||||
$GLOBALS['ods_buffer']
|
||||
.= '<table:table-cell office:value-type="string">'
|
||||
. '<text:p></text:p>'
|
||||
. '</table:table-cell>';
|
||||
} elseif ($fields_meta[$j]->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 ($fields_meta[$j]->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 ($fields_meta[$j]->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 (($fields_meta[$j]->numeric
|
||||
&& $fields_meta[$j]->type !== 'timestamp'
|
||||
&& ! $fields_meta[$j]->blob)
|
||||
|| $fields_meta[$j]->type === 'real'
|
||||
) {
|
||||
$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>';
|
||||
}
|
||||
$dbi->freeResult($result);
|
||||
|
||||
$GLOBALS['ods_buffer'] .= '</table:table>';
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs result raw query in ODS format
|
||||
*
|
||||
* @param string $err_url the url to go back in case of error
|
||||
* @param string $sql_query the rawquery to output
|
||||
* @param string $crlf the end of line sequence
|
||||
*
|
||||
* @return bool if succeeded
|
||||
*/
|
||||
public function exportRawQuery(string $err_url, string $sql_query, string $crlf): bool
|
||||
{
|
||||
return $this->exportData('', '', $crlf, $err_url, $sql_query);
|
||||
}
|
||||
}
|
824
admin/phpMyAdmin/libraries/classes/Plugins/Export/ExportOdt.php
Normal file
824
admin/phpMyAdmin/libraries/classes/Plugins/Export/ExportOdt.php
Normal file
|
@ -0,0 +1,824 @@
|
|||
<?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\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 bin2hex;
|
||||
use function htmlspecialchars;
|
||||
use function str_replace;
|
||||
use function stripos;
|
||||
use function stripslashes;
|
||||
|
||||
/**
|
||||
* Handles the export for the ODT class
|
||||
*/
|
||||
class ExportOdt extends ExportPlugin
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
$GLOBALS['odt_buffer'] = '';
|
||||
$this->setProperties();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the export ODT properties
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function setProperties()
|
||||
{
|
||||
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');
|
||||
// create primary items and add them to the group
|
||||
if (! empty($GLOBALS['cfgRelation']['relation'])) {
|
||||
$leaf = new BoolPropertyItem(
|
||||
'relation',
|
||||
__('Display foreign key relationships')
|
||||
);
|
||||
$structureOptions->addProperty($leaf);
|
||||
}
|
||||
$leaf = new BoolPropertyItem(
|
||||
'comments',
|
||||
__('Display comments')
|
||||
);
|
||||
$structureOptions->addProperty($leaf);
|
||||
if (! empty($GLOBALS['cfgRelation']['mimework'])) {
|
||||
$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);
|
||||
$this->properties = $exportPluginProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs export header
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportHeader()
|
||||
{
|
||||
$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
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportFooter()
|
||||
{
|
||||
$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 $db_alias Aliases of db
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBHeader($db, $db_alias = '')
|
||||
{
|
||||
if (empty($db_alias)) {
|
||||
$db_alias = $db;
|
||||
}
|
||||
$GLOBALS['odt_buffer']
|
||||
.= '<text:h text:outline-level="1" text:style-name="Heading_1"'
|
||||
. ' text:is-list-header="true">'
|
||||
. __('Database') . ' ' . htmlspecialchars($db_alias)
|
||||
. '</text:h>';
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs database footer
|
||||
*
|
||||
* @param string $db Database name
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBFooter($db)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs CREATE DATABASE statement
|
||||
*
|
||||
* @param string $db Database name
|
||||
* @param string $export_type 'server', 'database', 'table'
|
||||
* @param string $db_alias Aliases of db
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBCreate($db, $export_type, $db_alias = '')
|
||||
{
|
||||
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 $error_url the url to go back in case of error
|
||||
* @param string $sql_query SQL query for obtaining data
|
||||
* @param array $aliases Aliases of db/table/columns
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportData(
|
||||
$db,
|
||||
$table,
|
||||
$crlf,
|
||||
$error_url,
|
||||
$sql_query,
|
||||
array $aliases = []
|
||||
) {
|
||||
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(
|
||||
$sql_query,
|
||||
DatabaseInterface::CONNECT_USER,
|
||||
DatabaseInterface::QUERY_UNBUFFERED
|
||||
);
|
||||
$fields_cnt = $dbi->numFields($result);
|
||||
$fields_meta = $dbi->getFieldsMeta($result);
|
||||
$field_flags = [];
|
||||
for ($j = 0; $j < $fields_cnt; $j++) {
|
||||
$field_flags[$j] = $dbi->fieldFlags($result, $j);
|
||||
}
|
||||
|
||||
$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>';
|
||||
for ($i = 0; $i < $fields_cnt; $i++) {
|
||||
$col_as = $dbi->fieldName($result, $i);
|
||||
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 = $dbi->fetchRow($result)) {
|
||||
$GLOBALS['odt_buffer'] .= '<table:table-row>';
|
||||
for ($j = 0; $j < $fields_cnt; $j++) {
|
||||
if ($fields_meta[$j]->type === 'geometry') {
|
||||
// export GIS types as hex
|
||||
$row[$j] = '0x' . bin2hex($row[$j]);
|
||||
}
|
||||
if (! isset($row[$j]) || $row[$j] === null) {
|
||||
$GLOBALS['odt_buffer']
|
||||
.= '<table:table-cell office:value-type="string">'
|
||||
. '<text:p>'
|
||||
. htmlspecialchars($GLOBALS[$what . '_null'])
|
||||
. '</text:p>'
|
||||
. '</table:table-cell>';
|
||||
} elseif (stripos($field_flags[$j], 'BINARY') !== false
|
||||
&& $fields_meta[$j]->blob
|
||||
) {
|
||||
// ignore BLOB
|
||||
$GLOBALS['odt_buffer']
|
||||
.= '<table:table-cell office:value-type="string">'
|
||||
. '<text:p></text:p>'
|
||||
. '</table:table-cell>';
|
||||
} elseif ($fields_meta[$j]->numeric
|
||||
&& $fields_meta[$j]->type !== 'timestamp'
|
||||
&& ! $fields_meta[$j]->blob
|
||||
) {
|
||||
$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>';
|
||||
}
|
||||
$dbi->freeResult($result);
|
||||
|
||||
$GLOBALS['odt_buffer'] .= '</table:table>';
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs result raw query in ODT format
|
||||
*
|
||||
* @param string $err_url the url to go back in case of error
|
||||
* @param string $sql_query the rawquery to output
|
||||
* @param string $crlf the end of line sequence
|
||||
*
|
||||
* @return bool if succeeded
|
||||
*/
|
||||
public function exportRawQuery(string $err_url, string $sql_query, string $crlf): bool
|
||||
{
|
||||
return $this->exportData('', '', $crlf, $err_url, $sql_query);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
*
|
||||
* @return bool true
|
||||
*/
|
||||
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 $cfgRelation, $dbi;
|
||||
|
||||
$db_alias = $db;
|
||||
$table_alias = $table;
|
||||
$this->initAlias($aliases, $db_alias, $table_alias);
|
||||
/**
|
||||
* Gets fields properties
|
||||
*/
|
||||
$dbi->selectDb($db);
|
||||
|
||||
// Check if we can use Relations
|
||||
[$res_rel, $have_rel] = $this->relation->getRelationsAndStatus(
|
||||
$do_relation && ! empty($cfgRelation['relation']),
|
||||
$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 && $cfgRelation['mimework']) {
|
||||
$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 && $cfgRelation['mimework']) {
|
||||
$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 && $cfgRelation['mimework']) {
|
||||
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 $error_url the url to go back in case of error
|
||||
* @param string $export_mode 'create_table', 'triggers', 'create_view',
|
||||
* 'stand_in'
|
||||
* @param string $export_type '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
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportStructure(
|
||||
$db,
|
||||
$table,
|
||||
$crlf,
|
||||
$error_url,
|
||||
$export_mode,
|
||||
$export_type,
|
||||
$do_relation = false,
|
||||
$do_comments = false,
|
||||
$do_mime = false,
|
||||
$dates = false,
|
||||
array $aliases = []
|
||||
) {
|
||||
global $dbi;
|
||||
|
||||
$db_alias = $db;
|
||||
$table_alias = $table;
|
||||
$this->initAlias($aliases, $db_alias, $table_alias);
|
||||
switch ($export_mode) {
|
||||
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,
|
||||
$error_url,
|
||||
$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,
|
||||
$error_url,
|
||||
$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 = ' ';
|
||||
}
|
||||
|
||||
$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;
|
||||
}
|
||||
}
|
411
admin/phpMyAdmin/libraries/classes/Plugins/Export/ExportPdf.php
Normal file
411
admin/phpMyAdmin/libraries/classes/Plugins/Export/ExportPdf.php
Normal file
|
@ -0,0 +1,411 @@
|
|||
<?php
|
||||
/**
|
||||
* Produce a PDF report (export) from a query
|
||||
*/
|
||||
|
||||
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 function class_exists;
|
||||
|
||||
// phpcs:disable PSR1.Files.SideEffects
|
||||
/**
|
||||
* Skip the plugin if TCPDF is not available.
|
||||
*/
|
||||
if (! class_exists('TCPDF')) {
|
||||
$GLOBALS['skip_import'] = true;
|
||||
|
||||
return;
|
||||
}
|
||||
// phpcs:enable
|
||||
|
||||
/**
|
||||
* Handles the export for the PDF class
|
||||
*/
|
||||
class ExportPdf extends ExportPlugin
|
||||
{
|
||||
/**
|
||||
* PhpMyAdmin\Plugins\Export\Helpers\Pdf instance
|
||||
*
|
||||
* @var Pdf
|
||||
*/
|
||||
private $pdf;
|
||||
|
||||
/**
|
||||
* PDF Report Title
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private $pdfReportTitle;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
|
||||
// initialize the specific export PDF variables
|
||||
$this->initSpecificVariables();
|
||||
|
||||
$this->setProperties();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the local variables that are used for export PDF
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function initSpecificVariables()
|
||||
{
|
||||
if (! empty($_POST['pdf_report_title'])) {
|
||||
$this->setPdfReportTitle($_POST['pdf_report_title']);
|
||||
}
|
||||
$this->setPdf(new Pdf('L', 'pt', 'A3'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the export PDF properties
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function setProperties()
|
||||
{
|
||||
$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);
|
||||
$this->properties = $exportPluginProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs export header
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportHeader()
|
||||
{
|
||||
$pdf_report_title = $this->getPdfReportTitle();
|
||||
$pdf = $this->getPdf();
|
||||
$pdf->Open();
|
||||
|
||||
$attr = [
|
||||
'titleFontSize' => 18,
|
||||
'titleText' => $pdf_report_title,
|
||||
];
|
||||
$pdf->setAttributes($attr);
|
||||
$pdf->setTopMargin(30);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs export footer
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportFooter()
|
||||
{
|
||||
$pdf = $this->getPdf();
|
||||
|
||||
// instead of $pdf->Output():
|
||||
return $this->export->outputHandler($pdf->getPDFData());
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs database header
|
||||
*
|
||||
* @param string $db Database name
|
||||
* @param string $db_alias Aliases of db
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBHeader($db, $db_alias = '')
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs database footer
|
||||
*
|
||||
* @param string $db Database name
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBFooter($db)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs CREATE DATABASE statement
|
||||
*
|
||||
* @param string $db Database name
|
||||
* @param string $export_type 'server', 'database', 'table'
|
||||
* @param string $db_alias Aliases of db
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBCreate($db, $export_type, $db_alias = '')
|
||||
{
|
||||
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 $error_url the url to go back in case of error
|
||||
* @param string $sql_query SQL query for obtaining data
|
||||
* @param array $aliases Aliases of db/table/columns
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportData(
|
||||
$db,
|
||||
$table,
|
||||
$crlf,
|
||||
$error_url,
|
||||
$sql_query,
|
||||
array $aliases = []
|
||||
) {
|
||||
$db_alias = $db;
|
||||
$table_alias = $table;
|
||||
$this->initAlias($aliases, $db_alias, $table_alias);
|
||||
$pdf = $this->getPdf();
|
||||
$attr = [
|
||||
'currentDb' => $db,
|
||||
'currentTable' => $table,
|
||||
'dbAlias' => $db_alias,
|
||||
'tableAlias' => $table_alias,
|
||||
'aliases' => $aliases,
|
||||
'purpose' => __('Dumping data'),
|
||||
];
|
||||
$pdf->setAttributes($attr);
|
||||
$pdf->mysqlReport($sql_query);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs result of raw query in PDF format
|
||||
*
|
||||
* @param string $err_url the url to go back in case of error
|
||||
* @param string $sql_query the rawquery to output
|
||||
* @param string $crlf the end of line sequence
|
||||
*
|
||||
* @return bool if succeeded
|
||||
*/
|
||||
public function exportRawQuery(string $err_url, string $sql_query, string $crlf): bool
|
||||
{
|
||||
$pdf = $this->getPdf();
|
||||
$attr = [
|
||||
'dbAlias' => '----',
|
||||
'tableAlias' => '----',
|
||||
'purpose' => __('Query result data'),
|
||||
];
|
||||
$pdf->setAttributes($attr);
|
||||
$pdf->mysqlReport($sql_query);
|
||||
|
||||
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 $error_url the url to go back in case of error
|
||||
* @param string $export_mode 'create_table', 'triggers', 'create_view',
|
||||
* 'stand_in'
|
||||
* @param string $export_type '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
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportStructure(
|
||||
$db,
|
||||
$table,
|
||||
$crlf,
|
||||
$error_url,
|
||||
$export_mode,
|
||||
$export_type,
|
||||
$do_relation = false,
|
||||
$do_comments = false,
|
||||
$do_mime = false,
|
||||
$dates = false,
|
||||
array $aliases = []
|
||||
) {
|
||||
$db_alias = $db;
|
||||
$table_alias = $table;
|
||||
$purpose = null;
|
||||
$this->initAlias($aliases, $db_alias, $table_alias);
|
||||
$pdf = $this->getPdf();
|
||||
// getting purpose to show at top
|
||||
switch ($export_mode) {
|
||||
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');
|
||||
}
|
||||
|
||||
$attr = [
|
||||
'currentDb' => $db,
|
||||
'currentTable' => $table,
|
||||
'dbAlias' => $db_alias,
|
||||
'tableAlias' => $table_alias,
|
||||
'aliases' => $aliases,
|
||||
'purpose' => $purpose,
|
||||
];
|
||||
$pdf->setAttributes($attr);
|
||||
/**
|
||||
* comment display set true as presently in pdf
|
||||
* format, no option is present to take user input.
|
||||
*/
|
||||
$do_comments = true;
|
||||
switch ($export_mode) {
|
||||
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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function setPdf($pdf)
|
||||
{
|
||||
$this->pdf = $pdf;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the PDF report title
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function getPdfReportTitle()
|
||||
{
|
||||
return $this->pdfReportTitle;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the PDF report title
|
||||
*
|
||||
* @param string $pdfReportTitle PDF report title
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function setPdfReportTitle($pdfReportTitle)
|
||||
{
|
||||
$this->pdfReportTitle = $pdfReportTitle;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,278 @@
|
|||
<?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 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
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
$this->setProperties();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the export PHP Array properties
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function setProperties()
|
||||
{
|
||||
$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);
|
||||
$this->properties = $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
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportHeader()
|
||||
{
|
||||
$this->export->outputHandler(
|
||||
'<?php' . $GLOBALS['crlf']
|
||||
. '/**' . $GLOBALS['crlf']
|
||||
. ' * Export to PHP Array plugin for PHPMyAdmin' . $GLOBALS['crlf']
|
||||
. ' * @version ' . PMA_VERSION . $GLOBALS['crlf']
|
||||
. ' */' . $GLOBALS['crlf'] . $GLOBALS['crlf']
|
||||
);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs export footer
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportFooter()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs database header
|
||||
*
|
||||
* @param string $db Database name
|
||||
* @param string $db_alias Aliases of db
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBHeader($db, $db_alias = '')
|
||||
{
|
||||
if (empty($db_alias)) {
|
||||
$db_alias = $db;
|
||||
}
|
||||
$this->export->outputHandler(
|
||||
'/**' . $GLOBALS['crlf']
|
||||
. ' * Database ' . $this->commentString(Util::backquote($db_alias))
|
||||
. $GLOBALS['crlf'] . ' */' . $GLOBALS['crlf']
|
||||
);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs database footer
|
||||
*
|
||||
* @param string $db Database name
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBFooter($db)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs CREATE DATABASE statement
|
||||
*
|
||||
* @param string $db Database name
|
||||
* @param string $export_type 'server', 'database', 'table'
|
||||
* @param string $db_alias Aliases of db
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBCreate($db, $export_type, $db_alias = '')
|
||||
{
|
||||
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 $error_url the url to go back in case of error
|
||||
* @param string $sql_query SQL query for obtaining data
|
||||
* @param array $aliases Aliases of db/table/columns
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportData(
|
||||
$db,
|
||||
$table,
|
||||
$crlf,
|
||||
$error_url,
|
||||
$sql_query,
|
||||
array $aliases = []
|
||||
) {
|
||||
global $dbi;
|
||||
|
||||
$db_alias = $db;
|
||||
$table_alias = $table;
|
||||
$this->initAlias($aliases, $db_alias, $table_alias);
|
||||
|
||||
$result = $dbi->query(
|
||||
$sql_query,
|
||||
DatabaseInterface::CONNECT_USER,
|
||||
DatabaseInterface::QUERY_UNBUFFERED
|
||||
);
|
||||
|
||||
$columns_cnt = $dbi->numFields($result);
|
||||
$columns = [];
|
||||
for ($i = 0; $i < $columns_cnt; $i++) {
|
||||
$col_as = $dbi->fieldName($result, $i);
|
||||
if (! empty($aliases[$db]['tables'][$table]['columns'][$col_as])) {
|
||||
$col_as = $aliases[$db]['tables'][$table]['columns'][$col_as];
|
||||
}
|
||||
$columns[$i] = stripslashes($col_as);
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
} else {
|
||||
$tablefixed = $table;
|
||||
}
|
||||
|
||||
$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 = $dbi->fetchRow($result)) {
|
||||
$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;
|
||||
if (! $this->export->outputHandler($buffer)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$dbi->freeResult($result);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs result of raw query as PHP array
|
||||
*
|
||||
* @param string $err_url the url to go back in case of error
|
||||
* @param string $sql_query the rawquery to output
|
||||
* @param string $crlf the end of line sequence
|
||||
*
|
||||
* @return bool if succeeded
|
||||
*/
|
||||
public function exportRawQuery(string $err_url, string $sql_query, string $crlf): bool
|
||||
{
|
||||
return $this->exportData('', '', $crlf, $err_url, $sql_query);
|
||||
}
|
||||
}
|
3001
admin/phpMyAdmin/libraries/classes/Plugins/Export/ExportSql.php
Normal file
3001
admin/phpMyAdmin/libraries/classes/Plugins/Export/ExportSql.php
Normal file
File diff suppressed because it is too large
Load diff
|
@ -0,0 +1,642 @@
|
|||
<?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 htmlspecialchars;
|
||||
use function in_array;
|
||||
use function str_replace;
|
||||
use function stripslashes;
|
||||
|
||||
/**
|
||||
* Handles the export for the Texy! text class
|
||||
*/
|
||||
class ExportTexytext extends ExportPlugin
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
$this->setProperties();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the export Texy! text properties
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function setProperties()
|
||||
{
|
||||
$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);
|
||||
$this->properties = $exportPluginProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs export header
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportHeader()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs export footer
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportFooter()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs database header
|
||||
*
|
||||
* @param string $db Database name
|
||||
* @param string $db_alias Alias of db
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBHeader($db, $db_alias = '')
|
||||
{
|
||||
if (empty($db_alias)) {
|
||||
$db_alias = $db;
|
||||
}
|
||||
|
||||
return $this->export->outputHandler(
|
||||
'===' . __('Database') . ' ' . $db_alias . "\n\n"
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs database footer
|
||||
*
|
||||
* @param string $db Database name
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBFooter($db)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs CREATE DATABASE statement
|
||||
*
|
||||
* @param string $db Database name
|
||||
* @param string $export_type 'server', 'database', 'table'
|
||||
* @param string $db_alias Aliases of db
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBCreate($db, $export_type, $db_alias = '')
|
||||
{
|
||||
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 $error_url the url to go back in case of error
|
||||
* @param string $sql_query SQL query for obtaining data
|
||||
* @param array $aliases Aliases of db/table/columns
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportData(
|
||||
$db,
|
||||
$table,
|
||||
$crlf,
|
||||
$error_url,
|
||||
$sql_query,
|
||||
array $aliases = []
|
||||
) {
|
||||
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(
|
||||
$sql_query,
|
||||
DatabaseInterface::CONNECT_USER,
|
||||
DatabaseInterface::QUERY_UNBUFFERED
|
||||
);
|
||||
$fields_cnt = $dbi->numFields($result);
|
||||
|
||||
// If required, get fields name at the first line
|
||||
if (isset($GLOBALS[$what . '_columns'])) {
|
||||
$text_output = "|------\n";
|
||||
for ($i = 0; $i < $fields_cnt; $i++) {
|
||||
$col_as = $dbi->fieldName($result, $i);
|
||||
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 = $dbi->fetchRow($result)) {
|
||||
$text_output = '';
|
||||
for ($j = 0; $j < $fields_cnt; $j++) {
|
||||
if (! isset($row[$j]) || $row[$j] === null) {
|
||||
$value = $GLOBALS[$what . '_null'];
|
||||
} elseif ($row[$j] == '0' || $row[$j] != '') {
|
||||
$value = $row[$j];
|
||||
} else {
|
||||
$value = ' ';
|
||||
}
|
||||
$text_output .= '|'
|
||||
. str_replace(
|
||||
'|',
|
||||
'|',
|
||||
htmlspecialchars($value)
|
||||
);
|
||||
}
|
||||
$text_output .= "\n";
|
||||
if (! $this->export->outputHandler($text_output)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
$dbi->freeResult($result);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs result raw query in TexyText format
|
||||
*
|
||||
* @param string $err_url the url to go back in case of error
|
||||
* @param string $sql_query the rawquery to output
|
||||
* @param string $crlf the end of line sequence
|
||||
*
|
||||
* @return bool if succeeded
|
||||
*/
|
||||
public function exportRawQuery(string $err_url, string $sql_query, string $crlf): bool
|
||||
{
|
||||
return $this->exportData('', '', $crlf, $err_url, $sql_query);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 $cfgRelation, $dbi;
|
||||
|
||||
$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 && ! empty($cfgRelation['relation']),
|
||||
$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 && $cfgRelation['mimework']) {
|
||||
$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 && $cfgRelation['commwork']) {
|
||||
$text_output .= '|'
|
||||
. (isset($comments[$field_name])
|
||||
? htmlspecialchars($comments[$field_name])
|
||||
: '');
|
||||
}
|
||||
if ($do_mime && $cfgRelation['mimework']) {
|
||||
$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(
|
||||
'|',
|
||||
'|',
|
||||
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 $error_url the url to go back in case of error
|
||||
* @param string $export_mode 'create_table', 'triggers', 'create_view',
|
||||
* 'stand_in'
|
||||
* @param string $export_type '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
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportStructure(
|
||||
$db,
|
||||
$table,
|
||||
$crlf,
|
||||
$error_url,
|
||||
$export_mode,
|
||||
$export_type,
|
||||
$do_relation = false,
|
||||
$do_comments = false,
|
||||
$do_mime = false,
|
||||
$dates = false,
|
||||
array $aliases = []
|
||||
) {
|
||||
global $dbi;
|
||||
|
||||
$db_alias = $db;
|
||||
$table_alias = $table;
|
||||
$this->initAlias($aliases, $db_alias, $table_alias);
|
||||
$dump = '';
|
||||
|
||||
switch ($export_mode) {
|
||||
case 'create_table':
|
||||
$dump .= '== ' . __('Table structure for table') . ' '
|
||||
. $table_alias . "\n\n";
|
||||
$dump .= $this->getTableDef(
|
||||
$db,
|
||||
$table,
|
||||
$crlf,
|
||||
$error_url,
|
||||
$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,
|
||||
$error_url,
|
||||
$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 = ' ';
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
604
admin/phpMyAdmin/libraries/classes/Plugins/Export/ExportXml.php
Normal file
604
admin/phpMyAdmin/libraries/classes/Plugins/Export/ExportXml.php
Normal file
|
@ -0,0 +1,604 @@
|
|||
<?php
|
||||
/**
|
||||
* Set of functions used to build XML 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\Items\BoolPropertyItem;
|
||||
use PhpMyAdmin\Properties\Options\Items\HiddenPropertyItem;
|
||||
use PhpMyAdmin\Properties\Plugins\ExportPluginProperties;
|
||||
use PhpMyAdmin\Util;
|
||||
use const PHP_VERSION;
|
||||
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;
|
||||
|
||||
// phpcs:disable PSR1.Files.SideEffects
|
||||
/* Can't do server export */
|
||||
if (! isset($GLOBALS['db']) || strlen($GLOBALS['db']) === 0) {
|
||||
$GLOBALS['skip_import'] = true;
|
||||
|
||||
return;
|
||||
}
|
||||
// phpcs:enable
|
||||
|
||||
/**
|
||||
* Handles the export for the XML class
|
||||
*/
|
||||
class ExportXml extends ExportPlugin
|
||||
{
|
||||
/**
|
||||
* Table name
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private $table;
|
||||
/**
|
||||
* Table names
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private $tables;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
$this->setProperties();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the local variables that are used for export XML
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function initSpecificVariables()
|
||||
{
|
||||
global $table, $tables;
|
||||
$this->setTable($table);
|
||||
if (! is_array($tables)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->setTables($tables);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the export XML properties
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function setProperties()
|
||||
{
|
||||
// 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);
|
||||
$this->properties = $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.
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportHeader()
|
||||
{
|
||||
$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 ' . PMA_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 ($tables === null) {
|
||||
$tables = [];
|
||||
}
|
||||
|
||||
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
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportFooter()
|
||||
{
|
||||
$foot = '</pma_xml_export>';
|
||||
|
||||
return $this->export->outputHandler($foot);
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs database header
|
||||
*
|
||||
* @param string $db Database name
|
||||
* @param string $db_alias Aliases of db
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBHeader($db, $db_alias = '')
|
||||
{
|
||||
global $crlf;
|
||||
|
||||
if (empty($db_alias)) {
|
||||
$db_alias = $db;
|
||||
}
|
||||
if (isset($GLOBALS['xml_export_contents'])
|
||||
&& $GLOBALS['xml_export_contents']
|
||||
) {
|
||||
$head = ' <!--' . $crlf
|
||||
. ' - ' . __('Database:') . ' \''
|
||||
. htmlspecialchars($db_alias) . '\'' . $crlf
|
||||
. ' -->' . $crlf . ' <database name="'
|
||||
. htmlspecialchars($db_alias) . '">' . $crlf;
|
||||
|
||||
return $this->export->outputHandler($head);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs database footer
|
||||
*
|
||||
* @param string $db Database name
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBFooter($db)
|
||||
{
|
||||
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 $export_type 'server', 'database', 'table'
|
||||
* @param string $db_alias Aliases of db
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBCreate($db, $export_type, $db_alias = '')
|
||||
{
|
||||
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 $error_url the url to go back in case of error
|
||||
* @param string $sql_query SQL query for obtaining data
|
||||
* @param array $aliases Aliases of db/table/columns
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportData(
|
||||
$db,
|
||||
$table,
|
||||
$crlf,
|
||||
$error_url,
|
||||
$sql_query,
|
||||
array $aliases = []
|
||||
) {
|
||||
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(
|
||||
$sql_query,
|
||||
DatabaseInterface::CONNECT_USER,
|
||||
DatabaseInterface::QUERY_UNBUFFERED
|
||||
);
|
||||
|
||||
$columns_cnt = $dbi->numFields($result);
|
||||
$columns = [];
|
||||
for ($i = 0; $i < $columns_cnt; $i++) {
|
||||
$columns[$i] = stripslashes($dbi->fieldName($result, $i));
|
||||
}
|
||||
unset($i);
|
||||
|
||||
$buffer = ' <!-- ' . __('Table') . ' '
|
||||
. htmlspecialchars($table_alias) . ' -->' . $crlf;
|
||||
if (! $this->export->outputHandler($buffer)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
while ($record = $dbi->fetchRow($result)) {
|
||||
$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) {
|
||||
$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;
|
||||
}
|
||||
}
|
||||
$dbi->freeResult($result);
|
||||
}
|
||||
|
||||
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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function setTable($table)
|
||||
{
|
||||
$this->table = $table;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the table names
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
private function getTables()
|
||||
{
|
||||
return $this->tables;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the table names
|
||||
*
|
||||
* @param array $tables table names
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function setTables(array $tables)
|
||||
{
|
||||
$this->tables = $tables;
|
||||
}
|
||||
}
|
242
admin/phpMyAdmin/libraries/classes/Plugins/Export/ExportYaml.php
Normal file
242
admin/phpMyAdmin/libraries/classes/Plugins/Export/ExportYaml.php
Normal file
|
@ -0,0 +1,242 @@
|
|||
<?php
|
||||
/**
|
||||
* Set of functions used to build YAML 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\Items\HiddenPropertyItem;
|
||||
use PhpMyAdmin\Properties\Plugins\ExportPluginProperties;
|
||||
use function is_numeric;
|
||||
use function str_replace;
|
||||
use function stripslashes;
|
||||
use function strpos;
|
||||
|
||||
/**
|
||||
* Handles the export for the YAML format
|
||||
*/
|
||||
class ExportYaml extends ExportPlugin
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
$this->setProperties();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the export YAML properties
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function setProperties()
|
||||
{
|
||||
$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);
|
||||
$this->properties = $exportPluginProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs export header
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportHeader()
|
||||
{
|
||||
$this->export->outputHandler(
|
||||
'%YAML 1.1' . $GLOBALS['crlf'] . '---' . $GLOBALS['crlf']
|
||||
);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs export footer
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportFooter()
|
||||
{
|
||||
$this->export->outputHandler('...' . $GLOBALS['crlf']);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs database header
|
||||
*
|
||||
* @param string $db Database name
|
||||
* @param string $db_alias Aliases of db
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBHeader($db, $db_alias = '')
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs database footer
|
||||
*
|
||||
* @param string $db Database name
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBFooter($db)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs CREATE DATABASE statement
|
||||
*
|
||||
* @param string $db Database name
|
||||
* @param string $export_type 'server', 'database', 'table'
|
||||
* @param string $db_alias Aliases of db
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBCreate($db, $export_type, $db_alias = '')
|
||||
{
|
||||
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 $error_url the url to go back in case of error
|
||||
* @param string $sql_query SQL query for obtaining data
|
||||
* @param array $aliases Aliases of db/table/columns
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportData(
|
||||
$db,
|
||||
$table,
|
||||
$crlf,
|
||||
$error_url,
|
||||
$sql_query,
|
||||
array $aliases = []
|
||||
) {
|
||||
global $dbi;
|
||||
|
||||
$db_alias = $db;
|
||||
$table_alias = $table;
|
||||
$this->initAlias($aliases, $db_alias, $table_alias);
|
||||
$result = $dbi->query(
|
||||
$sql_query,
|
||||
DatabaseInterface::CONNECT_USER,
|
||||
DatabaseInterface::QUERY_UNBUFFERED
|
||||
);
|
||||
|
||||
$columns_cnt = $dbi->numFields($result);
|
||||
$fieldsMeta = $dbi->getFieldsMeta($result);
|
||||
|
||||
$columns = [];
|
||||
for ($i = 0; $i < $columns_cnt; $i++) {
|
||||
$col_as = $dbi->fieldName($result, $i);
|
||||
if (! empty($aliases[$db]['tables'][$table]['columns'][$col_as])) {
|
||||
$col_as = $aliases[$db]['tables'][$table]['columns'][$col_as];
|
||||
}
|
||||
$columns[$i] = stripslashes($col_as);
|
||||
}
|
||||
|
||||
$buffer = '';
|
||||
$record_cnt = 0;
|
||||
while ($record = $dbi->fetchRow($result)) {
|
||||
$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 (! isset($record[$i])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($record[$i] === null) {
|
||||
$buffer .= ' ' . $columns[$i] . ': null' . $crlf;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (is_numeric($record[$i]) && strpos($fieldsMeta[$i]->type, 'string') === false) {
|
||||
$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;
|
||||
}
|
||||
}
|
||||
$dbi->freeResult($result);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs result raw query in YAML format
|
||||
*
|
||||
* @param string $err_url the url to go back in case of error
|
||||
* @param string $sql_query the rawquery to output
|
||||
* @param string $crlf the end of line sequence
|
||||
*
|
||||
* @return bool if succeeded
|
||||
*/
|
||||
public function exportRawQuery(string $err_url, string $sql_query, string $crlf): bool
|
||||
{
|
||||
return $this->exportData('', '', $crlf, $err_url, $sql_query);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,909 @@
|
|||
<?php
|
||||
/**
|
||||
* PhpMyAdmin\Plugins\Export\Helpers\Pdf class
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpMyAdmin\Plugins\Export\Helpers;
|
||||
|
||||
use PhpMyAdmin\DatabaseInterface;
|
||||
use PhpMyAdmin\Pdf as PdfLib;
|
||||
use PhpMyAdmin\Relation;
|
||||
use PhpMyAdmin\Transformations;
|
||||
use PhpMyAdmin\Util;
|
||||
use TCPDF_STATIC;
|
||||
use function array_key_exists;
|
||||
use function count;
|
||||
use function ksort;
|
||||
use function stripos;
|
||||
|
||||
/**
|
||||
* 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 mixed */
|
||||
private $titleFontSize;
|
||||
|
||||
/** @var mixed */
|
||||
private $titleText;
|
||||
|
||||
/** @var mixed */
|
||||
private $dbAlias;
|
||||
|
||||
/** @var mixed */
|
||||
private $tableAlias;
|
||||
|
||||
/** @var mixed */
|
||||
private $purpose;
|
||||
|
||||
/** @var array */
|
||||
private $colTitles;
|
||||
|
||||
/** @var mixed */
|
||||
private $results;
|
||||
|
||||
/** @var array */
|
||||
private $colAlign;
|
||||
|
||||
/** @var mixed */
|
||||
private $titleWidth;
|
||||
|
||||
/** @var mixed */
|
||||
private $colFits;
|
||||
|
||||
/** @var array */
|
||||
private $displayColumn;
|
||||
|
||||
/** @var int */
|
||||
private $numFields;
|
||||
|
||||
/** @var array */
|
||||
private $fields;
|
||||
|
||||
/** @var int|float */
|
||||
private $sColWidth;
|
||||
|
||||
/** @var mixed */
|
||||
private $currentDb;
|
||||
|
||||
/** @var mixed */
|
||||
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 if true reduce the RAM memory usage by caching
|
||||
* temporary data on filesystem (slower).
|
||||
* @param bool $pdfa If TRUE set the document to PDF/A mode.
|
||||
*
|
||||
* @access public
|
||||
*/
|
||||
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
|
||||
*
|
||||
* @return bool true in case of page break, false otherwise.
|
||||
*/
|
||||
public function checkPageBreak($h = 0, $y = '', $addpage = true)
|
||||
{
|
||||
if (TCPDF_STATIC::empty_string($y)) {
|
||||
$y = $this->y;
|
||||
}
|
||||
$current_page = $this->page;
|
||||
if (($y + $h > $this->PageBreakTrigger)
|
||||
&& (! $this->InFooter)
|
||||
&& $this->AcceptPageBreak()
|
||||
) {
|
||||
if ($addpage) {
|
||||
//Automatic page break
|
||||
$x = $this->x;
|
||||
$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.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
// @codingStandardsIgnoreLine
|
||||
public function Header()
|
||||
{
|
||||
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
|
||||
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',
|
||||
1
|
||||
);
|
||||
$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;
|
||||
}
|
||||
|
||||
$this->dataY = $maxY;
|
||||
$this->SetAutoPageBreak(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate table
|
||||
*
|
||||
* @param int $lineheight Height of line
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function morepagestable($lineheight = 8)
|
||||
{
|
||||
global $dbi;
|
||||
|
||||
// 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 = $dbi->fetchRow($this->results)) {
|
||||
$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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a set of attributes.
|
||||
*
|
||||
* @param array $attr array containing the attributes
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function setAttributes(array $attr = [])
|
||||
{
|
||||
foreach ($attr as $key => $val) {
|
||||
$this->$key = $val;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Defines the top margin.
|
||||
* The method can be called before creating the first page.
|
||||
*
|
||||
* @param float $topMargin the margin
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function setTopMargin($topMargin)
|
||||
{
|
||||
$this->tMargin = $topMargin;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints triggers
|
||||
*
|
||||
* @param string $db database name
|
||||
* @param string $table table name
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function getTriggers($db, $table)
|
||||
{
|
||||
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],
|
||||
$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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function getTableDef(
|
||||
$db,
|
||||
$table,
|
||||
$do_relation,
|
||||
$do_comments,
|
||||
$do_mime,
|
||||
$view = false,
|
||||
array $aliases = []
|
||||
) {
|
||||
global $dbi;
|
||||
|
||||
// set $cfgRelation here, because there is a chance that it's modified
|
||||
// since the class initialization
|
||||
global $cfgRelation;
|
||||
|
||||
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;
|
||||
$columns_cnt++;
|
||||
}
|
||||
if ($do_comments /*&& $cfgRelation['commwork']*/) {
|
||||
$this->colTitles[$columns_cnt] = __('Comments');
|
||||
$this->displayColumn[$columns_cnt] = true;
|
||||
$this->colAlign[$columns_cnt] = 'L';
|
||||
$this->tablewidths[$columns_cnt] = 120;
|
||||
$columns_cnt++;
|
||||
}
|
||||
if ($do_mime && $cfgRelation['mimework']) {
|
||||
$this->colTitles[$columns_cnt] = __('Media type');
|
||||
$this->displayColumn[$columns_cnt] = true;
|
||||
$this->colAlign[$columns_cnt] = 'L';
|
||||
$this->tablewidths[$columns_cnt] = 120;
|
||||
$columns_cnt++;
|
||||
}
|
||||
|
||||
// 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 && $cfgRelation['mimework']) {
|
||||
$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],
|
||||
$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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function mysqlReport($query)
|
||||
{
|
||||
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 = $dbi->numFields($this->results);
|
||||
$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];
|
||||
}
|
||||
$stringWidth = $this->GetStringWidth($col_as) + 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;
|
||||
|
||||
switch ($this->fields[$i]->type) {
|
||||
case 'int':
|
||||
$this->colAlign[$i] = 'R';
|
||||
break;
|
||||
case 'blob':
|
||||
case 'tinyblob':
|
||||
case 'mediumblob':
|
||||
case 'longblob':
|
||||
/**
|
||||
* @todo do not deactivate completely the display
|
||||
* but show the field's name and [BLOB]
|
||||
*/
|
||||
if (stripos($this->fields[$i]->flags, 'BINARY') !== false) {
|
||||
$this->displayColumn[$i] = false;
|
||||
unset($this->colTitles[$i]);
|
||||
}
|
||||
$this->colAlign[$i] = 'L';
|
||||
break;
|
||||
default:
|
||||
$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 = $dbi->fetchRow($this->results)) {
|
||||
foreach ($colFits as $key => $val) {
|
||||
$stringWidth = $this->GetStringWidth($row[$key]) + 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);
|
||||
|
||||
$dbi->freeResult($this->results);
|
||||
|
||||
// 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);
|
||||
$this->morepagestable($this->FontSizePt);
|
||||
$dbi->freeResult($this->results);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,280 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpMyAdmin\Plugins\Export\Helpers;
|
||||
|
||||
use PhpMyAdmin\Plugins\Export\ExportCodegen;
|
||||
use const ENT_COMPAT;
|
||||
use function htmlspecialchars;
|
||||
use function mb_strpos;
|
||||
use function mb_substr;
|
||||
use function str_replace;
|
||||
use function strlen;
|
||||
use function trim;
|
||||
|
||||
/**
|
||||
* 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
|
||||
*
|
||||
* @return bool true if the key is primary, false otherwise
|
||||
*/
|
||||
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;
|
||||
}
|
||||
}
|
258
admin/phpMyAdmin/libraries/classes/Plugins/Export/README.md
Normal file
258
admin/phpMyAdmin/libraries/classes/Plugins/Export/README.md
Normal file
|
@ -0,0 +1,258 @@
|
|||
# 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
|
||||
*
|
||||
* @package PhpMyAdmin-Export
|
||||
* @subpackage [Name]
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Handles the export for the [Name] format
|
||||
*
|
||||
* @package PhpMyAdmin-Export
|
||||
*/
|
||||
class Export[Name] extends PhpMyAdmin\Plugins\ExportPlugin
|
||||
{
|
||||
/**
|
||||
* optional - declare variables and descriptions
|
||||
*
|
||||
* @var type
|
||||
*/
|
||||
private $myOptionalVariable;
|
||||
|
||||
/**
|
||||
* optional - declare global variables and descriptions
|
||||
*
|
||||
* @var type
|
||||
*/
|
||||
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
|
||||
*
|
||||
* @global type $global_variable_name
|
||||
* [..]
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
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(
|
||||
array(
|
||||
'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 $db_alias Aliases of db
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBHeader ($db, $db_alias = '')
|
||||
{
|
||||
// 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 $db_alias Aliases of db
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportDBCreate($db, $db_alias = '')
|
||||
{
|
||||
// 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 $error_url the url to go back in case of error
|
||||
* @param string $sql_query SQL query for obtaining data
|
||||
* @param array $aliases Aliases of db/table/columns
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportData(
|
||||
$db, $table, $crlf, $error_url, $sql_query, $aliases = array()
|
||||
) {
|
||||
// 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
|
||||
*
|
||||
* @return type
|
||||
*/
|
||||
private function _getMyOptionalVariable()
|
||||
{
|
||||
return $this->myOptionalVariable;
|
||||
}
|
||||
|
||||
/**
|
||||
* Setter description
|
||||
*
|
||||
* @param type $my_optional_variable description
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function _setMyOptionalVariable($my_optional_variable)
|
||||
{
|
||||
$this->myOptionalVariable = $my_optional_variable;
|
||||
}
|
||||
|
||||
/**
|
||||
* Getter description
|
||||
*
|
||||
* @return type
|
||||
*/
|
||||
private function _getGlobalVariableName()
|
||||
{
|
||||
return $this->globalVariableName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Setter description
|
||||
*
|
||||
* @param type $global_variable_name description
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function _setGlobalVariableName($global_variable_name)
|
||||
{
|
||||
$this->globalVariableName = $global_variable_name;
|
||||
}
|
||||
}
|
||||
```
|
401
admin/phpMyAdmin/libraries/classes/Plugins/ExportPlugin.php
Normal file
401
admin/phpMyAdmin/libraries/classes/Plugins/ExportPlugin.php
Normal file
|
@ -0,0 +1,401 @@
|
|||
<?php
|
||||
/**
|
||||
* Abstract class for the export plugins
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpMyAdmin\Plugins;
|
||||
|
||||
use PhpMyAdmin\Export;
|
||||
use PhpMyAdmin\Properties\Plugins\ExportPluginProperties;
|
||||
use PhpMyAdmin\Relation;
|
||||
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
|
||||
{
|
||||
/**
|
||||
* PhpMyAdmin\Properties\Plugins\ExportPluginProperties object containing
|
||||
* the specific export plugin type properties
|
||||
*
|
||||
* @var ExportPluginProperties
|
||||
*/
|
||||
protected $properties;
|
||||
|
||||
/** @var Relation */
|
||||
public $relation;
|
||||
|
||||
/** @var Export */
|
||||
protected $export;
|
||||
|
||||
/** @var Transformations */
|
||||
protected $transformations;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
global $dbi;
|
||||
|
||||
$this->relation = new Relation($dbi);
|
||||
$this->export = new Export($dbi);
|
||||
$this->transformations = new Transformations();
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs export header
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
abstract public function exportHeader();
|
||||
|
||||
/**
|
||||
* Outputs export footer
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
abstract public function exportFooter();
|
||||
|
||||
/**
|
||||
* Outputs database header
|
||||
*
|
||||
* @param string $db Database name
|
||||
* @param string $db_alias Aliases of db
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
abstract public function exportDBHeader($db, $db_alias = '');
|
||||
|
||||
/**
|
||||
* Outputs database footer
|
||||
*
|
||||
* @param string $db Database name
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
abstract public function exportDBFooter($db);
|
||||
|
||||
/**
|
||||
* Outputs CREATE DATABASE statement
|
||||
*
|
||||
* @param string $db Database name
|
||||
* @param string $export_type 'server', 'database', 'table'
|
||||
* @param string $db_alias Aliases of db
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
abstract public function exportDBCreate($db, $export_type, $db_alias = '');
|
||||
|
||||
/**
|
||||
* 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 $error_url the url to go back in case of error
|
||||
* @param string $sql_query SQL query for obtaining data
|
||||
* @param array $aliases Aliases of db/table/columns
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
abstract public function exportData(
|
||||
$db,
|
||||
$table,
|
||||
$crlf,
|
||||
$error_url,
|
||||
$sql_query,
|
||||
array $aliases = []
|
||||
);
|
||||
|
||||
/**
|
||||
* 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
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportRoutines($db, array $aliases = [])
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Exports events
|
||||
*
|
||||
* @param string $db Database
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportEvents($db)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs for raw query
|
||||
*
|
||||
* @param string $err_url the url to go back in case of error
|
||||
* @param string $sql_query the rawquery to output
|
||||
* @param string $crlf the seperator for a file
|
||||
*
|
||||
* @return bool if succeeded
|
||||
*/
|
||||
public function exportRawQuery(
|
||||
string $err_url,
|
||||
string $sql_query,
|
||||
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 $error_url the url to go back in case of error
|
||||
* @param string $export_mode 'create_table','triggers','create_view',
|
||||
* 'stand_in'
|
||||
* @param string $export_type '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
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportStructure(
|
||||
$db,
|
||||
$table,
|
||||
$crlf,
|
||||
$error_url,
|
||||
$export_mode,
|
||||
$export_type,
|
||||
$relation = false,
|
||||
$comments = false,
|
||||
$mime = false,
|
||||
$dates = false,
|
||||
array $aliases = []
|
||||
) {
|
||||
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
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportMetadata(
|
||||
$db,
|
||||
$tables,
|
||||
array $metadataTypes
|
||||
) {
|
||||
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 '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the specific variables for each export plugin
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function initSpecificVariables()
|
||||
{
|
||||
}
|
||||
|
||||
/* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */
|
||||
|
||||
/**
|
||||
* Gets the export specific format plugin properties
|
||||
*
|
||||
* @return ExportPluginProperties
|
||||
*/
|
||||
public function getProperties()
|
||||
{
|
||||
return $this->properties;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the export plugins properties and is implemented by each export
|
||||
* plugin
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
abstract protected function setProperties();
|
||||
|
||||
/**
|
||||
* 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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function initAlias($aliases, &$db, &$table = null)
|
||||
{
|
||||
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 $res_rel the foreigners array
|
||||
* @param string $field_name 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 $res_rel,
|
||||
$field_name,
|
||||
$db,
|
||||
array $aliases = []
|
||||
) {
|
||||
$relation = '';
|
||||
$foreigner = $this->relation->searchColumnInForeigners($res_rel, $field_name);
|
||||
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;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,101 @@
|
|||
<?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
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isSuccess()
|
||||
{
|
||||
return $this->success;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets the object properties
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function reset()
|
||||
{
|
||||
$this->success = true;
|
||||
$this->error = '';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,88 @@
|
|||
<?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\Groups\OptionsPropertyRootGroup;
|
||||
use PhpMyAdmin\Properties\Options\Items\BoolPropertyItem;
|
||||
use PhpMyAdmin\Properties\Options\Items\TextPropertyItem;
|
||||
use PhpMyAdmin\Properties\Plugins\ImportPluginProperties;
|
||||
|
||||
/**
|
||||
* Super class of the import plugins for the CSV format
|
||||
*/
|
||||
abstract class AbstractImportCsv extends ImportPlugin
|
||||
{
|
||||
/**
|
||||
* Sets the import plugin properties.
|
||||
* Called in the constructor.
|
||||
*
|
||||
* @return OptionsPropertyMainGroup|void object of the plugin
|
||||
*/
|
||||
protected function setProperties()
|
||||
{
|
||||
$importPluginProperties = new ImportPluginProperties();
|
||||
$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 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);
|
||||
|
||||
// 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;
|
||||
|
||||
return $generalOptions;
|
||||
}
|
||||
}
|
884
admin/phpMyAdmin/libraries/classes/Plugins/Import/ImportCsv.php
Normal file
884
admin/phpMyAdmin/libraries/classes/Plugins/Import/ImportCsv.php
Normal file
|
@ -0,0 +1,884 @@
|
|||
<?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\Items\BoolPropertyItem;
|
||||
use PhpMyAdmin\Properties\Options\Items\NumberPropertyItem;
|
||||
use PhpMyAdmin\Properties\Options\Items\TextPropertyItem;
|
||||
use PhpMyAdmin\Util;
|
||||
use function array_splice;
|
||||
use function basename;
|
||||
use function count;
|
||||
use function is_array;
|
||||
use function mb_strlen;
|
||||
use function mb_strpos;
|
||||
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 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;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
$this->setProperties();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the import plugin properties.
|
||||
* Called in the constructor.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function setProperties()
|
||||
{
|
||||
$this->setAnalyze(false);
|
||||
|
||||
if ($GLOBALS['plugin_param'] !== 'table') {
|
||||
$this->setAnalyze(true);
|
||||
}
|
||||
|
||||
$generalOptions = parent::setProperties();
|
||||
$this->properties->setText('CSV');
|
||||
$this->properties->setExtension('csv');
|
||||
|
||||
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)
|
||||
);
|
||||
$generalOptions->addProperty($leaf);
|
||||
}
|
||||
|
||||
$leaf = new BoolPropertyItem(
|
||||
'ignore',
|
||||
__('Do not abort on INSERT error')
|
||||
);
|
||||
$generalOptions->addProperty($leaf);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the whole import logic
|
||||
*
|
||||
* @param array $sql_data 2-element array with sql data
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function doImport(?File $importHandle = null, array &$sql_data = [])
|
||||
{
|
||||
global $error, $message, $dbi;
|
||||
global $db, $table, $csv_terminated, $csv_enclosed, $csv_escaped,
|
||||
$csv_new_line, $csv_columns, $err_url;
|
||||
// $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) $err_url
|
||||
);
|
||||
|
||||
[$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'
|
||||
&& mb_strpos($buffer, "\r") === false
|
||||
&& mb_strpos($buffer, "\n") === false)
|
||||
|| ($csv_new_line !== 'auto'
|
||||
&& mb_strpos($buffer, $csv_new_line) === false)
|
||||
) {
|
||||
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 $key => $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);
|
||||
$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');
|
||||
if (! is_array($result)) {
|
||||
$result = [];
|
||||
}
|
||||
$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) {
|
||||
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 (count($nameArray) === 0) {
|
||||
return $importFileName;
|
||||
}
|
||||
// check if {filename}_ as table exist
|
||||
$nameArray = preg_grep('/' . $importFileName . '_/isU', $result);
|
||||
|
||||
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);
|
||||
foreach ($tmp as $key => $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
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function getAnalyze()
|
||||
{
|
||||
return $this->analyze;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets to true if the table should be analyzed, false otherwise
|
||||
*
|
||||
* @param bool $analyze status
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function setAnalyze($analyze)
|
||||
{
|
||||
$this->analyze = $analyze;
|
||||
}
|
||||
}
|
184
admin/phpMyAdmin/libraries/classes/Plugins/Import/ImportLdi.php
Normal file
184
admin/phpMyAdmin/libraries/classes/Plugins/Import/ImportLdi.php
Normal file
|
@ -0,0 +1,184 @@
|
|||
<?php
|
||||
/**
|
||||
* CSV import plugin for phpMyAdmin using LOAD DATA
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpMyAdmin\Plugins\Import;
|
||||
|
||||
use PhpMyAdmin\File;
|
||||
use PhpMyAdmin\Message;
|
||||
use PhpMyAdmin\Properties\Options\Items\BoolPropertyItem;
|
||||
use PhpMyAdmin\Properties\Options\Items\TextPropertyItem;
|
||||
use PhpMyAdmin\Util;
|
||||
use const PHP_EOL;
|
||||
use function count;
|
||||
use function is_array;
|
||||
use function preg_split;
|
||||
use function strlen;
|
||||
use function trim;
|
||||
|
||||
// phpcs:disable PSR1.Files.SideEffects
|
||||
// We need relations enabled and we work only on database
|
||||
if (! isset($GLOBALS['plugin_param']) || $GLOBALS['plugin_param'] !== 'table') {
|
||||
$GLOBALS['skip_import'] = true;
|
||||
|
||||
return;
|
||||
}
|
||||
// phpcs:enable
|
||||
|
||||
/**
|
||||
* Handles the import for the CSV format using load data
|
||||
*/
|
||||
class ImportLdi extends AbstractImportCsv
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
$this->setProperties();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the import plugin properties.
|
||||
* Called in the constructor.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function setProperties()
|
||||
{
|
||||
global $dbi;
|
||||
|
||||
if ($GLOBALS['cfg']['Import']['ldi_local_option'] === 'auto') {
|
||||
$GLOBALS['cfg']['Import']['ldi_local_option'] = false;
|
||||
|
||||
$result = $dbi->tryQuery(
|
||||
'SELECT @@local_infile;'
|
||||
);
|
||||
if ($result != false && $dbi->numRows($result) > 0) {
|
||||
$tmp = $dbi->fetchRow($result);
|
||||
if ($tmp[0] === 'ON') {
|
||||
$GLOBALS['cfg']['Import']['ldi_local_option'] = true;
|
||||
}
|
||||
}
|
||||
$dbi->freeResult($result);
|
||||
unset($result);
|
||||
}
|
||||
|
||||
$generalOptions = parent::setProperties();
|
||||
$this->properties->setText('CSV using LOAD DATA');
|
||||
$this->properties->setExtension('ldi');
|
||||
|
||||
$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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the whole import logic
|
||||
*
|
||||
* @param array $sql_data 2-element array with sql data
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function doImport(?File $importHandle = null, array &$sql_data = [])
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,620 @@
|
|||
<?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 count;
|
||||
use function explode;
|
||||
use function mb_strlen;
|
||||
use function mb_strpos;
|
||||
use function mb_substr;
|
||||
use function preg_match;
|
||||
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;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
$this->setProperties();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the import plugin properties.
|
||||
* Called in the constructor.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function setProperties()
|
||||
{
|
||||
$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->setOptions([]);
|
||||
$importPluginProperties->setOptionsText(__('Options'));
|
||||
|
||||
$this->properties = $importPluginProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the whole import logic
|
||||
*
|
||||
* @param array $sql_data 2-element array with sql data
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function doImport(?File $importHandle = null, array &$sql_data = [])
|
||||
{
|
||||
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 (mb_strpos($buffer, $mediawiki_new_line) === false) {
|
||||
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
|
||||
*
|
||||
* @return void
|
||||
*
|
||||
* @global bool $analyze whether to scan for column types
|
||||
*/
|
||||
private function importDataOneTable(array $table, array &$sql_data)
|
||||
{
|
||||
$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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function setTableName(&$table_name)
|
||||
{
|
||||
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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function setTableHeaders(array &$table_headers, array $table_row)
|
||||
{
|
||||
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
|
||||
*
|
||||
* @return void
|
||||
*
|
||||
* @global string $db name of the database to import in
|
||||
*/
|
||||
private function executeImportTables(array &$tables, array &$analyses, array &$sql_data)
|
||||
{
|
||||
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
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function getAnalyze()
|
||||
{
|
||||
return $this->analyze;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets to true if the table should be analyzed, false otherwise
|
||||
*
|
||||
* @param bool $analyze status
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function setAnalyze($analyze)
|
||||
{
|
||||
$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 (mb_strpos($cell_data[0], '[[') === false) {
|
||||
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
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function mngInsideStructComm($inside_structure_comment)
|
||||
{
|
||||
// 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;
|
||||
}
|
||||
}
|
470
admin/phpMyAdmin/libraries/classes/Plugins/Import/ImportOds.php
Normal file
470
admin/phpMyAdmin/libraries/classes/Plugins/Import/ImportOds.php
Normal file
|
@ -0,0 +1,470 @@
|
|||
<?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 const LIBXML_COMPACT;
|
||||
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 PHP_VERSION_ID;
|
||||
|
||||
/**
|
||||
* Handles the import for the ODS format
|
||||
*/
|
||||
class ImportOds extends ImportPlugin
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
$this->setProperties();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the import plugin properties.
|
||||
* Called in the constructor.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function setProperties()
|
||||
{
|
||||
$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);
|
||||
$this->properties = $importPluginProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the whole import logic
|
||||
*
|
||||
* @param array $sql_data 2-element array with sql data
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function doImport(?File $importHandle = null, array &$sql_data = [])
|
||||
{
|
||||
global $db, $error, $timeout_passed, $finished;
|
||||
|
||||
$i = 0;
|
||||
$len = 0;
|
||||
$buffer = '';
|
||||
|
||||
/**
|
||||
* Read in the file via Import::getNextChunk so that
|
||||
* it can process compressed files
|
||||
*/
|
||||
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) {
|
||||
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', 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 array $cell_attrs Cell attributes
|
||||
* @param array $text Texts
|
||||
*
|
||||
* @return float|string
|
||||
*/
|
||||
protected function getValue($cell_attrs, $text)
|
||||
{
|
||||
if ($_REQUEST['ods_recognize_percentages']
|
||||
&& ! strcmp(
|
||||
'percentage',
|
||||
(string) $cell_attrs['value-type']
|
||||
)
|
||||
) {
|
||||
return (float) $cell_attrs['value'];
|
||||
}
|
||||
|
||||
if ($_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) {
|
||||
$values[] = (string) $paragraph;
|
||||
}
|
||||
|
||||
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;
|
||||
/** @var SimpleXMLElement $cell */
|
||||
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 {
|
||||
/** @var SimpleXMLElement $row */
|
||||
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', $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];
|
||||
}
|
||||
}
|
347
admin/phpMyAdmin/libraries/classes/Plugins/Import/ImportShp.php
Normal file
347
admin/phpMyAdmin/libraries/classes/Plugins/Import/ImportShp.php
Normal file
|
@ -0,0 +1,347 @@
|
|||
<?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 const LOCK_EX;
|
||||
use function count;
|
||||
use function extension_loaded;
|
||||
use function file_exists;
|
||||
use function file_put_contents;
|
||||
use function mb_strlen;
|
||||
use function mb_substr;
|
||||
use function pathinfo;
|
||||
use function strcmp;
|
||||
use function strlen;
|
||||
use function substr;
|
||||
use function trim;
|
||||
use function unlink;
|
||||
|
||||
/**
|
||||
* Handles the import for ESRI Shape files
|
||||
*/
|
||||
class ImportShp extends ImportPlugin
|
||||
{
|
||||
/** @var ZipExtension */
|
||||
private $zipExtension;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
$this->setProperties();
|
||||
if (! extension_loaded('zip')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->zipExtension = new ZipExtension(new ZipArchive());
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the import plugin properties.
|
||||
* Called in the constructor.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function setProperties()
|
||||
{
|
||||
$importPluginProperties = new ImportPluginProperties();
|
||||
$importPluginProperties->setText(__('ESRI Shape File'));
|
||||
$importPluginProperties->setExtension('shp');
|
||||
$importPluginProperties->setOptions([]);
|
||||
$importPluginProperties->setOptionsText(__('Options'));
|
||||
|
||||
$this->properties = $importPluginProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the whole import logic
|
||||
*
|
||||
* @param array $sql_data 2-element array with sql data
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function doImport(?File $importHandle = null, array &$sql_data = [])
|
||||
{
|
||||
global $db, $error, $finished, $import_file, $local_import_file, $message, $dbi;
|
||||
|
||||
$GLOBALS['finished'] = false;
|
||||
|
||||
if ($importHandle === 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['PMA_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.
|
||||
$file_name = mb_substr(
|
||||
$import_file,
|
||||
0,
|
||||
mb_strlen($import_file) - 4
|
||||
) . '.*';
|
||||
$shp->FileName = $file_name;
|
||||
}
|
||||
}
|
||||
|
||||
// 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) {
|
||||
$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';
|
||||
for ($n = 0; $n < $num_data_cols; $n++) {
|
||||
$col_names[] = $shp->getDBFHeader()[$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;
|
||||
}
|
||||
}
|
201
admin/phpMyAdmin/libraries/classes/Plugins/Import/ImportSql.php
Normal file
201
admin/phpMyAdmin/libraries/classes/Plugins/Import/ImportSql.php
Normal file
|
@ -0,0 +1,201 @@
|
|||
<?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 count;
|
||||
use function implode;
|
||||
use function mb_strlen;
|
||||
use function preg_replace;
|
||||
|
||||
/**
|
||||
* Handles the import for the SQL format
|
||||
*/
|
||||
class ImportSql extends ImportPlugin
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
$this->setProperties();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the import plugin properties.
|
||||
* Called in the constructor.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function setProperties()
|
||||
{
|
||||
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);
|
||||
}
|
||||
|
||||
$this->properties = $importPluginProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the whole import logic
|
||||
*
|
||||
* @param array $sql_data 2-element array with sql data
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function doImport(?File $importHandle = null, array &$sql_data = [])
|
||||
{
|
||||
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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function setSQLMode($dbi, array $request)
|
||||
{
|
||||
$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) . '"'
|
||||
);
|
||||
}
|
||||
}
|
375
admin/phpMyAdmin/libraries/classes/Plugins/Import/ImportXml.php
Normal file
375
admin/phpMyAdmin/libraries/classes/Plugins/Import/ImportXml.php
Normal file
|
@ -0,0 +1,375 @@
|
|||
<?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 const LIBXML_COMPACT;
|
||||
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 PHP_VERSION_ID;
|
||||
|
||||
/**
|
||||
* Handles the import for the XML format
|
||||
*/
|
||||
class ImportXml extends ImportPlugin
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
$this->setProperties();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the import plugin properties.
|
||||
* Called in the constructor.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function setProperties()
|
||||
{
|
||||
$importPluginProperties = new ImportPluginProperties();
|
||||
$importPluginProperties->setText(__('XML'));
|
||||
$importPluginProperties->setExtension('xml');
|
||||
$importPluginProperties->setMimeType('text/xml');
|
||||
$importPluginProperties->setOptions([]);
|
||||
$importPluginProperties->setOptionsText(__('Options'));
|
||||
|
||||
$this->properties = $importPluginProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the whole import logic
|
||||
*
|
||||
* @param array $sql_data 2-element array with sql data
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function doImport(?File $importHandle = null, array &$sql_data = [])
|
||||
{
|
||||
global $error, $timeout_passed, $finished, $db;
|
||||
|
||||
$i = 0;
|
||||
$len = 0;
|
||||
$buffer = '';
|
||||
|
||||
/**
|
||||
* Read in the file via Import::getNextChunk so that
|
||||
* it can process compressed files
|
||||
*/
|
||||
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) {
|
||||
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', 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 === null) {
|
||||
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 = [];
|
||||
|
||||
/** @var SimpleXMLElement $val1 */
|
||||
foreach ($struct as $val1) {
|
||||
/** @var SimpleXMLElement $val2 */
|
||||
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(
|
||||
$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) {
|
||||
$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) {
|
||||
$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 {
|
||||
if ($db_name === null) {
|
||||
$db_name = 'XML_DB';
|
||||
}
|
||||
|
||||
/* 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);
|
||||
}
|
||||
}
|
153
admin/phpMyAdmin/libraries/classes/Plugins/Import/README.md
Normal file
153
admin/phpMyAdmin/libraries/classes/Plugins/Import/README.md
Normal file
|
@ -0,0 +1,153 @@
|
|||
# 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;
|
||||
}
|
||||
}
|
||||
```
|
|
@ -0,0 +1,41 @@
|
|||
<?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($bytes)
|
||||
{
|
||||
return ImportShp::readFromBuffer($bytes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether file is at EOF
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function eofSHP()
|
||||
{
|
||||
global $eof;
|
||||
|
||||
return $eof;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,81 @@
|
|||
<?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 trim;
|
||||
|
||||
/**
|
||||
* Implementation for the APC extension
|
||||
*/
|
||||
class UploadApc implements UploadInterface
|
||||
{
|
||||
/**
|
||||
* Gets the specific upload ID Key
|
||||
*
|
||||
* @return string ID Key
|
||||
*/
|
||||
public static function getIdKey()
|
||||
{
|
||||
return 'APC_UPLOAD_PROGRESS';
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns upload status.
|
||||
*
|
||||
* This is implementation for APC extension.
|
||||
*
|
||||
* @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::apcCheck() || $ret['finished']) {
|
||||
return $ret;
|
||||
}
|
||||
$status = apc_fetch('upload_' . $id);
|
||||
|
||||
if ($status) {
|
||||
$ret['finished'] = (bool) $status['done'];
|
||||
$ret['total'] = $status['total'];
|
||||
$ret['complete'] = $status['current'];
|
||||
|
||||
if ($ret['total'] > 0) {
|
||||
$ret['percent'] = $ret['complete'] / $ret['total'] * 100;
|
||||
}
|
||||
|
||||
if ($ret['percent'] == 100) {
|
||||
$ret['finished'] = (bool) true;
|
||||
}
|
||||
|
||||
$_SESSION[$SESSION_KEY][$id] = $ret;
|
||||
}
|
||||
|
||||
return $ret;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,59 @@
|
|||
<?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];
|
||||
}
|
||||
}
|
|
@ -0,0 +1,97 @@
|
|||
<?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')) {
|
||||
$status = uploadprogress_get_info($id);
|
||||
}
|
||||
|
||||
if ($status) {
|
||||
if ($status['bytes_uploaded'] == $status['bytes_total']) {
|
||||
$ret['finished'] = true;
|
||||
} else {
|
||||
$ret['finished'] = false;
|
||||
}
|
||||
$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;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,94 @@
|
|||
<?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 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;
|
||||
}
|
||||
}
|
88
admin/phpMyAdmin/libraries/classes/Plugins/ImportPlugin.php
Normal file
88
admin/phpMyAdmin/libraries/classes/Plugins/ImportPlugin.php
Normal file
|
@ -0,0 +1,88 @@
|
|||
<?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 function strlen;
|
||||
|
||||
/**
|
||||
* Provides a common interface that will have to be implemented by all of the
|
||||
* import plugins.
|
||||
*/
|
||||
abstract class ImportPlugin
|
||||
{
|
||||
/**
|
||||
* ImportPluginProperties object containing the import plugin properties
|
||||
*
|
||||
* @var ImportPluginProperties
|
||||
*/
|
||||
protected $properties;
|
||||
|
||||
/** @var Import */
|
||||
protected $import;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->import = new Import();
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the whole import logic
|
||||
*
|
||||
* @param array $sql_data 2-element array with sql data
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
abstract public function doImport(?File $importHandle = null, array &$sql_data = []);
|
||||
|
||||
/* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */
|
||||
|
||||
/**
|
||||
* Gets the import specific format plugin properties
|
||||
*
|
||||
* @return ImportPluginProperties
|
||||
*/
|
||||
public function getProperties()
|
||||
{
|
||||
return $this->properties;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the export plugins properties and is implemented by each import
|
||||
* plugin
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
abstract protected function setProperties();
|
||||
|
||||
/**
|
||||
* 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)
|
||||
{
|
||||
if (strlen((string) $currentDb) > 0) {
|
||||
$db_name = $currentDb;
|
||||
$options = ['create_db' => false];
|
||||
} else {
|
||||
$db_name = $defaultDb;
|
||||
$options = null;
|
||||
}
|
||||
|
||||
return [
|
||||
$db_name,
|
||||
$options,
|
||||
];
|
||||
}
|
||||
}
|
198
admin/phpMyAdmin/libraries/classes/Plugins/Schema/Dia/Dia.php
Normal file
198
admin/phpMyAdmin/libraries/classes/Plugins/Schema/Dia/Dia.php
Normal file
|
@ -0,0 +1,198 @@
|
|||
<?php
|
||||
/**
|
||||
* Classes to create relation schema in Dia format.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpMyAdmin\Plugins\Schema\Dia;
|
||||
|
||||
use PhpMyAdmin\Core;
|
||||
use PhpMyAdmin\Response;
|
||||
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
|
||||
*
|
||||
* @access public
|
||||
*/
|
||||
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
|
||||
*
|
||||
* @return void
|
||||
*
|
||||
* @access public
|
||||
*/
|
||||
public function startDiaDoc(
|
||||
$paper,
|
||||
$topMargin,
|
||||
$bottomMargin,
|
||||
$leftMargin,
|
||||
$rightMargin,
|
||||
$orientation
|
||||
) {
|
||||
if ($orientation === 'P') {
|
||||
$isPortrait = 'true';
|
||||
} else {
|
||||
$isPortrait = 'false';
|
||||
}
|
||||
$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()
|
||||
*
|
||||
* @return void
|
||||
*
|
||||
* @access public
|
||||
*/
|
||||
public function endDiaDoc()
|
||||
{
|
||||
$this->endElement();
|
||||
$this->endDocument();
|
||||
}
|
||||
|
||||
/**
|
||||
* Output Dia Document for download
|
||||
*
|
||||
* @see XMLWriter::flush()
|
||||
*
|
||||
* @param string $fileName name of the dia document
|
||||
*
|
||||
* @return void
|
||||
*
|
||||
* @access public
|
||||
*/
|
||||
public function showOutput($fileName)
|
||||
{
|
||||
if (ob_get_clean()) {
|
||||
ob_end_clean();
|
||||
}
|
||||
$output = $this->flush();
|
||||
Response::getInstance()->disable();
|
||||
Core::downloadHeader(
|
||||
$fileName,
|
||||
'application/x-dia-diagram',
|
||||
strlen($output)
|
||||
);
|
||||
print $output;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,249 @@
|
|||
<?php
|
||||
/**
|
||||
* Classes to create relation schema in Dia format.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpMyAdmin\Plugins\Schema\Dia;
|
||||
|
||||
use PhpMyAdmin\Plugins\Schema\Eps\TableStatsEps;
|
||||
use PhpMyAdmin\Plugins\Schema\ExportRelationSchema;
|
||||
use PhpMyAdmin\Plugins\Schema\Pdf\TableStatsPdf;
|
||||
use PhpMyAdmin\Plugins\Schema\Svg\TableStatsSvg;
|
||||
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
|
||||
*
|
||||
* @name Dia_Relation_Schema
|
||||
*/
|
||||
class DiaRelationSchema extends ExportRelationSchema
|
||||
{
|
||||
/** @var TableStatsDia[]|TableStatsEps[]|TableStatsPdf[]|TableStatsSvg[] */
|
||||
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
|
||||
*
|
||||
* @return void
|
||||
*
|
||||
* @access public
|
||||
*/
|
||||
public function showOutput()
|
||||
{
|
||||
$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
|
||||
*
|
||||
* @return void
|
||||
*
|
||||
* @access private
|
||||
*/
|
||||
private function addRelation(
|
||||
$masterTable,
|
||||
$masterField,
|
||||
$foreignTable,
|
||||
$foreignField,
|
||||
$showKeys
|
||||
) {
|
||||
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()
|
||||
*
|
||||
* @return void
|
||||
*
|
||||
* @access private
|
||||
*/
|
||||
private function drawRelations()
|
||||
{
|
||||
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()
|
||||
*
|
||||
* @return void
|
||||
*
|
||||
* @access private
|
||||
*/
|
||||
private function drawTables()
|
||||
{
|
||||
foreach ($this->tables as $table) {
|
||||
$table->tableDraw($this->showColor);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,245 @@
|
|||
<?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.
|
||||
*
|
||||
* @see PMA_DIA
|
||||
*
|
||||
* @name Relation_Stats_Dia
|
||||
*/
|
||||
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;
|
||||
|
||||
/**
|
||||
* @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
|
||||
*
|
||||
* @access private
|
||||
*/
|
||||
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
|
||||
*
|
||||
* @access public
|
||||
*/
|
||||
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>'
|
||||
);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,234 @@
|
|||
<?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 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.
|
||||
*
|
||||
* @see PMA_DIA
|
||||
*
|
||||
* @name Table_Stats_Dia
|
||||
*/
|
||||
class TableStatsDia extends TableStats
|
||||
{
|
||||
/** @var int */
|
||||
public $tableId;
|
||||
|
||||
/** @var string */
|
||||
public $tableColor;
|
||||
|
||||
/**
|
||||
* @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.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function showMissingTableError()
|
||||
{
|
||||
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
|
||||
*
|
||||
* @return void
|
||||
*
|
||||
* @access public
|
||||
*/
|
||||
public function tableDraw($showColor)
|
||||
{
|
||||
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();
|
||||
}
|
||||
}
|
282
admin/phpMyAdmin/libraries/classes/Plugins/Schema/Eps/Eps.php
Normal file
282
admin/phpMyAdmin/libraries/classes/Plugins/Schema/Eps/Eps.php
Normal file
|
@ -0,0 +1,282 @@
|
|||
<?php
|
||||
/**
|
||||
* Classes to create relation schema in EPS format.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpMyAdmin\Plugins\Schema\Eps;
|
||||
|
||||
use PhpMyAdmin\Core;
|
||||
use PhpMyAdmin\Response;
|
||||
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
|
||||
*
|
||||
* @access public
|
||||
*/
|
||||
class Eps
|
||||
{
|
||||
/** @var string */
|
||||
public $font;
|
||||
|
||||
/** @var int */
|
||||
public $fontSize;
|
||||
|
||||
/** @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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function setTitle($value)
|
||||
{
|
||||
$this->stringCommands .= '%%Title: ' . $value . "\n";
|
||||
}
|
||||
|
||||
/**
|
||||
* Set document author
|
||||
*
|
||||
* @param string $value sets the author
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function setAuthor($value)
|
||||
{
|
||||
$this->stringCommands .= '%%Creator: ' . $value . "\n";
|
||||
}
|
||||
|
||||
/**
|
||||
* Set document creation date
|
||||
*
|
||||
* @param string $value sets the date
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function setDate($value)
|
||||
{
|
||||
$this->stringCommands .= '%%CreationDate: ' . $value . "\n";
|
||||
}
|
||||
|
||||
/**
|
||||
* Set document orientation
|
||||
*
|
||||
* @param string $orientation sets the orientation
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function setOrientation($orientation)
|
||||
{
|
||||
$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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function setFont($value, $size)
|
||||
{
|
||||
$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 string|int return the size of the font e.g 10
|
||||
*/
|
||||
public function getFontSize()
|
||||
{
|
||||
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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function line(
|
||||
$x_from = 0,
|
||||
$y_from = 0,
|
||||
$x_to = 0,
|
||||
$y_to = 0,
|
||||
$lineWidth = 0
|
||||
) {
|
||||
$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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function rect($x_from, $y_from, $x_to, $y_to, $lineWidth)
|
||||
{
|
||||
$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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function moveTo($x, $y)
|
||||
{
|
||||
$this->stringCommands .= $x . ' ' . $y . " moveto \n";
|
||||
}
|
||||
|
||||
/**
|
||||
* Output/Display the text
|
||||
*
|
||||
* @param string $text The string to be displayed
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function show($text)
|
||||
{
|
||||
$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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function showXY($text, $x, $y)
|
||||
{
|
||||
$this->moveTo($x, $y);
|
||||
$this->show($text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ends EPS Document
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function endEpsDoc()
|
||||
{
|
||||
$this->stringCommands .= "showpage \n";
|
||||
}
|
||||
|
||||
/**
|
||||
* Output EPS Document for download
|
||||
*
|
||||
* @param string $fileName name of the eps document
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function showOutput($fileName)
|
||||
{
|
||||
// if(ob_get_clean()){
|
||||
//ob_end_clean();
|
||||
//}
|
||||
$output = $this->stringCommands;
|
||||
Response::getInstance()
|
||||
->disable();
|
||||
Core::downloadHeader(
|
||||
$fileName,
|
||||
'image/x-eps',
|
||||
strlen($output)
|
||||
);
|
||||
print $output;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,252 @@
|
|||
<?php
|
||||
/**
|
||||
* Classes to create relation schema in EPS format.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpMyAdmin\Plugins\Schema\Eps;
|
||||
|
||||
use PhpMyAdmin\Plugins\Schema\Dia\TableStatsDia;
|
||||
use PhpMyAdmin\Plugins\Schema\ExportRelationSchema;
|
||||
use PhpMyAdmin\Plugins\Schema\Pdf\TableStatsPdf;
|
||||
use PhpMyAdmin\Plugins\Schema\Svg\TableStatsSvg;
|
||||
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
|
||||
*
|
||||
* @name EpsRelationSchema
|
||||
*/
|
||||
class EpsRelationSchema extends ExportRelationSchema
|
||||
{
|
||||
/** @var TableStatsDia[]|TableStatsEps[]|TableStatsPdf[]|TableStatsSvg[] */
|
||||
private $tables = [];
|
||||
|
||||
/** @var RelationStatsEps[] Relations */
|
||||
private $relations = [];
|
||||
|
||||
/** @var int */
|
||||
private $tablewidth;
|
||||
|
||||
/**
|
||||
* Upon instantiation This starts writing the EPS document
|
||||
* user will be prompted for download as .eps extension
|
||||
*
|
||||
* @see PMA_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 ' . PMA_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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function showOutput()
|
||||
{
|
||||
$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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function addRelation(
|
||||
$masterTable,
|
||||
$font,
|
||||
$fontSize,
|
||||
$masterField,
|
||||
$foreignTable,
|
||||
$foreignField,
|
||||
$tableDimension
|
||||
) {
|
||||
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()
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function drawRelations()
|
||||
{
|
||||
foreach ($this->relations as $relation) {
|
||||
$relation->relationDraw();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws tables
|
||||
*
|
||||
* @see TableStatsEps::Table_Stats_tableDraw()
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function drawTables()
|
||||
{
|
||||
foreach ($this->tables as $table) {
|
||||
$table->tableDraw($this->showColor);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,117 @@
|
|||
<?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
|
||||
*
|
||||
* @name RelationStatsEps
|
||||
*/
|
||||
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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function relationDraw()
|
||||
{
|
||||
// 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
|
||||
);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,187 @@
|
|||
<?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 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
|
||||
*
|
||||
* @name TableStatsEps
|
||||
*/
|
||||
class TableStatsEps extends TableStats
|
||||
{
|
||||
/** @var int */
|
||||
public $height;
|
||||
|
||||
/** @var int */
|
||||
public $currentCell = 0;
|
||||
|
||||
/**
|
||||
* @see Eps
|
||||
* @see TableStatsEps::setWidthTable
|
||||
* @see TableStatsEps::setHeightTable
|
||||
*
|
||||
* @param object $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.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function showMissingTableError()
|
||||
{
|
||||
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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function setWidthTable($font, $fontSize)
|
||||
{
|
||||
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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function setHeightTable($fontSize)
|
||||
{
|
||||
$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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function tableDraw($showColor)
|
||||
{
|
||||
$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
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,315 @@
|
|||
<?php
|
||||
/**
|
||||
* Contains PhpMyAdmin\Plugins\Schema\ExportRelationSchema class which is
|
||||
* inherited by all schema classes.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpMyAdmin\Plugins\Schema;
|
||||
|
||||
use PhpMyAdmin\Relation;
|
||||
use PhpMyAdmin\Url;
|
||||
use PhpMyAdmin\Util;
|
||||
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;
|
||||
|
||||
/** @var bool */
|
||||
protected $tableDimension;
|
||||
|
||||
/** @var bool */
|
||||
protected $sameWide;
|
||||
|
||||
/** @var bool */
|
||||
protected $showKeys;
|
||||
|
||||
/** @var string */
|
||||
protected $orientation;
|
||||
|
||||
/** @var string */
|
||||
protected $paper;
|
||||
|
||||
/** @var int */
|
||||
protected $pageNumber;
|
||||
|
||||
/** @var bool */
|
||||
protected $offline;
|
||||
|
||||
/** @var Relation */
|
||||
protected $relation;
|
||||
|
||||
/**
|
||||
* @param string $db database name
|
||||
* @param Pdf\Pdf|Svg\Svg|Eps\Eps|Dia\Dia|Pdf\Pdf|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
|
||||
*
|
||||
* @return bool whether to show colors
|
||||
*/
|
||||
public function isShowColor()
|
||||
{
|
||||
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
|
||||
*
|
||||
* @return bool whether to show table dimensions
|
||||
*/
|
||||
public function isTableDimension()
|
||||
{
|
||||
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
|
||||
*
|
||||
* @return bool whether to use same width for all tables or not
|
||||
*/
|
||||
public function isAllTableSameWidth()
|
||||
{
|
||||
return $this->sameWide;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set Show only keys
|
||||
*
|
||||
* @param bool $value show only keys or not
|
||||
*
|
||||
* @access public
|
||||
*/
|
||||
public function setShowKeys(bool $value): void
|
||||
{
|
||||
$this->showKeys = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether to show keys
|
||||
*
|
||||
* @return bool whether to show keys
|
||||
*/
|
||||
public function isShowKeys()
|
||||
{
|
||||
return $this->showKeys;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set Orientation
|
||||
*
|
||||
* @param string $value Orientation will be portrait or landscape
|
||||
*
|
||||
* @access public
|
||||
*/
|
||||
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
|
||||
*
|
||||
* @access public
|
||||
*/
|
||||
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
|
||||
*
|
||||
* @access public
|
||||
*/
|
||||
public function setOffline(bool $value): void
|
||||
{
|
||||
$this->offline = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the client side database is used
|
||||
*
|
||||
* @return bool
|
||||
*
|
||||
* @access public
|
||||
*/
|
||||
public function isOffline()
|
||||
{
|
||||
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;
|
||||
|
||||
$filename = $this->db . $extension;
|
||||
// Get the name of this page to use as filename
|
||||
if ($this->pageNumber != -1 && ! $this->offline) {
|
||||
$_name_sql = 'SELECT page_descr FROM '
|
||||
. Util::backquote($GLOBALS['cfgRelation']['db']) . '.'
|
||||
. Util::backquote($GLOBALS['cfgRelation']['pdf_pages'])
|
||||
. ' WHERE page_nr = ' . $this->pageNumber;
|
||||
$_name_rs = $this->relation->queryAsControlUser($_name_sql);
|
||||
$_name_row = $dbi->fetchRow($_name_rs);
|
||||
$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
|
||||
*
|
||||
* @return void
|
||||
*
|
||||
* @access public
|
||||
*/
|
||||
public static function dieSchema($pageNumber, $type = '', $error_message = '')
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
465
admin/phpMyAdmin/libraries/classes/Plugins/Schema/Pdf/Pdf.php
Normal file
465
admin/phpMyAdmin/libraries/classes/Plugins/Schema/Pdf/Pdf.php
Normal file
|
@ -0,0 +1,465 @@
|
|||
<?php
|
||||
/**
|
||||
* PDF schema handling
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpMyAdmin\Plugins\Schema\Pdf;
|
||||
|
||||
use PhpMyAdmin\Pdf as PdfLib;
|
||||
use PhpMyAdmin\Relation;
|
||||
use PhpMyAdmin\Util;
|
||||
use function class_exists;
|
||||
use function count;
|
||||
use function getcwd;
|
||||
use function max;
|
||||
use function mb_ord;
|
||||
use function str_replace;
|
||||
use function strlen;
|
||||
use function ucfirst;
|
||||
use function is_array;
|
||||
|
||||
// phpcs:disable PSR1.Files.SideEffects
|
||||
/**
|
||||
* Skip the plugin if TCPDF is not available.
|
||||
*/
|
||||
if (! class_exists('TCPDF')) {
|
||||
$GLOBALS['skip_import'] = true;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
*
|
||||
* @access public
|
||||
*/
|
||||
class Pdf extends PdfLib
|
||||
{
|
||||
/** @var int|float */
|
||||
public $xMin;
|
||||
|
||||
/** @var int|float */
|
||||
public $yMin;
|
||||
|
||||
/** @var int|float */
|
||||
public $leftMargin = 10;
|
||||
|
||||
/** @var int|float */
|
||||
public $topMargin = 10;
|
||||
|
||||
/** @var int|float */
|
||||
public $scale;
|
||||
|
||||
/** @var array */
|
||||
public $customLinks;
|
||||
|
||||
/** @var array */
|
||||
public $widths;
|
||||
|
||||
/** @var float */
|
||||
public $cMargin;
|
||||
|
||||
/** @var string */
|
||||
private $ff = PdfLib::PMA_PDF_FONT;
|
||||
|
||||
/** @var string */
|
||||
private $offline;
|
||||
|
||||
/** @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
|
||||
*
|
||||
* @access public
|
||||
*/
|
||||
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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function setCMargin($c_margin)
|
||||
{
|
||||
$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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function setScale(
|
||||
$scale = 1,
|
||||
$xMin = 0,
|
||||
$yMin = 0,
|
||||
$leftMargin = -1,
|
||||
$topMargin = -1
|
||||
) {
|
||||
$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 int $fill Whether to fill the cell with a color or not
|
||||
* @param string $link Link
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function cellScale(
|
||||
$w,
|
||||
$h = 0,
|
||||
$txt = '',
|
||||
$border = 0,
|
||||
$ln = 0,
|
||||
$align = '',
|
||||
$fill = 0,
|
||||
$link = ''
|
||||
) {
|
||||
$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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function lineScale($x1, $y1, $x2, $y2)
|
||||
{
|
||||
$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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function setXyScale($x, $y)
|
||||
{
|
||||
$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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function setXScale($x)
|
||||
{
|
||||
$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)
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function setFontSizeScale($size)
|
||||
{
|
||||
// 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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function setLineWidthScale($width)
|
||||
{
|
||||
$width /= $this->scale;
|
||||
$this->SetLineWidth($width);
|
||||
}
|
||||
|
||||
/**
|
||||
* This method is used to render the page header.
|
||||
*
|
||||
* @see TCPDF::Header()
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
// @codingStandardsIgnoreLine
|
||||
public function Header()
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
if ($this->offline || $this->pageNumber == -1) {
|
||||
$pg_name = __('PDF export page');
|
||||
} else {
|
||||
$test_query = 'SELECT * FROM '
|
||||
. Util::backquote($GLOBALS['cfgRelation']['db']) . '.'
|
||||
. Util::backquote($GLOBALS['cfgRelation']['pdf_pages'])
|
||||
. ' WHERE db_name = \'' . $dbi->escapeString($this->db)
|
||||
. '\' AND page_nr = \'' . $this->pageNumber . '\'';
|
||||
$test_rs = $this->relation->queryAsControlUser($test_query);
|
||||
$pageDesc = '';
|
||||
$pages = $dbi->fetchAssoc($test_rs);
|
||||
if (is_array($pages)) {
|
||||
$pageDesc = (string) $pages['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()
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
// @codingStandardsIgnoreLine
|
||||
public function Footer()
|
||||
{
|
||||
if (! $this->withDoc) {
|
||||
return;
|
||||
}
|
||||
|
||||
parent::Footer();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets widths
|
||||
*
|
||||
* @param array $w array of widths
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function setWidths(array $w)
|
||||
{
|
||||
// column widths
|
||||
$this->widths = $w;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates table row.
|
||||
*
|
||||
* @param array $data Data for table
|
||||
* @param array $links Links for table cells
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function row(array $data, array $links)
|
||||
{
|
||||
// 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]));
|
||||
}
|
||||
$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)
|
||||
{
|
||||
$cw = &$this->CurrentFont['cw'];
|
||||
if ($w == 0) {
|
||||
$w = $this->w - $this->rMargin - $this->x;
|
||||
}
|
||||
$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 string $value whether offline
|
||||
*
|
||||
* @return void
|
||||
*
|
||||
* @access private
|
||||
*/
|
||||
public function setOffline($value)
|
||||
{
|
||||
$this->offline = $value;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,822 @@
|
|||
<?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 ceil;
|
||||
use function class_exists;
|
||||
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
|
||||
/**
|
||||
* Skip the plugin if TCPDF is not available.
|
||||
*/
|
||||
if (! class_exists('TCPDF')) {
|
||||
$GLOBALS['skip_import'] = true;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
*
|
||||
* @name Pdf_Relation_Schema
|
||||
*/
|
||||
class PdfRelationSchema extends ExportRelationSchema
|
||||
{
|
||||
/** @var bool */
|
||||
private $showGrid;
|
||||
|
||||
/** @var bool */
|
||||
private $withDoc;
|
||||
|
||||
/** @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;
|
||||
|
||||
/** @var RelationStatsPdf[] */
|
||||
protected $relations = [];
|
||||
|
||||
/** @var Transformations */
|
||||
private $transformations;
|
||||
|
||||
/**
|
||||
* @see PMA_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('auto');
|
||||
$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('auto', 15);
|
||||
$this->diagram->setCMargin(1);
|
||||
$this->dataDictionaryDoc($alltables);
|
||||
$this->diagram->SetAutoPageBreak('auto');
|
||||
$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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function setShowGrid($value)
|
||||
{
|
||||
$this->showGrid = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether to show grid
|
||||
*
|
||||
* @return bool whether to show grid
|
||||
*/
|
||||
public function isShowGrid()
|
||||
{
|
||||
return $this->showGrid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set Data Dictionary
|
||||
*
|
||||
* @param bool $value show selected database data dictionary or not
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function setWithDataDictionary($value)
|
||||
{
|
||||
$this->withDoc = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return whether to show selected database data dictionary or not
|
||||
*
|
||||
* @return bool whether to show selected database data dictionary or not
|
||||
*/
|
||||
public function isWithDataDictionary()
|
||||
{
|
||||
return $this->withDoc;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the order of the table in data dictionary
|
||||
*
|
||||
* @param string $value table order
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function setTableOrder($value)
|
||||
{
|
||||
$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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function showOutput()
|
||||
{
|
||||
$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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function setMinMax($table)
|
||||
{
|
||||
$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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function addRelation(
|
||||
$masterTable,
|
||||
$masterField,
|
||||
$foreignTable,
|
||||
$foreignField
|
||||
) {
|
||||
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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function strokeGrid()
|
||||
{
|
||||
$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()
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function drawRelations()
|
||||
{
|
||||
$i = 0;
|
||||
foreach ($this->relations as $relation) {
|
||||
$relation->relationDraw($this->showColor, $i);
|
||||
$i++;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws tables
|
||||
*
|
||||
* @see TableStatsPdf::tableDraw()
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function drawTables()
|
||||
{
|
||||
foreach ($this->tables as $table) {
|
||||
$table->tableDraw(null, $this->withDoc, $this->showColor);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates data dictionary pages.
|
||||
*
|
||||
* @param array $alltables Tables to document.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function dataDictionaryDoc(array $alltables)
|
||||
{
|
||||
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',
|
||||
0,
|
||||
$this->diagram->customLinks['doc'][$table]['-']
|
||||
);
|
||||
$this->diagram->SetX(10);
|
||||
$this->diagram->Cell(
|
||||
0,
|
||||
6,
|
||||
$i . ' ' . $table,
|
||||
0,
|
||||
1,
|
||||
'L',
|
||||
0,
|
||||
$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',
|
||||
0,
|
||||
$this->diagram->customLinks['RT']['-']
|
||||
);
|
||||
$this->diagram->SetX(10);
|
||||
$this->diagram->Cell(
|
||||
0,
|
||||
6,
|
||||
$i . ' ' . __('Relational schema'),
|
||||
0,
|
||||
1,
|
||||
'L',
|
||||
0,
|
||||
$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',
|
||||
0,
|
||||
$this->diagram->customLinks['RT'][$table]['-']
|
||||
);
|
||||
$this->diagram->SetFont($this->ff, '', 8);
|
||||
$this->diagram->Ln();
|
||||
|
||||
$cfgRelation = $this->relation->getRelationsParam();
|
||||
$comments = $this->relation->getComments($this->db, $table);
|
||||
if ($cfgRelation['mimework']) {
|
||||
$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);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,160 @@
|
|||
<?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 PMA_Schema_PDF::SetDrawColor PMA_Schema_PDF::setLineWidthScale
|
||||
* Pdf::lineScale
|
||||
*
|
||||
* @name Relation_Stats_Pdf
|
||||
*/
|
||||
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
|
||||
*
|
||||
* @return void
|
||||
*
|
||||
* @access public
|
||||
*/
|
||||
public function relationDraw($showColor, $i)
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,235 @@
|
|||
<?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 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 PMA_Schema_PDF
|
||||
*
|
||||
* @name TableStatsPdf
|
||||
*/
|
||||
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 object $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.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function showMissingTableError()
|
||||
{
|
||||
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
|
||||
*
|
||||
* @return void
|
||||
*
|
||||
* @access private
|
||||
*/
|
||||
private function setWidth($fontSize)
|
||||
{
|
||||
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
|
||||
*
|
||||
* @return void
|
||||
*
|
||||
* @access private
|
||||
*/
|
||||
private function setHeight()
|
||||
{
|
||||
$this->height = (count($this->fields) + 1) * $this->heightCell;
|
||||
}
|
||||
|
||||
/**
|
||||
* Do draw the table
|
||||
*
|
||||
* @see PMA_Schema_PDF
|
||||
*
|
||||
* @param int $fontSize The font size
|
||||
* @param bool $withDoc Whether to include links to documentation
|
||||
* @param bool|int $setColor Whether to display color
|
||||
*
|
||||
* @return void
|
||||
*
|
||||
* @access public
|
||||
*/
|
||||
public function tableDraw($fontSize, $withDoc, $setColor = 0)
|
||||
{
|
||||
$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);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,129 @@
|
|||
<?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;
|
||||
|
||||
/**
|
||||
* @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
|
||||
*
|
||||
* @access private
|
||||
*/
|
||||
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,
|
||||
];
|
||||
}
|
||||
}
|
|
@ -0,0 +1,92 @@
|
|||
<?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;
|
||||
|
||||
/**
|
||||
* Handles the schema export for the Dia format
|
||||
*/
|
||||
class SchemaDia extends SchemaPlugin
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
$this->setProperties();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the schema export Dia properties
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function setProperties()
|
||||
{
|
||||
$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);
|
||||
$this->properties = $schemaPluginProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* Exports the schema into DIA format.
|
||||
*
|
||||
* @param string $db database name
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportSchema($db)
|
||||
{
|
||||
$export = new DiaRelationSchema($db);
|
||||
$export->showOutput();
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,93 @@
|
|||
<?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;
|
||||
|
||||
/**
|
||||
* Handles the schema export for the EPS format
|
||||
*/
|
||||
class SchemaEps extends SchemaPlugin
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
$this->setProperties();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the schema export EPS properties
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function setProperties()
|
||||
{
|
||||
$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);
|
||||
$this->properties = $schemaPluginProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* Exports the schema into EPS format.
|
||||
*
|
||||
* @param string $db database name
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportSchema($db)
|
||||
{
|
||||
$export = new EpsRelationSchema($db);
|
||||
$export->showOutput();
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
125
admin/phpMyAdmin/libraries/classes/Plugins/Schema/SchemaPdf.php
Normal file
125
admin/phpMyAdmin/libraries/classes/Plugins/Schema/SchemaPdf.php
Normal file
|
@ -0,0 +1,125 @@
|
|||
<?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;
|
||||
|
||||
/**
|
||||
* Handles the schema export for the PDF format
|
||||
*/
|
||||
class SchemaPdf extends SchemaPlugin
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
$this->setProperties();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the schema export PDF properties
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function setProperties()
|
||||
{
|
||||
$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);
|
||||
$this->properties = $schemaPluginProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* Exports the schema into PDF format.
|
||||
*
|
||||
* @param string $db database name
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportSchema($db)
|
||||
{
|
||||
$export = new PdfRelationSchema($db);
|
||||
$export->showOutput();
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,80 @@
|
|||
<?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;
|
||||
|
||||
/**
|
||||
* Handles the schema export for the SVG format
|
||||
*/
|
||||
class SchemaSvg extends SchemaPlugin
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
$this->setProperties();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the schema export SVG properties
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function setProperties()
|
||||
{
|
||||
$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);
|
||||
$this->properties = $schemaPluginProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* Exports the schema into SVG format.
|
||||
*
|
||||
* @param string $db database name
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
public function exportSchema($db)
|
||||
{
|
||||
$export = new SvgRelationSchema($db);
|
||||
$export->showOutput();
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,139 @@
|
|||
<?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 PMA_SVG::printElementLine
|
||||
*
|
||||
* @name Relation_Stats_Svg
|
||||
*/
|
||||
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
|
||||
*
|
||||
* @return void
|
||||
*
|
||||
* @access public
|
||||
*/
|
||||
public function relationDraw($showColor)
|
||||
{
|
||||
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;'
|
||||
);
|
||||
}
|
||||
}
|
298
admin/phpMyAdmin/libraries/classes/Plugins/Schema/Svg/Svg.php
Normal file
298
admin/phpMyAdmin/libraries/classes/Plugins/Schema/Svg/Svg.php
Normal file
|
@ -0,0 +1,298 @@
|
|||
<?php
|
||||
/**
|
||||
* Classes to create relation schema in SVG format.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpMyAdmin\Plugins\Schema\Svg;
|
||||
|
||||
use PhpMyAdmin\Core;
|
||||
use PhpMyAdmin\Response;
|
||||
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
|
||||
*
|
||||
* @access public
|
||||
*/
|
||||
class Svg extends XMLWriter
|
||||
{
|
||||
/** @var string */
|
||||
public $title;
|
||||
|
||||
/** @var string */
|
||||
public $author;
|
||||
|
||||
/** @var string */
|
||||
public $font;
|
||||
|
||||
/** @var int */
|
||||
public $fontSize;
|
||||
|
||||
/**
|
||||
* 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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function setTitle($value)
|
||||
{
|
||||
$this->title = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set document author
|
||||
*
|
||||
* @param string $value sets the author
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function setAuthor($value)
|
||||
{
|
||||
$this->author = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set document font
|
||||
*
|
||||
* @param string $value sets the font e.g Arial, Sans-serif etc
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function setFont($value)
|
||||
{
|
||||
$this->font = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get document font
|
||||
*
|
||||
* @return string returns the font name
|
||||
*/
|
||||
public function getFont()
|
||||
{
|
||||
return $this->font;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set document font size
|
||||
*
|
||||
* @param int $value sets the font size in pixels
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function setFontSize($value)
|
||||
{
|
||||
$this->fontSize = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get document font size
|
||||
*
|
||||
* @return int returns the font size
|
||||
*/
|
||||
public function getFontSize()
|
||||
{
|
||||
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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function startSvgDoc($width, $height, $x = 0, $y = 0)
|
||||
{
|
||||
$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()
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function endSvgDoc()
|
||||
{
|
||||
$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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function showOutput($fileName)
|
||||
{
|
||||
//ob_get_clean();
|
||||
$output = $this->flush();
|
||||
Response::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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function printElement(
|
||||
$name,
|
||||
$x,
|
||||
$y,
|
||||
$width = '',
|
||||
$height = '',
|
||||
?string $text = '',
|
||||
$styles = ''
|
||||
) {
|
||||
$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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function printElementLine($name, $x1, $y1, $x2, $y2, $styles)
|
||||
{
|
||||
$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();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,288 @@
|
|||
<?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 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
|
||||
*
|
||||
* @name Svg_Relation_Schema
|
||||
*/
|
||||
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;
|
||||
|
||||
/**
|
||||
* 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 ' . PMA_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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function showOutput()
|
||||
{
|
||||
$this->diagram->showOutput($this->getFileName('.svg'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets X and Y minimum and maximum for a table cell
|
||||
*
|
||||
* @param TableStatsSvg $table The table
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function setMinMax($table)
|
||||
{
|
||||
$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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function addRelation(
|
||||
$masterTable,
|
||||
$font,
|
||||
$fontSize,
|
||||
$masterField,
|
||||
$foreignTable,
|
||||
$foreignField,
|
||||
$tableDimension
|
||||
) {
|
||||
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()
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function drawRelations()
|
||||
{
|
||||
foreach ($this->relations as $relation) {
|
||||
$relation->relationDraw($this->showColor);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws tables
|
||||
*
|
||||
* @see TableStatsSvg::Table_Stats_tableDraw()
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function drawTables()
|
||||
{
|
||||
foreach ($this->tables as $table) {
|
||||
$table->tableDraw($this->showColor);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,199 @@
|
|||
<?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 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 PMA_SVG
|
||||
*
|
||||
* @name TableStatsSvg
|
||||
*/
|
||||
class TableStatsSvg extends TableStats
|
||||
{
|
||||
/** @var int */
|
||||
public $height;
|
||||
|
||||
/** @var int */
|
||||
public $currentCell = 0;
|
||||
|
||||
/**
|
||||
* @see Svg
|
||||
* @see TableStatsSvg::setWidthTable
|
||||
* @see TableStatsSvg::setHeightTable
|
||||
*
|
||||
* @param object $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
|
||||
*
|
||||
* @access private
|
||||
*/
|
||||
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
|
||||
*
|
||||
* @access public
|
||||
*/
|
||||
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;'
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
243
admin/phpMyAdmin/libraries/classes/Plugins/Schema/TableStats.php
Normal file
243
admin/phpMyAdmin/libraries/classes/Plugins/Schema/TableStats.php
Normal file
|
@ -0,0 +1,243 @@
|
|||
<?php
|
||||
/**
|
||||
* Contains abstract class to hold table preferences/statistics
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpMyAdmin\Plugins\Schema;
|
||||
|
||||
use PhpMyAdmin\DatabaseInterface;
|
||||
use PhpMyAdmin\Font;
|
||||
use PhpMyAdmin\Index;
|
||||
use PhpMyAdmin\Relation;
|
||||
use PhpMyAdmin\Util;
|
||||
use function array_flip;
|
||||
use function array_keys;
|
||||
use function array_merge;
|
||||
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;
|
||||
|
||||
/** @var int|float */
|
||||
public $y;
|
||||
|
||||
/** @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|Pdf\Pdf $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.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function validateTableAndLoadFields()
|
||||
{
|
||||
global $dbi;
|
||||
|
||||
$sql = 'DESCRIBE ' . Util::backquote($this->tableName);
|
||||
$result = $dbi->tryQuery(
|
||||
$sql,
|
||||
DatabaseInterface::CONNECT_USER,
|
||||
DatabaseInterface::QUERY_STORE
|
||||
);
|
||||
if (! $result || ! $dbi->numRows($result)) {
|
||||
$this->showMissingTableError();
|
||||
}
|
||||
|
||||
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 {
|
||||
while ($row = $dbi->fetchRow($result)) {
|
||||
$this->fields[] = $row[0];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays an error when the table cannot be found.
|
||||
*
|
||||
* @return void
|
||||
*
|
||||
* @abstract
|
||||
*/
|
||||
abstract protected function showMissingTableError();
|
||||
|
||||
/**
|
||||
* Loads coordinates of a table
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function loadCoordinates()
|
||||
{
|
||||
if (! isset($_POST['t_h'])) {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ($_POST['t_h'] as $key => $value) {
|
||||
$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
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function loadDisplayField()
|
||||
{
|
||||
$this->displayfield = $this->relation->getDisplayField($this->db, $this->tableName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the PRIMARY key.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function loadPrimaryKey()
|
||||
{
|
||||
global $dbi;
|
||||
|
||||
$result = $dbi->query(
|
||||
'SHOW INDEX FROM ' . Util::backquote($this->tableName) . ';',
|
||||
DatabaseInterface::CONNECT_USER,
|
||||
DatabaseInterface::QUERY_STORE
|
||||
);
|
||||
if ($dbi->numRows($result) <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
while ($row = $dbi->fetchAssoc($result)) {
|
||||
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;
|
||||
}
|
||||
}
|
86
admin/phpMyAdmin/libraries/classes/Plugins/SchemaPlugin.php
Normal file
86
admin/phpMyAdmin/libraries/classes/Plugins/SchemaPlugin.php
Normal file
|
@ -0,0 +1,86 @@
|
|||
<?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\SchemaPluginProperties;
|
||||
|
||||
/**
|
||||
* 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
|
||||
{
|
||||
/**
|
||||
* PhpMyAdmin\Properties\Plugins\SchemaPluginProperties object containing
|
||||
* the specific schema export plugin type properties
|
||||
*
|
||||
* @var SchemaPluginProperties
|
||||
*/
|
||||
protected $properties;
|
||||
|
||||
/**
|
||||
* Gets the export specific format plugin properties
|
||||
*
|
||||
* @return SchemaPluginProperties
|
||||
*/
|
||||
public function getProperties()
|
||||
{
|
||||
return $this->properties;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the export plugins properties and is implemented by
|
||||
* each schema export plugin
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
abstract protected function setProperties();
|
||||
|
||||
/**
|
||||
* Exports the schema into the specified format.
|
||||
*
|
||||
* @param string $db database name
|
||||
*
|
||||
* @return bool Whether it succeeded
|
||||
*/
|
||||
abstract public function exportSchema($db);
|
||||
|
||||
/**
|
||||
* Adds export options common to all plugins.
|
||||
*
|
||||
* @param OptionsPropertyMainGroup $propertyGroup property group
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function addCommonOptions(OptionsPropertyMainGroup $propertyGroup)
|
||||
{
|
||||
$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;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,63 @@
|
|||
<?php
|
||||
/**
|
||||
* Abstract class for the Bool2Text transformations plugins
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpMyAdmin\Plugins\Transformations\Abs;
|
||||
|
||||
use PhpMyAdmin\Plugins\TransformationsPlugin;
|
||||
use stdClass;
|
||||
|
||||
/**
|
||||
* 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 stdClass|null $meta meta information
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function applyTransformation($buffer, array $options = [], ?stdClass $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';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,72 @@
|
|||
<?php
|
||||
/**
|
||||
* Abstract class for syntax highlighted editors using CodeMirror
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpMyAdmin\Plugins\Transformations\Abs;
|
||||
|
||||
use PhpMyAdmin\Plugins\IOTransformationsPlugin;
|
||||
use stdClass;
|
||||
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 stdClass|null $meta meta information
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function applyTransformation($buffer, array $options = [], ?stdClass $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>';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,163 @@
|
|||
<?php
|
||||
/**
|
||||
* Abstract class for the date format transformations plugins
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpMyAdmin\Plugins\Transformations\Abs;
|
||||
|
||||
use PhpMyAdmin\Plugins\TransformationsPlugin;
|
||||
use PhpMyAdmin\Sanitize;
|
||||
use PhpMyAdmin\Util;
|
||||
use stdClass;
|
||||
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 stdClass|null $meta meta information
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function applyTransformation($buffer, array $options = [], ?stdClass $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->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';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,94 @@
|
|||
<?php
|
||||
/**
|
||||
* Abstract class for the download transformations plugins
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpMyAdmin\Plugins\Transformations\Abs;
|
||||
|
||||
use PhpMyAdmin\Plugins\TransformationsPlugin;
|
||||
use PhpMyAdmin\Url;
|
||||
use stdClass;
|
||||
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 stdClass|null $meta meta information
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function applyTransformation($buffer, array $options = [], ?stdClass $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';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,177 @@
|
|||
<?php
|
||||
/**
|
||||
* Abstract class for the external transformations plugins
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpMyAdmin\Plugins\Transformations\Abs;
|
||||
|
||||
use PhpMyAdmin\Plugins\TransformationsPlugin;
|
||||
use stdClass;
|
||||
use const E_USER_DEPRECATED;
|
||||
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;
|
||||
|
||||
/**
|
||||
* 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
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function applyTransformationNoWrap(array $options = [])
|
||||
{
|
||||
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 stdClass|null $meta meta information
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function applyTransformation($buffer, array $options = [], ?stdClass $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';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,60 @@
|
|||
<?php
|
||||
/**
|
||||
* Abstract class for the formatted transformations plugins
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpMyAdmin\Plugins\Transformations\Abs;
|
||||
|
||||
use PhpMyAdmin\Plugins\TransformationsPlugin;
|
||||
use stdClass;
|
||||
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 stdClass|null $meta meta information
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function applyTransformation($buffer, array $options = [], ?stdClass $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';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,69 @@
|
|||
<?php
|
||||
/**
|
||||
* Abstract class for the hex transformations plugins
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpMyAdmin\Plugins\Transformations\Abs;
|
||||
|
||||
use PhpMyAdmin\Plugins\TransformationsPlugin;
|
||||
use stdClass;
|
||||
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 stdClass|null $meta meta information
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function applyTransformation($buffer, array $options = [], ?stdClass $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';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,64 @@
|
|||
<?php
|
||||
/**
|
||||
* Abstract class for the link transformations plugins
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpMyAdmin\Plugins\Transformations\Abs;
|
||||
|
||||
use PhpMyAdmin\Plugins\TransformationsPlugin;
|
||||
use PhpMyAdmin\Url;
|
||||
use stdClass;
|
||||
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 stdClass|null $meta meta information
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function applyTransformation($buffer, array $options = [], ?stdClass $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';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,117 @@
|
|||
<?php
|
||||
/**
|
||||
* Abstract class for the image upload input transformations plugins
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpMyAdmin\Plugins\Transformations\Abs;
|
||||
|
||||
use PhpMyAdmin\Plugins\IOTransformationsPlugin;
|
||||
use PhpMyAdmin\Url;
|
||||
use stdClass;
|
||||
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 stdClass|null $meta meta information
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function applyTransformation($buffer, array $options = [], ?stdClass $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';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,75 @@
|
|||
<?php
|
||||
/**
|
||||
* Abstract class for the inline transformations plugins
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpMyAdmin\Plugins\Transformations\Abs;
|
||||
|
||||
use PhpMyAdmin\Plugins\TransformationsPlugin;
|
||||
use PhpMyAdmin\Url;
|
||||
use stdClass;
|
||||
use function array_merge;
|
||||
use function defined;
|
||||
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 stdClass|null $meta meta information
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function applyTransformation($buffer, array $options = [], ?stdClass $meta = null)
|
||||
{
|
||||
$cfg = $GLOBALS['cfg'];
|
||||
$options = $this->getOptions($options, $cfg['DefaultTransformations']['Inline']);
|
||||
|
||||
if (defined('PMA_IS_GD2') && 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';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,58 @@
|
|||
<?php
|
||||
/**
|
||||
* Abstract class for the long to IPv4 transformations plugins
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpMyAdmin\Plugins\Transformations\Abs;
|
||||
|
||||
use PhpMyAdmin\Plugins\TransformationsPlugin;
|
||||
use PhpMyAdmin\Utils\FormatConverter;
|
||||
use stdClass;
|
||||
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 stdClass|null $meta meta information
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function applyTransformation($buffer, array $options = [], ?stdClass $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';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,63 @@
|
|||
<?php
|
||||
/**
|
||||
* Abstract class for the prepend/append transformations plugins
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpMyAdmin\Plugins\Transformations\Abs;
|
||||
|
||||
use PhpMyAdmin\Plugins\TransformationsPlugin;
|
||||
use stdClass;
|
||||
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 stdClass|null $meta meta information
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function applyTransformation($buffer, array $options = [], ?stdClass $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';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,71 @@
|
|||
<?php
|
||||
/**
|
||||
* Abstract class for the regex validation input transformations plugins
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpMyAdmin\Plugins\Transformations\Abs;
|
||||
|
||||
use PhpMyAdmin\Plugins\IOTransformationsPlugin;
|
||||
use stdClass;
|
||||
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 stdClass|null $meta meta information
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function applyTransformation($buffer, array $options = [], ?stdClass $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';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,56 @@
|
|||
<?php
|
||||
/**
|
||||
* Abstract class for the SQL transformations plugins
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpMyAdmin\Plugins\Transformations\Abs;
|
||||
|
||||
use PhpMyAdmin\Html\Generator;
|
||||
use PhpMyAdmin\Plugins\TransformationsPlugin;
|
||||
use stdClass;
|
||||
|
||||
/**
|
||||
* 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 stdClass|null $meta meta information
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function applyTransformation($buffer, array $options = [], ?stdClass $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';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,92 @@
|
|||
<?php
|
||||
/**
|
||||
* Abstract class for the substring transformations plugins
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpMyAdmin\Plugins\Transformations\Abs;
|
||||
|
||||
use PhpMyAdmin\Plugins\TransformationsPlugin;
|
||||
use stdClass;
|
||||
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 stdClass|null $meta meta information
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function applyTransformation($buffer, array $options = [], ?stdClass $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';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,98 @@
|
|||
<?php
|
||||
/**
|
||||
* Abstract class for the text file upload input transformations plugins
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpMyAdmin\Plugins\Transformations\Abs;
|
||||
|
||||
use PhpMyAdmin\Plugins\IOTransformationsPlugin;
|
||||
use stdClass;
|
||||
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 stdClass|null $meta meta information
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function applyTransformation($buffer, array $options = [], ?stdClass $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';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,75 @@
|
|||
<?php
|
||||
/**
|
||||
* Abstract class for the image link transformations plugins
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpMyAdmin\Plugins\Transformations\Abs;
|
||||
|
||||
use PhpMyAdmin\Plugins\TransformationsPlugin;
|
||||
use PhpMyAdmin\Sanitize;
|
||||
use PhpMyAdmin\Template;
|
||||
use stdClass;
|
||||
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 stdClass|null $meta meta information
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function applyTransformation($buffer, array $options = [], ?stdClass $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';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,73 @@
|
|||
<?php
|
||||
/**
|
||||
* Abstract class for the link transformations plugins
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpMyAdmin\Plugins\Transformations\Abs;
|
||||
|
||||
use PhpMyAdmin\Plugins\TransformationsPlugin;
|
||||
use PhpMyAdmin\Sanitize;
|
||||
use stdClass;
|
||||
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 stdClass|null $meta meta information
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function applyTransformation($buffer, array $options = [], ?stdClass $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';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,38 @@
|
|||
<?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
|
||||
*/
|
||||
// @codingStandardsIgnoreLine
|
||||
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';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
<?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.
|
||||
*/
|
||||
// @codingStandardsIgnoreLine
|
||||
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';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,134 @@
|
|||
<?php
|
||||
/**
|
||||
* Handles the IPv4/IPv6 to binary transformation for text plain
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpMyAdmin\Plugins\Transformations\Input;
|
||||
|
||||
use PhpMyAdmin\Plugins\IOTransformationsPlugin;
|
||||
use PhpMyAdmin\Utils\FormatConverter;
|
||||
use stdClass;
|
||||
use function htmlspecialchars;
|
||||
use function inet_ntop;
|
||||
use function pack;
|
||||
use function strlen;
|
||||
|
||||
/**
|
||||
* Handles the IPv4/IPv6 to binary transformation for text plain
|
||||
*/
|
||||
// @codingStandardsIgnoreLine
|
||||
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 stdClass|null $meta meta information
|
||||
*
|
||||
* @return string IP address
|
||||
*/
|
||||
public function applyTransformation($buffer, array $options = [], ?stdClass $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';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,128 @@
|
|||
<?php
|
||||
/**
|
||||
* Handles the IPv4/IPv6 to long transformation for text plain
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpMyAdmin\Plugins\Transformations\Input;
|
||||
|
||||
use PhpMyAdmin\Plugins\IOTransformationsPlugin;
|
||||
use PhpMyAdmin\Utils\FormatConverter;
|
||||
use stdClass;
|
||||
use function htmlspecialchars;
|
||||
|
||||
/**
|
||||
* Handles the IPv4/IPv6 to long transformation for text plain
|
||||
*/
|
||||
// @codingStandardsIgnoreLine
|
||||
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 stdClass $meta meta information
|
||||
*
|
||||
* @return string IP address
|
||||
*/
|
||||
public function applyTransformation($buffer, array $options = [], ?stdClass $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';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,79 @@
|
|||
<?php
|
||||
/**
|
||||
* JSON editing with syntax highlighted CodeMirror editor
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpMyAdmin\Plugins\Transformations\Input;
|
||||
|
||||
use PhpMyAdmin\Plugins\Transformations\Abs\CodeMirrorEditorTransformationPlugin;
|
||||
|
||||
/**
|
||||
* JSON editing with syntax highlighted CodeMirror editor
|
||||
*/
|
||||
// @codingStandardsIgnoreLine
|
||||
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';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,38 @@
|
|||
<?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
|
||||
*/
|
||||
// @codingStandardsIgnoreLine
|
||||
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';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,79 @@
|
|||
<?php
|
||||
/**
|
||||
* SQL editing with syntax highlighted CodeMirror editor
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpMyAdmin\Plugins\Transformations\Input;
|
||||
|
||||
use PhpMyAdmin\Plugins\Transformations\Abs\CodeMirrorEditorTransformationPlugin;
|
||||
|
||||
/**
|
||||
* SQL editing with syntax highlighted CodeMirror editor
|
||||
*/
|
||||
// @codingStandardsIgnoreLine
|
||||
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';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,79 @@
|
|||
<?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;
|
||||
|
||||
/**
|
||||
* XML (and HTML) editing with syntax highlighted CodeMirror editor
|
||||
*/
|
||||
// @codingStandardsIgnoreLine
|
||||
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';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
<?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
|
||||
*/
|
||||
// @codingStandardsIgnoreLine
|
||||
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';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
<?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
|
||||
*/
|
||||
// @codingStandardsIgnoreLine
|
||||
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';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
<?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
|
||||
*/
|
||||
// @codingStandardsIgnoreLine
|
||||
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';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
<?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
|
||||
*/
|
||||
// @codingStandardsIgnoreLine
|
||||
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';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
<?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
|
||||
*/
|
||||
// @codingStandardsIgnoreLine
|
||||
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';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
<?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
|
||||
*/
|
||||
// @codingStandardsIgnoreLine
|
||||
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';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,86 @@
|
|||
<?php
|
||||
/**
|
||||
* Handles the binary to IPv4/IPv6 transformation for text plain
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpMyAdmin\Plugins\Transformations\Output;
|
||||
|
||||
use PhpMyAdmin\Plugins\TransformationsPlugin;
|
||||
use PhpMyAdmin\Utils\FormatConverter;
|
||||
use stdClass;
|
||||
use function stripos;
|
||||
|
||||
/**
|
||||
* Handles the binary to IPv4/IPv6 transformation for text plain
|
||||
*/
|
||||
// @codingStandardsIgnoreLine
|
||||
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 stdClass|null $meta meta information
|
||||
*
|
||||
* @return string IP address
|
||||
*/
|
||||
public function applyTransformation($buffer, array $options = [], ?stdClass $meta = null)
|
||||
{
|
||||
$isBinary = false;
|
||||
if ($meta !== null && stripos($meta->flags, 'binary') !== false) {
|
||||
$isBinary = true;
|
||||
}
|
||||
|
||||
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';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
<?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'
|
||||
*/
|
||||
// @codingStandardsIgnoreLine
|
||||
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';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
<?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
|
||||
*/
|
||||
// @codingStandardsIgnoreLine
|
||||
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';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
<?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
|
||||
*/
|
||||
// @codingStandardsIgnoreLine
|
||||
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
Loading…
Add table
Add a link
Reference in a new issue