Update website

This commit is contained in:
Guilhem Lavaux 2025-03-24 09:27:39 +01:00
parent a0b0d3dae7
commit ae7ef6ad45
3151 changed files with 566766 additions and 48 deletions

View file

@ -0,0 +1,93 @@
# Change Log
## [5.2.0] - 2021-02-05
* Fix "Translator::selectString() must be of the type integer, boolean returned" (#37)
* Fix "TypeError: StringReader::readintarray() ($count) must be of type int, float given" failing tests on ARM (#36)
* Add support for getting and setting all translations (#30)
## [5.1.0] - 2020-11-15
* Allow PHPUnit 9 (#35)
* Fix some typos
* Sync config files
* Allow PHP 8.0
## [5.0.0] - 2020-02-28
* Drop support for PHP 5.3, PHP 5.4, PHP 5.5, PHP 5.6, PHP 7.0 and HHVM
* Enabled strict mode on PHP files
* Add support for Symfony 5 (#34)
* Add support for phpunit 8
* Rename CHANGES.md to CHANGELOG.md and follow a standard format
## [4.0] - 2018-02-12
* The library no longer changes system locales.
## [3.4] - 2017-12-15
* Added Translator::setTranslation method.
## [3.3] - 2017-06-01
* Add support for switching locales for Loader instance.
## [3.2] - 2017-05-23
* Various fixes when handling corrupted mo files.
## [3.1] - 2017-05-15
* Documentation improvements.
## [3.0] - 2017-01-23
* All classes moved to the PhpMyAdmin namespace.
## [2.2] - 2017-01-07
* Coding style cleanup.
* Avoid installing tests using composer.
## [2.1] - 2016-12-21
* Various code cleanups.
* Added support for PHP 5.3.
## [2.0] - 2016-10-13
* Consistently use camelCase in API.
* No more relies on using eval().
* Depends on symfony/expression-language for calculations.
## [1.2] - 2016-09-22
* Stricter validation of plural expression.
## [1.1] - 2016-08-29
* Improved handling of corrupted mo files.
* Minor performance improvements.
* Stricter validation of plural expression.
## [1.0] - 2016-04-27
* Documentation improvements.
* Testsuite improvements.
## [0.4] - 2016-03-02
* Fixed test failures with hhvm due to broken putenv.
## [0.3] - 2016-03-01
* Added Loader::detectlocale method.
## [0.2] - 2016-02-24
* Marked PHP 5.4 and 5.5 as supported.
## [0.1] - 2016-02-23
* Initial release.

View file

@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc., <http://fsf.org/>
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{description}
Copyright (C) {year} {fullname}
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
{signature of Ty Coon}, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

View file

@ -0,0 +1,164 @@
# motranslator
Translation API for PHP using Gettext MO files.
![Test-suite](https://github.com/phpmyadmin/motranslator/workflows/Run%20tests/badge.svg?branch=master)
[![codecov.io](https://codecov.io/github/phpmyadmin/motranslator/coverage.svg?branch=master)](https://codecov.io/github/phpmyadmin/motranslator?branch=master)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/phpmyadmin/motranslator/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/phpmyadmin/motranslator/?branch=master)
[![Packagist](https://img.shields.io/packagist/dt/phpmyadmin/motranslator.svg)](https://packagist.org/packages/phpmyadmin/motranslator)
## Features
* All strings are stored in memory for fast lookup
* Fast loading of MO files
* Low level API for reading MO files
* Emulation of Gettext API
* No use of `eval()` for plural equation
## Limitations
* Not suitable for huge MO files which you don't want to store in memory
* Input and output encoding has to match (preferably UTF-8)
## Installation
Please use [Composer][1] to install:
```sh
composer require phpmyadmin/motranslator
```
## Documentation
The API documentation is available at <https://develdocs.phpmyadmin.net/motranslator/>.
## Object API usage
```php
// Create loader object
$loader = new PhpMyAdmin\MoTranslator\Loader();
// Set locale
$loader->setlocale('cs');
// Set default text domain
$loader->textdomain('domain');
// Set path where to look for a domain
$loader->bindtextdomain('domain', __DIR__ . '/data/locale/');
// Get translator
$translator = $loader->getTranslator();
// Now you can use Translator API (see below)
```
## Low level API usage
```php
// Directly load the mo file
// You can use null to not load a file and the use a setter to set the translations
$translator = new PhpMyAdmin\MoTranslator\Translator('./path/to/file.mo');
// Now you can use Translator API (see below)
```
## Translator API usage
```php
// Translate string
echo $translator->gettext('String');
// Translate plural string
echo $translator->ngettext('String', 'Plural string', $count);
// Translate string with context
echo $translator->pgettext('Context', 'String');
// Translate plural string with context
echo $translator->npgettext('Context', 'String', 'Plural string', $count);
// Get the translations
echo $translator->getTranslations();
// All getters and setters below are more to be used if you are using a manual loading mode
// Example: $translator = new PhpMyAdmin\MoTranslator\Translator(null);
// Set a translation
echo $translator->setTranslation('Test', 'Translation for "Test" key');
// Set translations
echo $translator->setTranslations([
'Test' => 'Translation for "Test" key',
'Test 2' => 'Translation for "Test 2" key',
]);
// Use the translation
echo $translator->gettext('Test 2'); // -> Translation for "Test 2" key
```
## Gettext compatibility usage
```php
// Load compatibility layer
PhpMyAdmin\MoTranslator\Loader::loadFunctions();
// Configure
_setlocale(LC_MESSAGES, 'cs');
_textdomain('phpmyadmin');
_bindtextdomain('phpmyadmin', __DIR__ . '/data/locale/');
_bind_textdomain_codeset('phpmyadmin', 'UTF-8');
// Use functions
echo _gettext('Type');
echo __('Type');
// It also support other Gettext functions
_dnpgettext($domain, $msgctxt, $msgid, $msgidPlural, $number);
_dngettext($domain, $msgid, $msgidPlural, $number);
_npgettext($msgctxt, $msgid, $msgidPlural, $number);
_ngettext($msgid, $msgidPlural, $number);
_dpgettext($domain, $msgctxt, $msgid);
_dgettext($domain, $msgid);
_pgettext($msgctxt, $msgid);
```
## History
This library is based on [php-gettext][2]. It adds some performance
improvements and ability to install using [Composer][1].
## Motivation
Motivation for this library includes:
* The [php-gettext][2] library is not maintained anymore
* It doesn't work with recent PHP version (phpMyAdmin has patched version)
* It relies on `eval()` function for plural equations what can have severe security implications, see CVE-2016-6175
* It's not possible to install it using [Composer][1]
* There was place for performance improvements in the library
### Why not to use native gettext in PHP?
We've tried that, but it's not a viable solution:
* You can not use locales not known to system, what is something you can not
control from web application. This gets even more tricky with minimalist
virtualisation containers.
* Changing the MO file usually leads to PHP segmentation fault. It (or rather
Gettext library) caches headers of MO file and if it's content is changed
(for example new version is uploaded to server) it tries to access new data
with old references. This is bug known for ages:
https://bugs.php.net/bug.php?id=45943
### Why use Gettext and not JSON, YAML or whatever?
We want translators to be able to use their favorite tools and we want us to be
able to use wide range of tools available with Gettext as well such as
[web based translation using Weblate][3]. Using custom format usually adds
another barrier for translators and we want to make it easy for them to
contribute.
[1]:https://getcomposer.org/
[2]:https://launchpad.net/php-gettext
[3]:https://weblate.org/

View file

@ -0,0 +1,48 @@
{
"name": "phpmyadmin/motranslator",
"description": "Translation API for PHP using Gettext MO files",
"license": "GPL-2.0-or-later",
"keywords": ["gettext", "mo", "translator", "i18n"],
"homepage": "https://github.com/phpmyadmin/motranslator",
"authors": [
{
"name": "The phpMyAdmin Team",
"email": "developers@phpmyadmin.net",
"homepage": "https://www.phpmyadmin.net/team/"
}
],
"support": {
"issues": "https://github.com/phpmyadmin/motranslator/issues",
"source": "https://github.com/phpmyadmin/motranslator"
},
"scripts": {
"phpcbf": "./vendor/bin/phpcbf",
"phpcs": "./vendor/bin/phpcs",
"phpstan": "./vendor/bin/phpstan analyse",
"phpunit": "./vendor/bin/phpunit --color=always",
"test": [
"@phpcs",
"@phpstan",
"@phpunit"
]
},
"require": {
"php": "^7.1 || ^8.0",
"symfony/expression-language": "^4.0 || ^5.0"
},
"require-dev": {
"phpunit/phpunit": "^7.4 || ^8 || ^9",
"phpmyadmin/coding-standard": "^2.1.1",
"phpstan/phpstan": "^0.12.56"
},
"autoload": {
"psr-4": {
"PhpMyAdmin\\MoTranslator\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"PhpMyAdmin\\MoTranslator\\Tests\\": "tests"
}
}
}

View file

@ -0,0 +1,290 @@
<?php
declare(strict_types=1);
/*
Copyright (c) 2005 Steven Armstrong <sa at c-area dot ch>
Copyright (c) 2009 Danilo Segan <danilo@kvota.net>
Copyright (c) 2016 Michal Čihař <michal@cihar.com>
This file is part of MoTranslator.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
namespace PhpMyAdmin\MoTranslator;
use function array_push;
use function file_exists;
use function getenv;
use function in_array;
use function preg_match;
use function sprintf;
class Loader
{
/**
* Loader instance.
*
* @static
* @var Loader
*/
private static $instance;
/**
* Default gettext domain to use.
*
* @var string
*/
private $defaultDomain = '';
/**
* Configured locale.
*
* @var string
*/
private $locale = '';
/**
* Loaded domains.
*
* @var array<string,array<string,Translator>>
*/
private $domains = [];
/**
* Bound paths for domains.
*
* @var array<string,string>
*/
private $paths = ['' => './'];
/**
* Returns the singleton Loader object.
*
* @return Loader object
*/
public static function getInstance(): Loader
{
if (empty(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Loads global localization functions.
*/
public static function loadFunctions(): void
{
require_once __DIR__ . '/functions.php';
}
/**
* Figure out all possible locale names and start with the most
* specific ones. I.e. for sr_CS.UTF-8@latin, look through all of
* sr_CS.UTF-8@latin, sr_CS@latin, sr@latin, sr_CS.UTF-8, sr_CS, sr.
*
* @param string $locale Locale code
*
* @return string[] list of locales to try for any POSIX-style locale specification
*/
public static function listLocales(string $locale): array
{
$localeNames = [];
if ($locale) {
if (preg_match(
'/^(?P<lang>[a-z]{2,3})' // language code
. '(?:_(?P<country>[A-Z]{2}))?' // country code
. '(?:\\.(?P<charset>[-A-Za-z0-9_]+))?' // charset
. '(?:@(?P<modifier>[-A-Za-z0-9_]+))?$/', // @ modifier
$locale,
$matches
)) {
$lang = $matches['lang'] ?? null;
$country = $matches['country'] ?? null;
$charset = $matches['charset'] ?? null;
$modifier = $matches['modifier'] ?? null;
if ($modifier) {
if ($country) {
if ($charset) {
array_push(
$localeNames,
sprintf('%s_%s.%s@%s', $lang, $country, $charset, $modifier)
);
}
array_push(
$localeNames,
sprintf('%s_%s@%s', $lang, $country, $modifier)
);
} elseif ($charset) {
array_push(
$localeNames,
sprintf('%s.%s@%s', $lang, $charset, $modifier)
);
}
array_push(
$localeNames,
sprintf('%s@%s', $lang, $modifier)
);
}
if ($country) {
if ($charset) {
array_push(
$localeNames,
sprintf('%s_%s.%s', $lang, $country, $charset)
);
}
array_push(
$localeNames,
sprintf('%s_%s', $lang, $country)
);
} elseif ($charset) {
array_push(
$localeNames,
sprintf('%s.%s', $lang, $charset)
);
}
array_push($localeNames, $lang);
}
// If the locale name doesn't match POSIX style, just include it as-is.
if (! in_array($locale, $localeNames)) {
array_push($localeNames, $locale);
}
}
return $localeNames;
}
/**
* Returns Translator object for domain or for default domain.
*
* @param string $domain Translation domain
*/
public function getTranslator(string $domain = ''): Translator
{
if (empty($domain)) {
$domain = $this->defaultDomain;
}
if (! isset($this->domains[$this->locale])) {
$this->domains[$this->locale] = [];
}
if (! isset($this->domains[$this->locale][$domain])) {
if (isset($this->paths[$domain])) {
$base = $this->paths[$domain];
} else {
$base = './';
}
$localeNames = $this->listLocales($this->locale);
$filename = '';
foreach ($localeNames as $locale) {
$filename = $base . '/' . $locale . '/LC_MESSAGES/' . $domain . '.mo';
if (file_exists($filename)) {
break;
}
}
// We don't care about invalid path, we will get fallback
// translator here
$this->domains[$this->locale][$domain] = new Translator($filename);
}
return $this->domains[$this->locale][$domain];
}
/**
* Sets the path for a domain.
*
* @param string $domain Domain name
* @param string $path Path where to find locales
*/
public function bindtextdomain(string $domain, string $path): void
{
$this->paths[$domain] = $path;
}
/**
* Sets the default domain.
*
* @param string $domain Domain name
*/
public function textdomain(string $domain): void
{
$this->defaultDomain = $domain;
}
/**
* Sets a requested locale.
*
* @param string $locale Locale name
*
* @return string Set or current locale
*/
public function setlocale(string $locale): string
{
if (! empty($locale)) {
$this->locale = $locale;
}
return $this->locale;
}
/**
* Detects currently configured locale.
*
* It checks:
*
* - global lang variable
* - environment for LC_ALL, LC_MESSAGES and LANG
*
* @return string with locale name
*/
public function detectlocale(): string
{
if (isset($GLOBALS['lang'])) {
return $GLOBALS['lang'];
}
$locale = getenv('LC_ALL');
if ($locale !== false) {
return $locale;
}
$locale = getenv('LC_MESSAGES');
if ($locale !== false) {
return $locale;
}
$locale = getenv('LANG');
if ($locale !== false) {
return $locale;
}
return 'en';
}
}

View file

@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
/*
Copyright (c) 2003, 2005, 2006, 2009 Danilo Segan <danilo@kvota.net>.
Copyright (c) 2016 Michal Čihař <michal@cihar.com>
This file is part of MoTranslator.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
namespace PhpMyAdmin\MoTranslator;
use Exception;
/**
* Exception thrown when file can not be read.
*/
class ReaderException extends Exception
{
}

View file

@ -0,0 +1,113 @@
<?php
declare(strict_types=1);
/*
Copyright (c) 2003, 2005, 2006, 2009 Danilo Segan <danilo@kvota.net>.
Copyright (c) 2016 Michal Čihař <michal@cihar.com>
This file is part of MoTranslator.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
namespace PhpMyAdmin\MoTranslator;
use const PHP_INT_MAX;
use function file_get_contents;
use function strlen;
use function substr;
use function unpack;
/**
* Simple wrapper around string buffer for
* random access and values parsing.
*/
class StringReader
{
/** @var string */
private $string;
/** @var int */
private $length;
/**
* @param string $filename Name of file to load
*/
public function __construct(string $filename)
{
$this->string = (string) file_get_contents($filename);
$this->length = strlen($this->string);
}
/**
* Read number of bytes from given offset.
*
* @param int $pos Offset
* @param int $bytes Number of bytes to read
*/
public function read(int $pos, int $bytes): string
{
if ($pos + $bytes > $this->length) {
throw new ReaderException('Not enough bytes!');
}
return substr($this->string, $pos, $bytes);
}
/**
* Reads a 32bit integer from the stream.
*
* @param string $unpack Unpack string
* @param int $pos Position
*
* @return int Integer from the stream
*/
public function readint(string $unpack, int $pos): int
{
$data = unpack($unpack, $this->read($pos, 4));
if ($data === false) {
return PHP_INT_MAX;
}
$result = $data[1];
/* We're reading unsigned int, but PHP will happily
* give us negative number on 32-bit platforms.
*
* See also documentation:
* https://secure.php.net/manual/en/function.unpack.php#refsect1-function.unpack-notes
*/
return $result < 0 ? PHP_INT_MAX : $result;
}
/**
* Reads an array of integers from the stream.
*
* @param string $unpack Unpack string
* @param int $pos Position
* @param int $count How many elements should be read
*
* @return int[] Array of Integers
*/
public function readintarray(string $unpack, int $pos, int $count): array
{
$data = unpack($unpack . $count, $this->read($pos, 4 * $count));
if ($data === false) {
return [];
}
return $data;
}
}

View file

@ -0,0 +1,442 @@
<?php
declare(strict_types=1);
/*
Copyright (c) 2003, 2009 Danilo Segan <danilo@kvota.net>.
Copyright (c) 2005 Nico Kaiser <nico@siriux.net>
Copyright (c) 2016 Michal Čihař <michal@cihar.com>
This file is part of MoTranslator.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
namespace PhpMyAdmin\MoTranslator;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Throwable;
use function array_key_exists;
use function chr;
use function count;
use function explode;
use function implode;
use function intval;
use function is_readable;
use function ltrim;
use function preg_replace;
use function rtrim;
use function strcmp;
use function stripos;
use function strpos;
use function strtolower;
use function substr;
use function trim;
/**
* Provides a simple gettext replacement that works independently from
* the system's gettext abilities.
* It can read MO files and use them for translating strings.
*
* It caches ll strings and translations to speed up the string lookup.
*/
class Translator
{
/**
* None error.
*/
public const ERROR_NONE = 0;
/**
* File does not exist.
*/
public const ERROR_DOES_NOT_EXIST = 1;
/**
* File has bad magic number.
*/
public const ERROR_BAD_MAGIC = 2;
/**
* Error while reading file, probably too short.
*/
public const ERROR_READING = 3;
/**
* Big endian mo file magic bytes.
*/
public const MAGIC_BE = "\x95\x04\x12\xde";
/**
* Little endian mo file magic bytes.
*/
public const MAGIC_LE = "\xde\x12\x04\x95";
/**
* Parse error code (0 if no error).
*
* @var int
*/
public $error = self::ERROR_NONE;
/**
* Cache header field for plural forms.
*
* @var string|null
*/
private $pluralEquation = null;
/** @var ExpressionLanguage|null Evaluator for plurals */
private $pluralExpression = null;
/** @var int|null number of plurals */
private $pluralCount = null;
/**
* Array with original -> translation mapping.
*
* @var array<string,string>
*/
private $cacheTranslations = [];
/**
* @param string|null $filename Name of mo file to load (null to not load a file)
*/
public function __construct(?string $filename)
{
// The user can load the translations manually
if ($filename === null) {
return;
}
$this->loadTranslationsFromFile($filename);
}
/**
* Load a Mo file translations
*
* @param string $filename Name of mo file to load
*/
private function loadTranslationsFromFile(string $filename): void
{
if (! is_readable($filename)) {
$this->error = self::ERROR_DOES_NOT_EXIST;
return;
}
$stream = new StringReader($filename);
try {
$magic = $stream->read(0, 4);
if (strcmp($magic, self::MAGIC_LE) === 0) {
$unpack = 'V';
} elseif (strcmp($magic, self::MAGIC_BE) === 0) {
$unpack = 'N';
} else {
$this->error = self::ERROR_BAD_MAGIC;
return;
}
/* Parse header */
$total = $stream->readint($unpack, 8);
$originals = $stream->readint($unpack, 12);
$translations = $stream->readint($unpack, 16);
/* get original and translations tables */
$totalTimesTwo = (int) ($total * 2);// Fix for issue #36 on ARM
$tableOriginals = $stream->readintarray($unpack, $originals, $totalTimesTwo);
$tableTranslations = $stream->readintarray($unpack, $translations, $totalTimesTwo);
/* read all strings to the cache */
for ($i = 0; $i < $total; ++$i) {
$iTimesTwo = $i * 2;
$iPlusOne = $iTimesTwo + 1;
$iPlusTwo = $iTimesTwo + 2;
$original = $stream->read($tableOriginals[$iPlusTwo], $tableOriginals[$iPlusOne]);
$translation = $stream->read($tableTranslations[$iPlusTwo], $tableTranslations[$iPlusOne]);
$this->cacheTranslations[$original] = $translation;
}
} catch (ReaderException $e) {
$this->error = self::ERROR_READING;
return;
}
}
/**
* Translates a string.
*
* @param string $msgid String to be translated
*
* @return string translated string (or original, if not found)
*/
public function gettext(string $msgid): string
{
if (array_key_exists($msgid, $this->cacheTranslations)) {
return $this->cacheTranslations[$msgid];
}
return $msgid;
}
/**
* Check if a string is translated.
*
* @param string $msgid String to be checked
*/
public function exists(string $msgid): bool
{
return array_key_exists($msgid, $this->cacheTranslations);
}
/**
* Sanitize plural form expression for use in ExpressionLanguage.
*
* @param string $expr Expression to sanitize
*
* @return string sanitized plural form expression
*/
public static function sanitizePluralExpression(string $expr): string
{
// Parse equation
$expr = explode(';', $expr);
if (count($expr) >= 2) {
$expr = $expr[1];
} else {
$expr = $expr[0];
}
$expr = trim(strtolower($expr));
// Strip plural prefix
if (substr($expr, 0, 6) === 'plural') {
$expr = ltrim(substr($expr, 6));
}
// Strip equals
if (substr($expr, 0, 1) === '=') {
$expr = ltrim(substr($expr, 1));
}
// Cleanup from unwanted chars
$expr = preg_replace('@[^n0-9:\(\)\?=!<>/%&| ]@', '', $expr);
return (string) $expr;
}
/**
* Extracts number of plurals from plurals form expression.
*
* @param string $expr Expression to process
*
* @return int Total number of plurals
*/
public static function extractPluralCount(string $expr): int
{
$parts = explode(';', $expr, 2);
$nplurals = explode('=', trim($parts[0]), 2);
if (strtolower(rtrim($nplurals[0])) !== 'nplurals') {
return 1;
}
if (count($nplurals) === 1) {
return 1;
}
return intval($nplurals[1]);
}
/**
* Parse full PO header and extract only plural forms line.
*
* @param string $header Gettext header
*
* @return string verbatim plural form header field
*/
public static function extractPluralsForms(string $header): string
{
$headers = explode("\n", $header);
$expr = 'nplurals=2; plural=n == 1 ? 0 : 1;';
foreach ($headers as $header) {
if (stripos($header, 'Plural-Forms:') !== 0) {
continue;
}
$expr = substr($header, 13);
}
return $expr;
}
/**
* Get possible plural forms from MO header.
*
* @return string plural form header
*/
private function getPluralForms(): string
{
// lets assume message number 0 is header
// this is true, right?
// cache header field for plural forms
if ($this->pluralEquation === null) {
if (isset($this->cacheTranslations[''])) {
$header = $this->cacheTranslations[''];
} else {
$header = '';
}
$expr = $this->extractPluralsForms($header);
$this->pluralEquation = $this->sanitizePluralExpression($expr);
$this->pluralCount = $this->extractPluralCount($expr);
}
return $this->pluralEquation;
}
/**
* Detects which plural form to take.
*
* @param int $n count of objects
*
* @return int array index of the right plural form
*/
private function selectString(int $n): int
{
if ($this->pluralExpression === null) {
$this->pluralExpression = new ExpressionLanguage();
}
try {
$plural = (int) $this->pluralExpression->evaluate(
$this->getPluralForms(),
['n' => $n]
);
} catch (Throwable $e) {
$plural = 0;
}
if ($plural >= $this->pluralCount) {
$plural = $this->pluralCount - 1;
}
return $plural;
}
/**
* Plural version of gettext.
*
* @param string $msgid Single form
* @param string $msgidPlural Plural form
* @param int $number Number of objects
*
* @return string translated plural form
*/
public function ngettext(string $msgid, string $msgidPlural, int $number): string
{
// this should contains all strings separated by NULLs
$key = implode(chr(0), [$msgid, $msgidPlural]);
if (! array_key_exists($key, $this->cacheTranslations)) {
return $number !== 1 ? $msgidPlural : $msgid;
}
// find out the appropriate form
$select = $this->selectString($number);
$result = $this->cacheTranslations[$key];
$list = explode(chr(0), $result);
// @codeCoverageIgnoreStart
if ($list === false) {
// This was added in 3ff2c63bcf85f81b3a205ce7222de11b33e2bf56 for phpstan
// But according to the php manual it should never happen
return '';
}
// @codeCoverageIgnoreEnd
if (! isset($list[$select])) {
return $list[0];
}
return $list[$select];
}
/**
* Translate with context.
*
* @param string $msgctxt Context
* @param string $msgid String to be translated
*
* @return string translated plural form
*/
public function pgettext(string $msgctxt, string $msgid): string
{
$key = implode(chr(4), [$msgctxt, $msgid]);
$ret = $this->gettext($key);
if (strpos($ret, chr(4)) !== false) {
return $msgid;
}
return $ret;
}
/**
* Plural version of pgettext.
*
* @param string $msgctxt Context
* @param string $msgid Single form
* @param string $msgidPlural Plural form
* @param int $number Number of objects
*
* @return string translated plural form
*/
public function npgettext(string $msgctxt, string $msgid, string $msgidPlural, int $number): string
{
$key = implode(chr(4), [$msgctxt, $msgid]);
$ret = $this->ngettext($key, $msgidPlural, $number);
if (strpos($ret, chr(4)) !== false) {
return $msgid;
}
return $ret;
}
/**
* Set translation in place
*
* @param string $msgid String to be set
* @param string $msgstr Translation
*/
public function setTranslation(string $msgid, string $msgstr): void
{
$this->cacheTranslations[$msgid] = $msgstr;
}
/**
* Set the translations
*
* @param array<string,string> $translations The translations "key => value" array
*/
public function setTranslations(array $translations): void
{
$this->cacheTranslations = $translations;
}
/**
* Get the translations
*
* @return array<string,string> The translations "key => value" array
*/
public function getTranslations(): array
{
return $this->cacheTranslations;
}
}

View file

@ -0,0 +1,230 @@
<?php
declare(strict_types=1);
/*
Copyright (c) 2005 Steven Armstrong <sa at c-area dot ch>
Copyright (c) 2009 Danilo Segan <danilo@kvota.net>
Copyright (c) 2016 Michal Čihař <michal@cihar.com>
This file is part of MoTranslator.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
use PhpMyAdmin\MoTranslator\Loader;
/**
* Sets a requested locale.
*
* @param int $category Locale category, ignored
* @param string $locale Locale name
*
* @return string Set or current locale
*/
function _setlocale(int $category, string $locale): string
{
return Loader::getInstance()->setlocale($locale);
}
/**
* Sets the path for a domain.
*
* @param string $domain Domain name
* @param string $path Path where to find locales
*/
function _bindtextdomain(string $domain, string $path): void
{
Loader::getInstance()->bindtextdomain($domain, $path);
}
/**
* Dummy compatibility function, MoTranslator assumes
* everything is using same character set on input and
* output.
*
* Generally it is wise to output in UTF-8 and have
* mo files in UTF-8.
*
* @param string $domain Domain where to set character set
* @param string $codeset Character set to set
*/
function _bind_textdomain_codeset($domain, $codeset): void
{
}
/**
* Sets the default domain.
*
* @param string $domain Domain name
*/
function _textdomain(string $domain): void
{
Loader::getInstance()->textdomain($domain);
}
/**
* Translates a string.
*
* @param string $msgid String to be translated
*
* @return string translated string (or original, if not found)
*/
function _gettext(string $msgid): string
{
return Loader::getInstance()->getTranslator()->gettext(
$msgid
);
}
/**
* Translates a string, alias for _gettext.
*
* @param string $msgid String to be translated
*
* @return string translated string (or original, if not found)
*/
function __(string $msgid): string
{
return Loader::getInstance()->getTranslator()->gettext(
$msgid
);
}
/**
* Plural version of gettext.
*
* @param string $msgid Single form
* @param string $msgidPlural Plural form
* @param int $number Number of objects
*
* @return string translated plural form
*/
function _ngettext(string $msgid, string $msgidPlural, int $number): string
{
return Loader::getInstance()->getTranslator()->ngettext(
$msgid,
$msgidPlural,
$number
);
}
/**
* Translate with context.
*
* @param string $msgctxt Context
* @param string $msgid String to be translated
*
* @return string translated plural form
*/
function _pgettext(string $msgctxt, string $msgid): string
{
return Loader::getInstance()->getTranslator()->pgettext(
$msgctxt,
$msgid
);
}
/**
* Plural version of pgettext.
*
* @param string $msgctxt Context
* @param string $msgid Single form
* @param string $msgidPlural Plural form
* @param int $number Number of objects
*
* @return string translated plural form
*/
function _npgettext(string $msgctxt, string $msgid, string $msgidPlural, int $number): string
{
return Loader::getInstance()->getTranslator()->npgettext(
$msgctxt,
$msgid,
$msgidPlural,
$number
);
}
/**
* Translates a string.
*
* @param string $domain Domain to use
* @param string $msgid String to be translated
*
* @return string translated string (or original, if not found)
*/
function _dgettext(string $domain, string $msgid): string
{
return Loader::getInstance()->getTranslator($domain)->gettext(
$msgid
);
}
/**
* Plural version of gettext.
*
* @param string $domain Domain to use
* @param string $msgid Single form
* @param string $msgidPlural Plural form
* @param int $number Number of objects
*
* @return string translated plural form
*/
function _dngettext(string $domain, string $msgid, string $msgidPlural, int $number): string
{
return Loader::getInstance()->getTranslator($domain)->ngettext(
$msgid,
$msgidPlural,
$number
);
}
/**
* Translate with context.
*
* @param string $domain Domain to use
* @param string $msgctxt Context
* @param string $msgid String to be translated
*
* @return string translated plural form
*/
function _dpgettext(string $domain, string $msgctxt, string $msgid): string
{
return Loader::getInstance()->getTranslator($domain)->pgettext(
$msgctxt,
$msgid
);
}
/**
* Plural version of pgettext.
*
* @param string $domain Domain to use
* @param string $msgctxt Context
* @param string $msgid Single form
* @param string $msgidPlural Plural form
* @param int $number Number of objects
*
* @return string translated plural form
*/
function _dnpgettext(string $domain, string $msgctxt, string $msgid, string $msgidPlural, int $number): string
{
return Loader::getInstance()->getTranslator($domain)->npgettext(
$msgctxt,
$msgid,
$msgidPlural,
$number
);
}

View file

@ -0,0 +1,80 @@
# Change Log
## [2.1] - 2017-05-15
* Documentation improvements.
## [2.0] - 2017-01-23
* Switched to PhpMyAdmin vendor namespace to follow PSR-4.
## [1.2] - 2017-01-07
* Coding style cleanup.
* PHP 7.2 support.
* Avoid installing tests and test data using composer.
## [1.1] - 2016-11-21
* Fixed adjusting of record bouding box
## [1.0] - 2016-11-21
* Documentation improvements
* Code cleanups
## [0.12] - 2016-11-17
* Fixed DBF search
* Improved test coverage
## [0.11] - 2016-11-16
* Code cleanups
* Fixed behavior without configured DBF header
## [0.11] - 2016-11-16
* Fixed saving Polygon/Polyline creation with multiple parts
* Fixed saving Multipont records
## [0.10] - 2016-09-05
* Improved error handling on loading
## [0.9] - 2016-08-04
* Code cleanups
## [0.8] - 2016-06-24
* Code cleanups
* Fixed loading of records with optional data
## [0.7] - 2016-06-24
* Properly fail on loading corrupted files
## [0.6] - 2016-06-24
* Fixed detection of end of file when loading
## [0.5] - 2016-06-24
* Added getShapeName method to ShapeFile
## [0.4] - 2016-06-24
* Make API work even without real file open
## [0.3] - 2016-06-24
* Better support for subclassing
## [0.2] - 2016-06-24
* Make the dbase extension optional dependency
## [0.1] - 2016-06-14
* Inital release based on bfShapeFiles

View file

@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc., <http://fsf.org/>
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{description}
Copyright (C) {year} {fullname}
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
{signature of Ty Coon}, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

View file

@ -0,0 +1,57 @@
# shapefile
ShapeFile library for PHP
[![Build Status](https://travis-ci.org/phpmyadmin/shapefile.svg?branch=master)](https://travis-ci.org/phpmyadmin/shapefile)
[![codecov.io](https://codecov.io/github/phpmyadmin/shapefile/coverage.svg?branch=master)](https://codecov.io/github/phpmyadmin/shapefile?branch=master)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/phpmyadmin/shapefile/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/phpmyadmin/shapefile/?branch=master)
[![Packagist](https://img.shields.io/packagist/dt/phpmyadmin/shapefile.svg)](https://packagist.org/packages/phpmyadmin/shapefile)
## Features
Currently the 2D and 3D variants except MultiPatch of the ShapeFile format as
defined in https://www.esri.com/library/whitepapers/pdfs/shapefile.pdf. The
library currently supports reading and editing of ShapeFiles and the Associated
information (DBF file). There are a lot of things that can be improved in the
code, if you are interested in developing, helping with the documentation,
making translations or offering new ideas please contact us.
## Installation
Please use [Composer][1] to install:
```
composer require phpmyadmin/shapefile
```
To be able to read and write the associated DBF file, you need ``dbase``
extension:
```
pecl install dbase
echo "extension=dbase.so" > /etc/php5/conf.d/dbase.ini
```
## Documentation
The API documentation is available at
<https://develdocs.phpmyadmin.net/shapefile/>.
## Usage
To read shape file:
```php
$shp = new \PhpMyAdmin\ShapeFile\ShapeFile(0);
$shp->loadFromFile('path/file.*');
```
## History
This library is based on BytesFall ShapeFiles library written by Ovidio (ovidio
AT users.sourceforge.net). The library has been embedded in phpMyAdmin for
years and slowly developed there. At one point people started to use our
version rather than the original library and that was the point we decided to
make it separate package.
[1]:https://getcomposer.org/

View file

@ -0,0 +1,3 @@
comment:
layout: header, changes, diff
coverage: {}

View file

@ -0,0 +1,33 @@
{
"name": "phpmyadmin/shapefile",
"description": "ESRI ShapeFile library for PHP",
"license": "GPL-2.0+",
"keywords": ["shapefile", "shp", "geo", "geospatial", "dbf", "ESRI", "shape"],
"homepage": "https://github.com/phpmyadmin/shapefile",
"authors": [
{
"name": "The phpMyAdmin Team",
"email": "developers@phpmyadmin.net",
"homepage": "https://www.phpmyadmin.net/team/"
}
],
"support": {
"issues": "https://github.com/phpmyadmin/shapefile/issues",
"source": "https://github.com/phpmyadmin/shapefile"
},
"require": {
"php": ">=5.4.0"
},
"suggest": {
"ext-dbase": "For dbf files parsing"
},
"require-dev": {
"phpunit/php-code-coverage": "*",
"phpunit/phpunit": "~4.8 || ~5.7"
},
"autoload": {
"psr-4": {
"PhpMyAdmin\\ShapeFile\\": "src"
}
}
}

View file

@ -0,0 +1,647 @@
<?php
/**
* phpMyAdmin ShapeFile library
* <https://github.com/phpmyadmin/shapefile/>.
*
* Copyright 2006-2007 Ovidio <ovidio AT users.sourceforge.net>
* Copyright 2016 - 2017 Michal Čihař <michal@cihar.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, you can download one from
* https://www.gnu.org/copyleft/gpl.html.
*/
namespace PhpMyAdmin\ShapeFile;
/**
* ShapeFile class.
*/
class ShapeFile
{
const MAGIC = 0x270a;
public $FileName;
private $SHPFile = null;
private $SHXFile = null;
private $DBFFile = null;
private $DBFHeader;
public $lastError = '';
public $boundingBox = array('xmin' => 0.0, 'ymin' => 0.0, 'xmax' => 0.0, 'ymax' => 0.0);
private $fileLength = 0;
public $shapeType = 0;
public $records = array();
/**
* Checks whether dbase manipuations are supported.
*
* @return bool
*/
public static function supports_dbase()
{
return extension_loaded('dbase');
}
/**
* @param int $shapeType File shape type, should be same as all records
* @param array $boundingBox File bounding box
* @param null|mixed $FileName File name
*/
public function __construct($shapeType, $boundingBox = array('xmin' => 0.0, 'ymin' => 0.0, 'xmax' => 0.0, 'ymax' => 0.0), $FileName = null)
{
$this->shapeType = $shapeType;
$this->boundingBox = $boundingBox;
$this->FileName = $FileName;
$this->fileLength = 50; // The value for file length is the total length of the file in 16-bit words (including the fifty 16-bit words that make up the header).
}
/**
* Loads shapefile and dbase (if supported).
*
* @param string $FileName File mask to load (eg. example.*)
*/
public function loadFromFile($FileName)
{
if (!empty($FileName)) {
$this->FileName = $FileName;
$result = $this->_openSHPFile();
} else {
/* We operate on buffer emulated by readSHP / eofSHP */
$result = true;
}
if ($result && ($this->_openDBFFile())) {
if (!$this->_loadHeaders()) {
$this->_closeSHPFile();
$this->_closeDBFFile();
return false;
}
if (!$this->_loadRecords()) {
$this->_closeSHPFile();
$this->_closeDBFFile();
return false;
}
$this->_closeSHPFile();
$this->_closeDBFFile();
return true;
}
return false;
}
/**
* Saves shapefile.
*
* @param string|null $FileName Name of file, otherwise existing is used
*/
public function saveToFile($FileName = null)
{
if (!is_null($FileName)) {
$this->FileName = $FileName;
}
if (($this->_openSHPFile(true)) && ($this->_openSHXFile(true)) && ($this->_createDBFFile())) {
$this->_saveHeaders();
$this->_saveRecords();
$this->_closeSHPFile();
$this->_closeSHXFile();
$this->_closeDBFFile();
} else {
return false;
}
}
/**
* Generates filename with given extension.
*
* @param string $extension Extension to use (including dot)
*
* @return string
*/
private function _getFilename($extension)
{
return str_replace('.*', $extension, $this->FileName);
}
/**
* Updates bounding box based on SHPData.
*
* @param string $type Type of box
* @param array $data ShapeRecord SHPData
*/
private function updateBBox($type, $data)
{
$min = $type . 'min';
$max = $type . 'max';
if (!isset($this->boundingBox[$min]) || $this->boundingBox[$min] == 0.0 || ($this->boundingBox[$min] > $data[$min])) {
$this->boundingBox[$min] = $data[$min];
}
if (!isset($this->boundingBox[$max]) || $this->boundingBox[$max] == 0.0 || ($this->boundingBox[$max] < $data[$max])) {
$this->boundingBox[$max] = $data[$max];
}
}
/**
* Adds record to shape file.
*
* @param ShapeRecord $record
*
* @return int Number of added record
*/
public function addRecord($record)
{
if ((isset($this->DBFHeader)) && (is_array($this->DBFHeader))) {
$record->updateDBFInfo($this->DBFHeader);
}
$this->fileLength += ($record->getContentLength() + 4);
$this->records[] = $record;
$this->records[count($this->records) - 1]->recordNumber = count($this->records);
$this->updateBBox('x', $record->SHPData);
$this->updateBBox('y', $record->SHPData);
if (in_array($this->shapeType, array(11, 13, 15, 18, 21, 23, 25, 28))) {
$this->updateBBox('m', $record->SHPData);
}
if (in_array($this->shapeType, array(11, 13, 15, 18))) {
$this->updateBBox('z', $record->SHPData);
}
return count($this->records) - 1;
}
/**
* Deletes record from shapefile.
*
* @param int $index
*/
public function deleteRecord($index)
{
if (isset($this->records[$index])) {
$this->fileLength -= ($this->records[$index]->getContentLength() + 4);
$count = count($this->records) - 1;
for ($i = $index; $i < $count; ++$i) {
$this->records[$i] = $this->records[$i + 1];
}
unset($this->records[count($this->records) - 1]);
$this->_deleteRecordFromDBF($index);
}
}
/**
* Returns array defining fields in DBF file.
*
* @return array see setDBFHeader for more information
*/
public function getDBFHeader()
{
return $this->DBFHeader;
}
/**
* Changes array defining fields in DBF file, used in dbase_create call.
*
* @param array $header An array of arrays, each array describing the
* format of one field of the database. Each
* field consists of a name, a character indicating
* the field type, and optionally, a length,
* a precision and a nullable flag.
*/
public function setDBFHeader($header)
{
$this->DBFHeader = $header;
$count = count($this->records);
for ($i = 0; $i < $count; ++$i) {
$this->records[$i]->updateDBFInfo($header);
}
}
/**
* Lookups value in the DBF file and returs index.
*
* @param string $field Field to match
* @param mixed $value Value to match
*
* @return int
*/
public function getIndexFromDBFData($field, $value)
{
foreach ($this->records as $index => $record) {
if (isset($record->DBFData[$field]) &&
(trim(strtoupper($record->DBFData[$field])) == strtoupper($value))
) {
return $index;
}
}
return -1;
}
/**
* Loads DBF metadata.
*/
private function _loadDBFHeader()
{
$DBFFile = fopen($this->_getFilename('.dbf'), 'r');
$result = array();
$i = 1;
$inHeader = true;
while ($inHeader) {
if (!feof($DBFFile)) {
$buff32 = fread($DBFFile, 32);
if ($i > 1) {
if (substr($buff32, 0, 1) == chr(13)) {
$inHeader = false;
} else {
$pos = strpos(substr($buff32, 0, 10), chr(0));
$pos = ($pos == 0 ? 10 : $pos);
$fieldName = substr($buff32, 0, $pos);
$fieldType = substr($buff32, 11, 1);
$fieldLen = ord(substr($buff32, 16, 1));
$fieldDec = ord(substr($buff32, 17, 1));
array_push($result, array($fieldName, $fieldType, $fieldLen, $fieldDec));
}
}
++$i;
} else {
$inHeader = false;
}
}
fclose($DBFFile);
return $result;
}
/**
* Deletes record from the DBF file.
*
* @param int $index
*/
private function _deleteRecordFromDBF($index)
{
if (@dbase_delete_record($this->DBFFile, $index)) {
dbase_pack($this->DBFFile);
}
}
/**
* Loads SHP file metadata.
*
* @return bool
*/
private function _loadHeaders()
{
if (Util::loadData('N', $this->readSHP(4)) != self::MAGIC) {
$this->setError('Not a SHP file (file code mismatch)');
return false;
}
/* Skip 20 unused bytes */
$this->readSHP(20);
$this->fileLength = Util::loadData('N', $this->readSHP(4));
/* We currently ignore version */
$this->readSHP(4);
$this->shapeType = Util::loadData('V', $this->readSHP(4));
$this->boundingBox = array();
$this->boundingBox['xmin'] = Util::loadData('d', $this->readSHP(8));
$this->boundingBox['ymin'] = Util::loadData('d', $this->readSHP(8));
$this->boundingBox['xmax'] = Util::loadData('d', $this->readSHP(8));
$this->boundingBox['ymax'] = Util::loadData('d', $this->readSHP(8));
$this->boundingBox['zmin'] = Util::loadData('d', $this->readSHP(8));
$this->boundingBox['zmax'] = Util::loadData('d', $this->readSHP(8));
$this->boundingBox['mmin'] = Util::loadData('d', $this->readSHP(8));
$this->boundingBox['mmax'] = Util::loadData('d', $this->readSHP(8));
if (self::supports_dbase()) {
$this->DBFHeader = $this->_loadDBFHeader();
}
return true;
}
/**
* Saves bounding box record, possibly using 0 instead of not set values.
*
* @param file $file File object
* @param string $type Bounding box dimension (eg. xmax, mmin...)
*/
private function _saveBBoxRecord($file, $type)
{
fwrite($file, Util::packDouble(
isset($this->boundingBox[$type]) ? $this->boundingBox[$type] : 0)
);
}
/**
* Saves bounding box to a file.
*
* @param file $file File object
*/
private function _saveBBox($file)
{
$this->_saveBBoxRecord($file, 'xmin');
$this->_saveBBoxRecord($file, 'ymin');
$this->_saveBBoxRecord($file, 'xmax');
$this->_saveBBoxRecord($file, 'ymax');
$this->_saveBBoxRecord($file, 'zmin');
$this->_saveBBoxRecord($file, 'zmax');
$this->_saveBBoxRecord($file, 'mmin');
$this->_saveBBoxRecord($file, 'mmax');
}
/**
* Saves SHP and SHX file metadata.
*/
private function _saveHeaders()
{
fwrite($this->SHPFile, pack('NNNNNN', self::MAGIC, 0, 0, 0, 0, 0));
fwrite($this->SHPFile, pack('N', $this->fileLength));
fwrite($this->SHPFile, pack('V', 1000));
fwrite($this->SHPFile, pack('V', $this->shapeType));
$this->_saveBBox($this->SHPFile);
fwrite($this->SHXFile, pack('NNNNNN', self::MAGIC, 0, 0, 0, 0, 0));
fwrite($this->SHXFile, pack('N', 50 + 4 * count($this->records)));
fwrite($this->SHXFile, pack('V', 1000));
fwrite($this->SHXFile, pack('V', $this->shapeType));
$this->_saveBBox($this->SHXFile);
}
/**
* Loads records from SHP file (and DBF).
*
* @return bool
*/
private function _loadRecords()
{
/* Need to start at offset 100 */
while (!$this->eofSHP()) {
$record = new ShapeRecord(-1);
$record->loadFromFile($this, $this->SHPFile, $this->DBFFile);
if ($record->lastError != '') {
$this->setError($record->lastError);
return false;
}
if (($record->shapeType === false || $record->shapeType === '') && $this->eofSHP()) {
break;
}
$this->records[] = $record;
}
return true;
}
/**
* Saves records to SHP and SHX files.
*/
private function _saveRecords()
{
$offset = 50;
if (is_array($this->records) && (count($this->records) > 0)) {
foreach ($this->records as $index => $record) {
//Save the record to the .shp file
$record->saveToFile($this->SHPFile, $this->DBFFile, $index + 1);
//Save the record to the .shx file
fwrite($this->SHXFile, pack('N', $offset));
fwrite($this->SHXFile, pack('N', $record->getContentLength()));
$offset += (4 + $record->getContentLength());
}
}
}
/**
* Generic interface to open files.
*
* @param bool $toWrite Whether file should be opened for writing
* @param string $extension File extension
* @param string $name Verbose file name to report errors
*
* @return file|false File handle
*/
private function _openFile($toWrite, $extension, $name)
{
$shp_name = $this->_getFilename($extension);
$result = @fopen($shp_name, ($toWrite ? 'wb+' : 'rb'));
if (!$result) {
$this->setError(sprintf('It wasn\'t possible to open the %s file "%s"', $name, $shp_name));
return false;
}
return $result;
}
/**
* Opens SHP file.
*
* @param bool $toWrite Whether file should be opened for writing
*
* @return bool
*/
private function _openSHPFile($toWrite = false)
{
$this->SHPFile = $this->_openFile($toWrite, '.shp', 'Shape');
if (!$this->SHPFile) {
return false;
}
return true;
}
/**
* Closes SHP file.
*/
private function _closeSHPFile()
{
if ($this->SHPFile) {
fclose($this->SHPFile);
$this->SHPFile = null;
}
}
/**
* Opens SHX file.
*
* @param bool $toWrite Whether file should be opened for writing
*
* @return bool
*/
private function _openSHXFile($toWrite = false)
{
$this->SHXFile = $this->_openFile($toWrite, '.shx', 'Index');
if (!$this->SHXFile) {
return false;
}
return true;
}
/**
* Closes SHX file.
*/
private function _closeSHXFile()
{
if ($this->SHXFile) {
fclose($this->SHXFile);
$this->SHXFile = null;
}
}
/**
* Creates DBF file.
*
* @return bool
*/
private function _createDBFFile()
{
if (!self::supports_dbase() || !is_array($this->DBFHeader) || count($this->DBFHeader) == 0) {
$this->DBFFile = null;
return true;
}
$dbf_name = $this->_getFilename('.dbf');
/* Unlink existing file */
if (file_exists($dbf_name)) {
unlink($dbf_name);
}
/* Create new file */
$this->DBFFile = @dbase_create($dbf_name, $this->DBFHeader);
if ($this->DBFFile === false) {
$this->setError(sprintf('It wasn\'t possible to create the DBase file "%s"', $dbf_name));
return false;
}
return true;
}
/**
* Loads DBF file if supported.
*
* @return bool
*/
private function _openDBFFile()
{
if (!self::supports_dbase()) {
$this->DBFFile = null;
return true;
}
$dbf_name = $this->_getFilename('.dbf');
if (is_readable($dbf_name)) {
$this->DBFFile = @dbase_open($dbf_name, 0);
if (!$this->DBFFile) {
$this->setError(sprintf('It wasn\'t possible to open the DBase file "%s"', $dbf_name));
return false;
}
} else {
$this->setError(sprintf('It wasn\'t possible to find the DBase file "%s"', $dbf_name));
return false;
}
return true;
}
/**
* Closes DBF file.
*/
private function _closeDBFFile()
{
if ($this->DBFFile) {
dbase_close($this->DBFFile);
$this->DBFFile = null;
}
}
/**
* Sets error message.
*
* @param string $error
*/
public function setError($error)
{
$this->lastError = $error;
}
/**
* Reads given number of bytes from SHP file.
*
* @param int $bytes
*
* @return string
*/
public function readSHP($bytes)
{
return fread($this->SHPFile, $bytes);
}
/**
* Checks whether file is at EOF.
*
* @return bool
*/
public function eofSHP()
{
return feof($this->SHPFile);
}
/**
* Returns shape name.
*
* @return string
*/
public function getShapeName()
{
return Util::nameShape($this->shapeType);
}
/**
* Check whether file contains measure data.
*
* For some reason this is distinguished by zero bounding box in the
* specification.
*
* @return bool
*/
public function hasMeasure()
{
return $this->boundingBox['mmin'] != 0 || $this->boundingBox['mmax'] != 0;
}
}

View file

@ -0,0 +1,849 @@
<?php
/**
* phpMyAdmin ShapeFile library
* <https://github.com/phpmyadmin/shapefile/>.
*
* Copyright 2006-2007 Ovidio <ovidio AT users.sourceforge.net>
* Copyright 2016 - 2017 Michal Čihař <michal@cihar.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, you can download one from
* https://www.gnu.org/copyleft/gpl.html.
*/
namespace PhpMyAdmin\ShapeFile;
/**
* ShapeFile record class.
*/
class ShapeRecord
{
private $SHPFile = null;
private $DBFFile = null;
private $ShapeFile = null;
private $size = 0;
private $read = 0;
public $recordNumber = null;
public $shapeType = null;
public $lastError = '';
public $SHPData = array();
public $DBFData = array();
/**
* @param int $shapeType
*/
public function __construct($shapeType)
{
$this->shapeType = $shapeType;
}
/**
* Loads record from files.
*
* @param ShapeFile $ShapeFile
* @param file &$SHPFile Opened SHP file
* @param file &$DBFFile Opened DBF file
*/
public function loadFromFile(&$ShapeFile, &$SHPFile, &$DBFFile)
{
$this->ShapeFile = $ShapeFile;
$this->SHPFile = $SHPFile;
$this->DBFFile = $DBFFile;
$this->_loadHeaders();
/* No header read */
if ($this->read == 0) {
return;
}
switch ($this->shapeType) {
case 0:
$this->_loadNullRecord();
break;
case 1:
$this->_loadPointRecord();
break;
case 21:
$this->_loadPointMRecord();
break;
case 11:
$this->_loadPointZRecord();
break;
case 3:
$this->_loadPolyLineRecord();
break;
case 23:
$this->_loadPolyLineMRecord();
break;
case 13:
$this->_loadPolyLineZRecord();
break;
case 5:
$this->_loadPolygonRecord();
break;
case 25:
$this->_loadPolygonMRecord();
break;
case 15:
$this->_loadPolygonZRecord();
break;
case 8:
$this->_loadMultiPointRecord();
break;
case 28:
$this->_loadMultiPointMRecord();
break;
case 18:
$this->_loadMultiPointZRecord();
break;
default:
$this->setError(sprintf('The Shape Type "%s" is not supported.', $this->shapeType));
break;
}
/* We need to skip rest of the record */
while ($this->read < $this->size) {
$this->_loadData('V', 4);
}
/* Check if we didn't read too much */
if ($this->read != $this->size) {
$this->setError(sprintf('Failed to parse record, read=%d, size=%d', $this->read, $this->size));
}
if (ShapeFile::supports_dbase() && isset($this->DBFFile)) {
$this->_loadDBFData();
}
}
/**
* Saves record to files.
*
* @param file &$SHPFile Opened SHP file
* @param file &$DBFFile Opened DBF file
* @param int $recordNumber Record number
*/
public function saveToFile(&$SHPFile, &$DBFFile, $recordNumber)
{
$this->SHPFile = $SHPFile;
$this->DBFFile = $DBFFile;
$this->recordNumber = $recordNumber;
$this->_saveHeaders();
switch ($this->shapeType) {
case 0:
// Nothing to save
break;
case 1:
$this->_savePointRecord();
break;
case 21:
$this->_savePointMRecord();
break;
case 11:
$this->_savePointZRecord();
break;
case 3:
$this->_savePolyLineRecord();
break;
case 23:
$this->_savePolyLineMRecord();
break;
case 13:
$this->_savePolyLineZRecord();
break;
case 5:
$this->_savePolygonRecord();
break;
case 25:
$this->_savePolygonMRecord();
break;
case 15:
$this->_savePolygonZRecord();
break;
case 8:
$this->_saveMultiPointRecord();
break;
case 28:
$this->_saveMultiPointMRecord();
break;
case 18:
$this->_saveMultiPointZRecord();
break;
default:
$this->setError(sprintf('The Shape Type "%s" is not supported.', $this->shapeType));
break;
}
if (ShapeFile::supports_dbase() && !is_null($this->DBFFile)) {
$this->_saveDBFData();
}
}
/**
* Updates DBF data to match header.
*
* @param array $header DBF structure header
*/
public function updateDBFInfo($header)
{
$tmp = $this->DBFData;
unset($this->DBFData);
$this->DBFData = array();
foreach ($header as $value) {
$this->DBFData[$value[0]] = (isset($tmp[$value[0]])) ? $tmp[$value[0]] : '';
}
}
/**
* Reads data.
*
* @param string $type type for unpack()
* @param int $count number of bytes
*
* @return mixed
*/
private function _loadData($type, $count)
{
$data = $this->ShapeFile->readSHP($count);
if ($data === false) {
return false;
}
$this->read += strlen($data);
return Util::loadData($type, $data);
}
/**
* Loads metadata header from a file.
*/
private function _loadHeaders()
{
$this->shapeType = false;
$this->recordNumber = $this->_loadData('N', 4);
if ($this->recordNumber === false) {
return;
}
// We read the length of the record
$this->size = $this->_loadData('N', 4);
if ($this->size === false) {
return;
}
$this->size = $this->size * 2 + 8;
$this->shapeType = $this->_loadData('V', 4);
}
/**
* Saves metadata header to a file.
*/
private function _saveHeaders()
{
fwrite($this->SHPFile, pack('N', $this->recordNumber));
fwrite($this->SHPFile, pack('N', $this->getContentLength()));
fwrite($this->SHPFile, pack('V', $this->shapeType));
}
private function _loadPoint()
{
$data = array();
$data['x'] = $this->_loadData('d', 8);
$data['y'] = $this->_loadData('d', 8);
return $data;
}
private function _loadPointM()
{
$data = $this->_loadPoint();
$data['m'] = $this->_loadData('d', 8);
return $data;
}
private function _loadPointZ()
{
$data = $this->_loadPoint();
$data['z'] = $this->_loadData('d', 8);
$data['m'] = $this->_loadData('d', 8);
return $data;
}
private function _savePoint($data)
{
fwrite($this->SHPFile, Util::packDouble($data['x']));
fwrite($this->SHPFile, Util::packDouble($data['y']));
}
private function _savePointM($data)
{
fwrite($this->SHPFile, Util::packDouble($data['x']));
fwrite($this->SHPFile, Util::packDouble($data['y']));
fwrite($this->SHPFile, Util::packDouble($data['m']));
}
private function _savePointZ($data)
{
fwrite($this->SHPFile, Util::packDouble($data['x']));
fwrite($this->SHPFile, Util::packDouble($data['y']));
fwrite($this->SHPFile, Util::packDouble($data['z']));
fwrite($this->SHPFile, Util::packDouble($data['m']));
}
private function _loadNullRecord()
{
$this->SHPData = array();
}
private function _loadPointRecord()
{
$this->SHPData = $this->_loadPoint();
}
private function _loadPointMRecord()
{
$this->SHPData = $this->_loadPointM();
}
private function _loadPointZRecord()
{
$this->SHPData = $this->_loadPointZ();
}
private function _savePointRecord()
{
$this->_savePoint($this->SHPData);
}
private function _savePointMRecord()
{
$this->_savePointM($this->SHPData);
}
private function _savePointZRecord()
{
$this->_savePointZ($this->SHPData);
}
private function _loadBBox()
{
$this->SHPData['xmin'] = $this->_loadData('d', 8);
$this->SHPData['ymin'] = $this->_loadData('d', 8);
$this->SHPData['xmax'] = $this->_loadData('d', 8);
$this->SHPData['ymax'] = $this->_loadData('d', 8);
}
private function _loadMultiPointRecord()
{
$this->SHPData = array();
$this->_loadBBox();
$this->SHPData['numpoints'] = $this->_loadData('V', 4);
for ($i = 0; $i < $this->SHPData['numpoints']; ++$i) {
$this->SHPData['points'][] = $this->_loadPoint();
}
}
/**
* @param string $type
*/
private function _loadMultiPointMZRecord($type)
{
/* The m dimension is optional, depends on bounding box data */
if ($type == 'm' && !$this->ShapeFile->hasMeasure()) {
return;
}
$this->SHPData[$type . 'min'] = $this->_loadData('d', 8);
$this->SHPData[$type . 'max'] = $this->_loadData('d', 8);
for ($i = 0; $i < $this->SHPData['numpoints']; ++$i) {
$this->SHPData['points'][$i][$type] = $this->_loadData('d', 8);
}
}
private function _loadMultiPointMRecord()
{
$this->_loadMultiPointRecord();
$this->_loadMultiPointMZRecord('m');
}
private function _loadMultiPointZRecord()
{
$this->_loadMultiPointRecord();
$this->_loadMultiPointMZRecord('z');
$this->_loadMultiPointMZRecord('m');
}
private function _saveMultiPointRecord()
{
fwrite($this->SHPFile, pack('dddd', $this->SHPData['xmin'], $this->SHPData['ymin'], $this->SHPData['xmax'], $this->SHPData['ymax']));
fwrite($this->SHPFile, pack('V', $this->SHPData['numpoints']));
for ($i = 0; $i < $this->SHPData['numpoints']; ++$i) {
$this->_savePoint($this->SHPData['points'][$i]);
}
}
/**
* @param string $type
*/
private function _saveMultiPointMZRecord($type)
{
fwrite($this->SHPFile, pack('dd', $this->SHPData[$type . 'min'], $this->SHPData[$type . 'max']));
for ($i = 0; $i < $this->SHPData['numpoints']; ++$i) {
fwrite($this->SHPFile, Util::packDouble($this->SHPData['points'][$i][$type]));
}
}
private function _saveMultiPointMRecord()
{
$this->_saveMultiPointRecord();
$this->_saveMultiPointMZRecord('m');
}
private function _saveMultiPointZRecord()
{
$this->_saveMultiPointRecord();
$this->_saveMultiPointMZRecord('z');
$this->_saveMultiPointMZRecord('m');
}
private function _loadPolyLineRecord()
{
$this->SHPData = array();
$this->_loadBBox();
$this->SHPData['numparts'] = $this->_loadData('V', 4);
$this->SHPData['numpoints'] = $this->_loadData('V', 4);
$numparts = $this->SHPData['numparts'];
$numpoints = $this->SHPData['numpoints'];
for ($i = 0; $i < $numparts; ++$i) {
$this->SHPData['parts'][$i] = $this->_loadData('V', 4);
}
$part = 0;
for ($i = 0; $i < $numpoints; ++$i) {
if ($part + 1 < $numparts && $this->SHPData['parts'][$part + 1] == $i) {
++$part;
}
if (!isset($this->SHPData['parts'][$part]['points']) || !is_array($this->SHPData['parts'][$part]['points'])) {
$this->SHPData['parts'][$part] = array('points' => array());
}
$this->SHPData['parts'][$part]['points'][] = $this->_loadPoint();
}
}
/**
* @param string $type
*/
private function _loadPolyLineMZRecord($type)
{
/* The m dimension is optional, depends on bounding box data */
if ($type == 'm' && !$this->ShapeFile->hasMeasure()) {
return;
}
$this->SHPData[$type . 'min'] = $this->_loadData('d', 8);
$this->SHPData[$type . 'max'] = $this->_loadData('d', 8);
$numparts = $this->SHPData['numparts'];
$numpoints = $this->SHPData['numpoints'];
$part = 0;
for ($i = 0; $i < $numpoints; ++$i) {
if ($part + 1 < $numparts && $this->SHPData['parts'][$part + 1] == $i) {
++$part;
}
$this->SHPData['parts'][$part]['points'][$i][$type] = $this->_loadData('d', 8);
}
}
private function _loadPolyLineMRecord()
{
$this->_loadPolyLineRecord();
$this->_loadPolyLineMZRecord('m');
}
private function _loadPolyLineZRecord()
{
$this->_loadPolyLineRecord();
$this->_loadPolyLineMZRecord('z');
$this->_loadPolyLineMZRecord('m');
}
private function _savePolyLineRecord()
{
fwrite($this->SHPFile, pack('dddd', $this->SHPData['xmin'], $this->SHPData['ymin'], $this->SHPData['xmax'], $this->SHPData['ymax']));
fwrite($this->SHPFile, pack('VV', $this->SHPData['numparts'], $this->SHPData['numpoints']));
$part_index = 0;
for ($i = 0; $i < $this->SHPData['numparts']; ++$i) {
fwrite($this->SHPFile, pack('V', $part_index));
$part_index += count($this->SHPData['parts'][$i]['points']);
}
foreach ($this->SHPData['parts'] as $partData) {
foreach ($partData['points'] as $pointData) {
$this->_savePoint($pointData);
}
}
}
/**
* @param string $type
*/
private function _savePolyLineMZRecord($type)
{
fwrite($this->SHPFile, pack('dd', $this->SHPData[$type . 'min'], $this->SHPData[$type . 'max']));
foreach ($this->SHPData['parts'] as $partData) {
foreach ($partData['points'] as $pointData) {
fwrite($this->SHPFile, Util::packDouble($pointData[$type]));
}
}
}
private function _savePolyLineMRecord()
{
$this->_savePolyLineRecord();
$this->_savePolyLineMZRecord('m');
}
private function _savePolyLineZRecord()
{
$this->_savePolyLineRecord();
$this->_savePolyLineMZRecord('z');
$this->_savePolyLineMZRecord('m');
}
private function _loadPolygonRecord()
{
$this->_loadPolyLineRecord();
}
private function _loadPolygonMRecord()
{
$this->_loadPolyLineMRecord();
}
private function _loadPolygonZRecord()
{
$this->_loadPolyLineZRecord();
}
private function _savePolygonRecord()
{
$this->_savePolyLineRecord();
}
private function _savePolygonMRecord()
{
$this->_savePolyLineMRecord();
}
private function _savePolygonZRecord()
{
$this->_savePolyLineZRecord();
}
private function _adjustBBox($point)
{
// Adjusts bounding box based on point
$directions = array('x', 'y', 'z', 'm');
foreach ($directions as $direction) {
if (!isset($point[$direction])) {
continue;
}
$min = $direction . 'min';
$max = $direction . 'max';
if (!isset($this->SHPData[$min]) || ($this->SHPData[$min] > $point[$direction])) {
$this->SHPData[$min] = $point[$direction];
}
if (!isset($this->SHPData[$max]) || ($this->SHPData[$max] < $point[$direction])) {
$this->SHPData[$max] = $point[$direction];
}
}
}
/**
* Sets dimension to 0 if not set.
*
* @param array $point Point to check
* @param string $dimension Dimension to check
*
* @return array
*/
private function _fixPoint($point, $dimension)
{
if (!isset($point[$dimension])) {
$point[$dimension] = 0.0; // no_value
}
return $point;
}
/**
* Adjust point and bounding box when adding point.
*
* @param array $point Point data
*
* @return array Fixed point data
*/
private function _adjustPoint($point)
{
$type = $this->shapeType / 10;
if ($type >= 2) {
$point = $this->_fixPoint($point, 'm');
} elseif ($type >= 1) {
$point = $this->_fixPoint($point, 'z');
$point = $this->_fixPoint($point, 'm');
}
return $point;
}
/**
* Adds point to a record.
*
* @param array $point Point data
* @param int $partIndex Part index
*/
public function addPoint($point, $partIndex = 0)
{
$point = $this->_adjustPoint($point);
switch ($this->shapeType) {
case 0:
//Don't add anything
return;
case 1:
case 11:
case 21:
//Substitutes the value of the current point
$this->SHPData = $point;
break;
case 3:
case 5:
case 13:
case 15:
case 23:
case 25:
//Adds a new point to the selected part
$this->SHPData['parts'][$partIndex]['points'][] = $point;
$this->SHPData['numparts'] = count($this->SHPData['parts']);
$this->SHPData['numpoints'] = 1 + (isset($this->SHPData['numpoints']) ? $this->SHPData['numpoints'] : 0);
break;
case 8:
case 18:
case 28:
//Adds a new point
$this->SHPData['points'][] = $point;
$this->SHPData['numpoints'] = 1 + (isset($this->SHPData['numpoints']) ? $this->SHPData['numpoints'] : 0);
break;
default:
$this->setError(sprintf('The Shape Type "%s" is not supported.', $this->shapeType));
return;
}
$this->_adjustBBox($point);
}
/**
* Deletes point from a record.
*
* @param int $pointIndex Point index
* @param int $partIndex Part index
*/
public function deletePoint($pointIndex = 0, $partIndex = 0)
{
switch ($this->shapeType) {
case 0:
//Don't delete anything
break;
case 1:
case 11:
case 21:
//Sets the value of the point to zero
$this->SHPData['x'] = 0.0;
$this->SHPData['y'] = 0.0;
if (in_array($this->shapeType, array(11, 21))) {
$this->SHPData['m'] = 0.0;
}
if (in_array($this->shapeType, array(11))) {
$this->SHPData['z'] = 0.0;
}
break;
case 3:
case 5:
case 13:
case 15:
case 23:
case 25:
//Deletes the point from the selected part, if exists
if (isset($this->SHPData['parts'][$partIndex]) && isset($this->SHPData['parts'][$partIndex]['points'][$pointIndex])) {
$count = count($this->SHPData['parts'][$partIndex]['points']) - 1;
for ($i = $pointIndex; $i < $count; ++$i) {
$this->SHPData['parts'][$partIndex]['points'][$i] = $this->SHPData['parts'][$partIndex]['points'][$i + 1];
}
unset($this->SHPData['parts'][$partIndex]['points'][count($this->SHPData['parts'][$partIndex]['points']) - 1]);
$this->SHPData['numparts'] = count($this->SHPData['parts']);
--$this->SHPData['numpoints'];
}
break;
case 8:
case 18:
case 28:
//Deletes the point, if exists
if (isset($this->SHPData['points'][$pointIndex])) {
$count = count($this->SHPData['points']) - 1;
for ($i = $pointIndex; $i < $count; ++$i) {
$this->SHPData['points'][$i] = $this->SHPData['points'][$i + 1];
}
unset($this->SHPData['points'][count($this->SHPData['points']) - 1]);
--$this->SHPData['numpoints'];
}
break;
default:
$this->setError(sprintf('The Shape Type "%s" is not supported.', $this->shapeType));
break;
}
}
/**
* Returns length of content.
*
* @return int
*/
public function getContentLength()
{
// The content length for a record is the length of the record contents section measured in 16-bit words.
// one coordinate makes 4 16-bit words (64 bit double)
switch ($this->shapeType) {
case 0:
$result = 0;
break;
case 1:
$result = 10;
break;
case 21:
$result = 10 + 4;
break;
case 11:
$result = 10 + 8;
break;
case 3:
case 5:
$count = count($this->SHPData['parts']);
$result = 22 + 2 * $count;
for ($i = 0; $i < $count; ++$i) {
$result += 8 * count($this->SHPData['parts'][$i]['points']);
}
break;
case 23:
case 25:
$count = count($this->SHPData['parts']);
$result = 22 + (2 * 4) + 2 * $count;
for ($i = 0; $i < $count; ++$i) {
$result += (8 + 4) * count($this->SHPData['parts'][$i]['points']);
}
break;
case 13:
case 15:
$count = count($this->SHPData['parts']);
$result = 22 + (4 * 4) + 2 * $count;
for ($i = 0; $i < $count; ++$i) {
$result += (8 + 8) * count($this->SHPData['parts'][$i]['points']);
}
break;
case 8:
$result = 20 + 8 * count($this->SHPData['points']);
break;
case 28:
$result = 20 + (2 * 4) + (8 + 4) * count($this->SHPData['points']);
break;
case 18:
$result = 20 + (4 * 4) + (8 + 8) * count($this->SHPData['points']);
break;
default:
$result = false;
$this->setError(sprintf('The Shape Type "%s" is not supported.', $this->shapeType));
break;
}
return $result;
}
private function _loadDBFData()
{
$this->DBFData = @dbase_get_record_with_names($this->DBFFile, $this->recordNumber);
unset($this->DBFData['deleted']);
}
private function _saveDBFData()
{
if (count($this->DBFData) == 0) {
return;
}
unset($this->DBFData['deleted']);
if ($this->recordNumber <= dbase_numrecords($this->DBFFile)) {
if (!dbase_replace_record($this->DBFFile, array_values($this->DBFData), $this->recordNumber)) {
$this->setError('I wasn\'t possible to update the information in the DBF file.');
}
} else {
if (!dbase_add_record($this->DBFFile, array_values($this->DBFData))) {
$this->setError('I wasn\'t possible to add the information to the DBF file.');
}
}
}
/**
* Sets error message.
*
* @param string $error
*/
public function setError($error)
{
$this->lastError = $error;
}
/**
* Returns shape name.
*
* @return string
*/
public function getShapeName()
{
return Util::nameShape($this->shapeType);
}
}

View file

@ -0,0 +1,118 @@
<?php
/**
* phpMyAdmin ShapeFile library
* <https://github.com/phpmyadmin/shapefile/>.
*
* Copyright 2006-2007 Ovidio <ovidio AT users.sourceforge.net>
* Copyright 2016 - 2017 Michal Čihař <michal@cihar.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, you can download one from
* https://www.gnu.org/copyleft/gpl.html.
*/
namespace PhpMyAdmin\ShapeFile;
class Util
{
private static $little_endian = null;
private static $shape_names = array(
0 => 'Null Shape',
1 => 'Point',
3 => 'PolyLine',
5 => 'Polygon',
8 => 'MultiPoint',
11 => 'PointZ',
13 => 'PolyLineZ',
15 => 'PolygonZ',
18 => 'MultiPointZ',
21 => 'PointM',
23 => 'PolyLineM',
25 => 'PolygonM',
28 => 'MultiPointM',
31 => 'MultiPatch',
);
/**
* Reads data.
*
* @param string $type type for unpack()
* @param string $data Data to process
*
* @return mixed
*/
public static function loadData($type, $data)
{
if ($data === false || strlen($data) == 0) {
return false;
}
$tmp = unpack($type, $data);
return current($tmp);
}
/**
* Changes endianity.
*
* @param string $binValue Binary value
*
* @return string
*/
public static function swap($binValue)
{
$result = $binValue[strlen($binValue) - 1];
for ($i = strlen($binValue) - 2; $i >= 0; --$i) {
$result .= $binValue[$i];
}
return $result;
}
/**
* Encodes double value to correct endianity.
*
* @param float $value Value to pack
*
* @return string
*/
public static function packDouble($value)
{
$bin = pack('d', (float) $value);
if (is_null(self::$little_endian)) {
self::$little_endian = (pack('L', 1) == pack('V', 1));
}
if (self::$little_endian) {
return $bin;
}
return self::swap($bin);
}
/**
* Returns shape name.
*
* @param int $type
*
* @return string
*/
public static function nameShape($type)
{
if (isset(self::$shape_names[$type])) {
return self::$shape_names[$type];
}
return sprintf('Shape %d', $type);
}
}

View file

@ -0,0 +1,458 @@
# Change Log
## [5.4.2] - 2021-02-05
* Added check for quoted symbol to avoid parser error in case of keyword (#317)
* Allow PHP 8
## [5.4.1] - 2020-10-15
* Fix array_key_exists warning when parsing a "DEFAULT FALSE" token (#299)
## [5.4.0] - 2020-10-08
* EXISTS is also a function. (#297)
* Fix lexer to not allow numbers with letters (#300)
* Add support for INVISIBLE keyword (#292)
* Fix the "$" might be a character used in a name (#301)
* Fix use stream_select instead of non-blocking STDIN (#309)
* Add select validation to a create view statement (#310)
## [5.3.1] - 2020-03-20
* Revert some changes with the understanding of ANSI_QUOTES mode and identifiers
* Suggest motranslator 5.0 in README
## [5.3.0] - 2020-03-20
* Stop instanciating an object to check its class name. (#290)
* Replace sscanf by equivalent native PHP functions because sscanf can be disabled for security reasons. (#270)
* Allow phpunit 9
* Allow phpmyadmin/motranslator 5.0
* Fix for php error when "INSERT INTO x SET a = 1" is "INSERT INTO x SET = 1" (#295)
* Fixed lexer fails to detect "*" as a wildcard (#288)
* Fixed ANSI_QUOTES support (#284)
* Fixed parser mistakes with comments (#156)
## [5.2.0] - 2020-01-07
* Fix ALTER TABLE ... PRIMARY/UNIQUE KEY results in error (#267)
* Prevent overwrite of offset in Limit clause by parenthesis (#275)
* Allow SCHEMA to be used in CREATE Database statement (#231)
* Add missing options in SET statement (#255)
* Add support for DROP USER statement (#259)
* Fix php error "undefined index" when replacing a non existing clause (#249)
## [5.1.0] - 2019-11-12
* Fix for PHP deprecations messages about implode for php 7.4+ (#258)
* Parse CHECK keyword on table definition (#264)
* Parse truncate statement (#221)
* Fix wrong parsing of partitions (#265)
## [5.0.0] - 2019-05-09
* Drop support for PHP 5.3, PHP 5.4, PHP 5.5, PHP 5.6, PHP 7.0 and HHVM
* Enable strict mode on PHP files
* Fix redundant whitespaces in build() outputs (#228)
* Fix incorrect error on DEFAULT keyword in ALTER operation (#229)
* Fix incorrect outputs from Query::getClause (#233)
* Add support for reading an SQL file from stdin
* Fix for missing tokenize-query in Composer's vendor/bin/ directory
* Fix for PHP warnings with an incomplete CASE expression (#241)
* Fix for error message with multiple CALL statements (#223)
* Recognize the question mark character as a parameter (#242)
## [4.7.2] - 2021-02-05
- Added check for quoted symbol to avoid parser error in case of keyword (#317)
- Adjust PHP version constraint to not support PHP 8.0 on the 4.7 series (5.x series supports it)
## [4.7.1] - 2020-10-15
* Fix array_key_exists warning when parsing a "DEFAULT FALSE" token (#299)
## [4.7.0] - 2020-10-08
* EXISTS is also a function. (#297)
* Fix lexer to not allow numbers with letters (#300)
* Add support for INVISIBLE keyword (#292)
* Fix the "$" might be a character used in a name (#301)
* Fix use stream_select instead of non-blocking STDIN (#309)
* Add select validation to a create view statement (#310)
## [4.6.1] - 2020-03-20
* Revert some changes with the understanding of ANSI_QUOTES mode and identifiers
* Suggest motranslator 4.0 in README
## [4.6.0] - 2020-03-20
* Stop instanciating an object to check its class name. (#290)
* Replace sscanf by equivalent native PHP functions because sscanf can be disabled for security reasons. (#270)
* Allow phpunit 7
* Fix for php error when "INSERT INTO x SET a = 1" is "INSERT INTO x SET = 1" (#295)
* Fixed lexer fails to detect "*" as a wildcard (#288)
* Fixed ANSI_QUOTES support (#284)
* Fixed parser mistakes with comments (#156)
## [4.5.0] - 2020-01-07
* Fix ALTER TABLE ... PRIMARY/UNIQUE KEY results in error (#267)
* Prevent overwrite of offset in Limit clause by parenthesis (#275)
* Allow SCHEMA to be used in CREATE Database statement (#231)
* Add missing options in SET statement (#255)
* Add support for DROP USER statement (#259)
* Fix php error "undefined index" when replacing a non existing clause (#249)
## [4.4.0] - 2019-11-12
* Fix for PHP deprecations messages about implode for php 7.4+ (#258)
* Parse CHECK keyword on table definition (#264)
* Parse truncate statement (#221)
* Fix wrong parsing of partitions (#265)
## [4.3.2] - 2019-06-03
Backport fixes from 5.0.0 to QA branch:
* Fix redundant whitespaces in build() outputs (#228)
* Fix incorrect error on DEFAULT keyword in ALTER operation (#229)
* Fix incorrect outputs from Query::getClause (#233)
* Add support for reading an SQL file from stdin
* Fix for missing tokenize-query in Composer's vendor/bin/ directory
* Fix for PHP warnings with an incomplete CASE expression (#241)
* Fix for error message with multiple CALL statements (#223)
* Recognize the question mark character as a parameter (#242)
## [4.3.1] - 2019-01-05
* Fixed incorrect error thrown on DEFAULT keyword in ALTER statement (#218)
## [4.3.0] - 2018-12-25
* Add support for aliases on CASE expressions (#162 and #192)
* Add support for INDEX hints in SELECT statement (#199)
* Add support for LOCK and UNLOCK TABLES statement (#180)
* Add detection of extraneous comma in UPDATE statement (#160)
* Add detection of a missing comma between two ALTER operations (#189)
* Add missing support for STRAIGHT_JOIN (#196)
* Add support for end options in SET statement (#190)
* Fix building of RENAME statements (#201)
* Add support for PURGE statements (#207)
* Add support for COLLATE keyword (#190)
## [4.2.5] - 2018-10-31
* Fix issue with CREATE OR REPLACE VIEW.
## [4.2.4] - 2017-12-06
* Fix parsing of CREATE TABLE with per field COLLATE.
* Improved Context::loadClosest to better deal with corner cases.
* Localization updates.
## [4.2.3] - 2017-10-10
* Make mbstring extension optional (though Symfony polyfill).
* Fixed build CREATE TABLE query with PARTITIONS having ENGINE but not VALUES.
## [4.2.2] - 2017-09-28
* Added support for binding parameters.
## [4.2.1] - 2017-09-08
* Fixed minor bug in Query::getFlags.
* Localization updates.
## [4.2.0] - 2017-08-30
* Initial support for MariaDB SQL contexts.
* Add support for MariaDB 10.3 INTERSECT and EXCEPT.
## [4.1.10] - 2017-08-21
* Use custom LoaderException for context loading errors.
## [4.1.9] - 2017-07-12
* Various code cleanups.
* Improved error handling of several invalid statements.
## [4.1.8] - 2017-07-09
* Fixed parsing SQL comment at the end of query.
* Improved handing of non utf-8 strings.
* Added query flag for SET queries.
## [4.1.7] - 2017-06-06
* Fixed setting combination SQL Modes.
## [4.1.6] - 2017-06-01
* Fixed building query with GROUP BY clause.
## [4.1.5] - 2017-05-15
* Fixed invalid lexing of queries with : in strings.
* Properly handle maximal length of delimiter.
## [4.1.4] - 2017-05-05
* Fixed wrong extract of string tokens with escaped characters.
* Properly handle lowercase begin statement.
## [4.1.3] - 2017-04-06
* Added support for DELETE ... JOIN clauses.
* Changed BufferedQuery to include comments in output.
* Fixed parsing of inline comments.
## [4.1.2] - 2017-02-20
* Coding style improvements.
* Chinese localization.
* Improved order validatin for JOIN clauses.
* Improved pretty printing of JOIN clauses.
* Added support for LOAD DATA statements.
## [4.1.1] - 2017-02-07
* Localization using phpmyadmin/motranslator is now optional.
* Improved testsuite.
* Better handling of non upper cased not reserved keywords.
* Minor performance and coding style improvements.
## [4.1.0] - 2017-01-23
* Use phpmyadmin/motranslator to localize messages.
## [4.0.1] - 2017-01-23
* Fixed CLI wrappers for new API.
* Fixed README for new API.
## [4.0.0] - 2017-01-23
* Added PhpMyAdmin namespace prefix to follow PSR-4.
## [3.4.17] - 2017-01-20
* Coding style fixes.
* Fixed indentation in HTML formatting.
* Fixed parsing of unterminated variables.
* Improved comments lexing.
## [3.4.16] - 2017-01-06
* Coding style fixes.
* Properly handle operators AND, NOT, OR, XOR, DIV, MOD
## [3.4.15] - 2017-01-02
* Fix return value of Formatter.toString() when type is text
* Fix parsing of FIELDS and LINES options in SELECT..INTO
* PHP 7.2 compatibility.
* Better parameter passing to query formatter.
## [3.4.14] - 2016-11-30
* Improved parsing of UNION queries.
* Recognize BINARY function.
## [3.4.13] - 2016-11-15
* Fix broken incorrect clause order detection for Joins.
* Add parsing of end options in Select statements.
## [3.4.12] - 2016-11-09
* Added verification order of SELECT statement clauses.
## [3.4.11] - 2016-10-25
* Fixed parsing of ON UPDATE option in field definition of TIMESTAMP type with precision
* Fixed parsing of NATURAL JOIN, CROSS JOIN and related joins.
* Fixed parsing of BEGIN/END labels.
## [3.4.10] - 2016-10-03
* Fixed API regression on DELETE statement
## [3.4.9] - 2016-10-03
* Added support for CASE expressions
* Support for parsing and building DELETE statement
* Support for parsing subqueries in FROM clause
## [3.4.8] - 2016-09-22
* No change release to sync GitHub releases with Packagist
## [3.4.7] - 2016-09-20
* Fix parsing of DEFINER without backquotes
* Fixed escaping HTML entities in HTML formatter
* Fixed escaping of control chars in CLI formatter
## [3.4.6] - 2016-09-13
* Fix parsing of REPLACE INTO ...
* Fix parsing of INSERT ... ON DUPLICATE KEY UPDATE ...
* Extended testsuite
* Re-enabled PHP 5.3 support
## [3.4.5] - 2016-09-13
* Fix parsing of INSERT...SELECT and INSERT...SET syntax
* Fix parsing of CREATE TABLE ... PARTITION
* Fix parsing of SET CHARACTER SET, CHARSET, NAMES
* Add Support for 'CREATE TABLE `table_copy` LIKE `table`
## [3.4.4] - 2016-04-26
* Add support for FULL OUTER JOIN
## [3.4.3] - 2016-04-19
* Fix parsing of query with \
## [3.4.2] - 2016-04-07
* Recognize UNION DISTINCT
* Recognize REGEXP and RLIKE operators
## [3.4.1] - 2016-04-06
* Add FULLTEXT and SPATIAL keywords
* Properly parse CREATE TABLE [AS] SELECT
* Fix parsing of table with DEFAULT and COMMENT
## [3.4.0] - 2016-02-23
* Fix parsing DEFAULT value on CREATE
* Fix parsing of ALTER VIEW
## [3.3.1] - 2016-02-12
* Condition: Allow keyword `INTERVAL`.
## [3.3.0] - 2016-02-12
* Expression: Refactored parsing options.
## [3.2.0] - 2016-02-11
* Context: Added custom mode that avoids escaping when possible.
## [3.1.0] - 2016-02-10
* ArrayObj: Handle more complex expressions in arrays.
* BufferedQuery: Backslashes in comments escaped characters in comments.
* Condition: Allow `IF` in conditions.
* Context: Add `;` as operator.
* Context: Updated contexts to contain `BIT` data type.
* CreateStatement: The `DEFAULT` option may be an expression.
* DescribeStatement: Added `DESC` as alias for `DESCRIBE`.
* Expression: Rewrote expression parsing.
* Misc: Added PHPUnit's Code Coverage 3.0 as a dependency.
* Misc: Added support for PHP 5.4 back.
* Misc: Removed dependency to Ctype.
* Misc: Repository transferred from @udan11 to @phpMyAdmin.
* Misc: Updated `.gitignore` to ignore `composer.lock`.
* Misc: Updated Composer and Travis configuration for PHP 7 and PHPUnit 5.
* Tools: Documented tags in `ContextGenerator`.
## [3.0.8] - 2015-12-18
* Allow `NULL` in expressions.
* Downgraded PHPUnit to 4.8. Removed old PHP versions.
* Updated PHPUnit to 5.1 and fixed some of the tests.
* Added `UNION ALL` as a type of `UNION`.
* Expressions are permitted in `SET` operations.
* Added `STRAIGHT_JOIN` as a known type of join.
* Added missing definitions for `MATCH` and `AGAINST`.
* Added missing statement (`FLUSH` and `DEALLOCATE`).
## [3.0.7] - 2015-11-12
* Expressions may begin with a function that is also a reserved keyword (e.g. `IF`).
## [3.0.6] - 2015-11-12
* Fixed a bug where formatter split the function name and the parameters list.
## [3.0.5] - 2015-11-08
* Add GRANT as known statement.
* Use JOIN expressions for flag detection.
* Fix the order of clauses in SELECT statements involving UNIONs.
* Added dummy parsers for CREATE USER and SET PASSWORD statements.
* Accept NOT operator in conditions.
* Fixed DELIMITER statements in BufferedQuery.
* Added INSERT statement builder.
## [3.0.4] - 2015-10-21
* Fix error message in `SqlParser\Components\OptionsArray`.
## [3.0.3] - 2015-10-10
* Avoid building a field multiple times if clause has synonyms.
## [3.0.2] - 2015-10-10
* Add EXISTS as an acceptable keyword in conditions.
## [3.0.1] - 2015-10-06
* Handle backslashes separately for `SqlParser\Utils\BufferedQuery`. Fixes a bug where backslashes in combination with strings weren't handled properly.
## [3.0.0] - 2015-10-02
__Breaking changes:__
* `SqlParser\Components\Reference::$table` is now an instance of `SqlParser\Components\Expression` to support references from other tables.
## [2.1.3] - 2015-10-02
* Add definitions for all JOIN clauses.
## [2.1.2] - 2015-10-02
* Properly parse options when the value of the option is '='.
## [2.1.1] - 2015-09-30
* Only RANGE and LIST type partitions support VALUES.
## [2.1.0] - 2015-09-30
* Added utilities for handling tokens and tokens list.
## [2.0.3] - 2015-09-30
* Added missing NOT IN operator. This caused troubles when parsing conditions that contained the `NOT IN` operator.
## [2.0.2] - 2015-09-30
* Added support for `OUTER` as an optional keyword in joins.
## [2.0.1] - 2015-09-30
* Fixed a bug related to (sub)partitions options not being included in the built component. Also, the option `ENGINE` was unrecognized.
## [2.0.0] - 2015-09-25
* Better parsing for CREATE TABLE statements (related to breaking change 1).
* Added support for JSON data type.
* Refactoring and minor documentation improvements.
__Breaking changes:__
* `SqlParser\Components\Key::$columns` is now an array of arrays. Each array must contain a `name` key which represents the name of the column and an optional `length` key which represents the length of the column.
## [1.0.0] - 2015-08-20
* First release of this library.

View file

@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

View file

@ -0,0 +1,135 @@
# SQL Parser
A validating SQL lexer and parser with a focus on MySQL dialect.
## Code status
![Tests](https://github.com/phpmyadmin/sql-parser/workflows/Run%20tests/badge.svg?branch=master)
[![Code Coverage](https://scrutinizer-ci.com/g/phpmyadmin/sql-parser/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/phpmyadmin/sql-parser/?branch=master)
[![codecov.io](https://codecov.io/github/phpmyadmin/sql-parser/coverage.svg?branch=master)](https://codecov.io/github/phpmyadmin/sql-parser?branch=master)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/phpmyadmin/sql-parser/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/phpmyadmin/sql-parser/?branch=master)
[![Translation status](https://hosted.weblate.org/widgets/phpmyadmin/-/svg-badge.svg)](https://hosted.weblate.org/engage/phpmyadmin/?utm_source=widget)
[![Packagist](https://img.shields.io/packagist/dt/phpmyadmin/sql-parser.svg)](https://packagist.org/packages/phpmyadmin/sql-parser)
[![Open Source Helpers](https://www.codetriage.com/phpmyadmin/sql-parser/badges/users.svg)](https://www.codetriage.com/phpmyadmin/sql-parser)
## Installation
Please use [Composer][1] to install:
```sh
composer require phpmyadmin/sql-parser
```
## Documentation
The API documentation is available at
<https://develdocs.phpmyadmin.net/sql-parser/>.
## Usage
### Command line utilities
Command line utility to syntax highlight SQL query:
```sh
./vendor/bin/highlight-query --query "SELECT 1"
```
Command line utility to lint SQL query:
```sh
./vendor/bin/lint-query --query "SELECT 1"
```
Command line utility to tokenize SQL query:
```sh
./vendor/bin/tokenize-query --query "SELECT 1"
```
All commands are able to parse input from stdin (standard in), such as:
```sh
echo "SELECT 1" | ./vendor/bin/highlight-query
cat example.sql | ./vendor/bin/lint-query
```
### Formatting SQL query
```php
echo PhpMyAdmin\SqlParser\Utils\Formatter::format($query, ['type' => 'html']);
```
### Discoverying query type
```php
use PhpMyAdmin\SqlParser\Parser;
use PhpMyAdmin\SqlParser\Utils\Query;
$query = 'OPTIMIZE TABLE tbl';
$parser = new Parser($query);
$flags = Query::getFlags($parser->statements[0]);
echo $flags['querytype'];
```
### Parsing and building SQL query
```php
require __DIR__ . '/vendor/autoload.php';
$query1 = 'select * from a';
$parser = new PhpMyAdmin\SqlParser\Parser($query1);
// inspect query
var_dump($parser->statements[0]); // outputs object(PhpMyAdmin\SqlParser\Statements\SelectStatement)
// modify query by replacing table a with table b
$table2 = new \PhpMyAdmin\SqlParser\Components\Expression('', 'b', '', '');
$parser->statements[0]->from[0] = $table2;
// build query again from an array of object(PhpMyAdmin\SqlParser\Statements\SelectStatement) to a string
$statement = $parser->statements[0];
$query2 = $statement->build();
var_dump($query2); // outputs string(19) 'SELECT * FROM `b` '
// Change SQL mode
PhpMyAdmin\SqlParser\Context::setMode('ANSI_QUOTES');
// build the query again using different quotes
$query2 = $statement->build();
var_dump($query2); // outputs string(19) 'SELECT * FROM "b" '
```
## Localization
You can localize error messages installing `phpmyadmin/motranslator` version `5.0` or newer:
```sh
composer require phpmyadmin/motranslator:^5.0
```
The locale is automatically detected from your environment, you can also set a different locale
**From cli**:
```sh
LC_ALL=pl ./vendor/bin/lint-query --query "SELECT 1"
```
**From php**:
```php
require __DIR__ . '/vendor/autoload.php';
$GLOBALS['lang'] = 'pl';
$query1 = 'select * from a';
$parser = new PhpMyAdmin\SqlParser\Parser($query1);
```
## More information
This library was originally created during the Google Summer of Code 2015 and has been used by phpMyAdmin since version 4.5.
[1]:https://getcomposer.org/

View file

@ -0,0 +1,56 @@
{
"name": "phpmyadmin/sql-parser",
"description": "A validating SQL lexer and parser with a focus on MySQL dialect.",
"license": "GPL-2.0-or-later",
"keywords": ["sql", "lexer", "parser", "analysis"],
"homepage": "https://github.com/phpmyadmin/sql-parser",
"authors": [
{
"name": "The phpMyAdmin Team",
"email": "developers@phpmyadmin.net",
"homepage": "https://www.phpmyadmin.net/team/"
}
],
"support": {
"issues": "https://github.com/phpmyadmin/sql-parser/issues",
"source": "https://github.com/phpmyadmin/sql-parser"
},
"require": {
"php": "^7.1 || ^8.0",
"symfony/polyfill-mbstring": "^1.3"
},
"require-dev": {
"phpmyadmin/coding-standard": "^2.1.1",
"phpmyadmin/motranslator": "^4.0 || ^5.0",
"phpstan/extension-installer": "^1.0",
"phpstan/phpstan": "^0.12.54",
"phpstan/phpstan-phpunit": "^0.12.16",
"phpunit/php-code-coverage": "*",
"phpunit/phpunit": "^7.4 || ^8 || ^9"
},
"conflict": {
"phpmyadmin/motranslator": "<3.0"
},
"suggest": {
"ext-mbstring": "For best performance",
"phpmyadmin/motranslator": "Translate messages to your favorite locale"
},
"bin": [
"bin/highlight-query",
"bin/lint-query",
"bin/tokenize-query"
],
"autoload": {
"psr-4": {
"PhpMyAdmin\\SqlParser\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"PhpMyAdmin\\SqlParser\\Tests\\": "tests"
}
},
"config":{
"sort-packages": true
}
}

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