├── CHANGELOG.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── composer.json
├── data
├── Czech_Republic_AL2.dbf
├── Czech_Republic_AL2.prj
├── Czech_Republic_AL2.shp
├── Czech_Republic_AL2.shx
├── bc_hospitals.dbf
├── bc_hospitals.prj
├── bc_hospitals.qix
├── bc_hospitals.shp
├── bc_hospitals.shx
├── capitals.dbf
├── capitals.shp
├── capitals.shx
├── invalid-dbf.dbf
├── invalid-dbf.shp
├── invalid-dbf.shx
├── invalid-shp.shp
├── mexico.dbf
├── mexico.shp
├── mexico.shx
├── multipoint.dbf
├── multipoint.prj
├── multipoint.shp
├── multipoint.shx
├── no-dbf.shp
├── no-dbf.shx
├── no-shp.dbf
├── no-shp.shx
├── w001n05f.dbf
├── w001n05f.shp
└── w001n05f.shx
├── examples
├── create_shapefile.php
├── index.php
├── read.php
├── read_point.php
└── read_polygon.php
├── phpunit.xml.dist
├── src
├── ShapeFile.php
├── ShapeRecord.php
├── ShapeType.php
└── Util.php
└── tests
├── ShapeFileTest.php
└── UtilTest.php
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 | All notable changes to this project will be documented in this file.
3 |
4 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
5 |
6 | ## [Unreleased]
7 | ### Removed
8 | - Drop support for PHP 7.1, PHP 7.2, PHP 7.3, PHP 7.4, PHP 8.0 and PHP 8.1
9 |
10 | ## [3.1.0] - YYYY-MM-DD
11 |
12 | ### Added
13 |
14 | - Adds a toggle to allow shape files with no dbf (#41)
15 |
16 | ## [3.0.2] - 2023-09-11
17 | ### Added
18 | - Support for PHP 8.3
19 | - Support for PHPUnit 10
20 |
21 | ## [3.0.1] - 2021-02-05
22 | ### Fixed
23 | - Fix method signature of ShapeFile::getDBFHeader()
24 |
25 | ## [3.0.0] - 2021-02-05
26 | ### Added
27 | - Support for PHPUnit 8 and 9
28 | - Support PHP 8
29 |
30 | ### Changed
31 | - Enable strict mode on PHP files
32 | - Rename ShapeFile::$FileName property to ShapeFile::$fileName
33 | - Rename ShapeRecord::$SHPData property to ShapeRecord::$shpData
34 | - Rename ShapeRecord::$DBFData property to ShapeRecord::$dbfData
35 | - ShapeRecord::getContentLength returns `null` when the shape type is not supported instead of `false`.
36 |
37 | ### Removed
38 | - Drop support for PHP 5.4, PHP 5.5, PHP 5.6, PHP 7.0 and HHVM
39 |
40 | ## [2.1] - 2017-05-15
41 | ### Changed
42 | - Documentation improvements.
43 |
44 | ## [2.0] - 2017-01-23
45 | ### Changed
46 | - Switched to PhpMyAdmin vendor namespace to follow PSR-4.
47 |
48 | ## [1.2] - 2017-01-07
49 | ### Added
50 | - PHP 7.2 support.
51 |
52 | ### Changed
53 | - Coding style cleanup.
54 | - Avoid installing tests and test data using composer.
55 |
56 | ## [1.1] - 2016-11-21
57 | ### Fixed
58 | - Fixed adjusting of record bounding box
59 |
60 | ## [1.0] - 2016-11-21
61 | ### Changed
62 | - Documentation improvements
63 | - Code cleanups
64 |
65 | ## [0.13] - 2016-11-21
66 | ### Changed
67 | - Code cleanups
68 | - Improved test coverage
69 |
70 | ## [0.12] - 2016-11-17
71 | ### Changed
72 | - Improved test coverage
73 |
74 | ### Fixed
75 | - Fixed DBF search
76 |
77 | ## [0.11] - 2016-11-16
78 | ### Changed
79 | - Code cleanups
80 |
81 | ### Fixed
82 | - Fixed behavior without configured DBF header
83 | - Fixed saving Polygon/Polyline creation with multiple parts
84 | - Fixed saving Multipoint records
85 |
86 | ## [0.10] - 2016-09-05
87 | ### Changed
88 | - Improved error handling on loading
89 |
90 | ## [0.9] - 2016-08-04
91 | ### Changed
92 | - Code cleanups
93 |
94 | ## [0.8] - 2016-06-24
95 | ### Changed
96 | - Code cleanups
97 |
98 | ### Fixed
99 | - Fixed loading of records with optional data
100 |
101 | ## [0.7] - 2016-06-24
102 | ### Fixed
103 | - Properly fail on loading corrupted files
104 |
105 | ## [0.6] - 2016-06-24
106 | ### Fixed
107 | - Fixed detection of end of file when loading
108 |
109 | ## [0.5] - 2016-06-24
110 | ### Added
111 | - Added getShapeName method to ShapeFile
112 |
113 | ## [0.4] - 2016-06-24
114 | ### Changed
115 | - Make API work even without real file open
116 |
117 | ## [0.3] - 2016-06-24
118 | ### Added
119 | - Better support for subclassing
120 |
121 | ## [0.2] - 2016-06-24
122 | ### Changed
123 | - Make the dbase extension optional dependency
124 |
125 | ## 0.1 - 2016-06-14
126 | ### Added
127 | - Initial release based on bfShapeFiles
128 |
129 | [Unreleased]: https://github.com/phpmyadmin/shapefile/compare/3.0.2...HEAD
130 | [3.1.0]: https://github.com/phpmyadmin/shapefile/compare/3.0.2...3.1.x
131 | [3.0.2]: https://github.com/phpmyadmin/shapefile/compare/3.0.1...3.0.2
132 | [3.0.1]: https://github.com/phpmyadmin/shapefile/compare/3.0.0...3.0.1
133 | [3.0.0]: https://github.com/phpmyadmin/shapefile/compare/2.1...3.0.0
134 | [2.1]: https://github.com/phpmyadmin/shapefile/compare/2.0...2.1
135 | [2.0]: https://github.com/phpmyadmin/shapefile/compare/1.2...2.0
136 | [1.2]: https://github.com/phpmyadmin/shapefile/compare/1.1...1.2
137 | [1.1]: https://github.com/phpmyadmin/shapefile/compare/1.0...1.1
138 | [1.0]: https://github.com/phpmyadmin/shapefile/compare/0.13...1.0
139 | [0.13]: https://github.com/phpmyadmin/shapefile/compare/0.12...0.13
140 | [0.12]: https://github.com/phpmyadmin/shapefile/compare/0.11...0.12
141 | [0.11]: https://github.com/phpmyadmin/shapefile/compare/0.10...0.11
142 | [0.10]: https://github.com/phpmyadmin/shapefile/compare/0.9...0.10
143 | [0.9]: https://github.com/phpmyadmin/shapefile/compare/0.8...0.9
144 | [0.8]: https://github.com/phpmyadmin/shapefile/compare/0.7...0.8
145 | [0.7]: https://github.com/phpmyadmin/shapefile/compare/0.6...0.7
146 | [0.6]: https://github.com/phpmyadmin/shapefile/compare/0.5...0.6
147 | [0.5]: https://github.com/phpmyadmin/shapefile/compare/0.4...0.5
148 | [0.4]: https://github.com/phpmyadmin/shapefile/compare/0.3...0.4
149 | [0.3]: https://github.com/phpmyadmin/shapefile/compare/0.2...0.3
150 | [0.2]: https://github.com/phpmyadmin/shapefile/compare/0.1...0.2
151 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing to shapefile
2 |
3 | ## Reporting issues
4 |
5 | Our issue tracker is hosted at GitHub:
6 |
7 | https://github.com/phpmyadmin/shapefile/issues
8 |
9 | Please search for existing issues before reporting new ones.
10 |
11 | ## Working with Git checkout
12 |
13 | The dependencies are managed by Composer, to get them all installed (or update
14 | on consequent runs) do:
15 |
16 | ```
17 | composer update
18 | ```
19 |
20 | ## Submitting patches
21 |
22 | Please submit your patches using GitHub pull requests, this allows us to review
23 | them and to run automated tests on the code.
24 |
25 | ## Coding standards
26 |
27 | We do follow PSR-1 and PSR-2 coding standards.
28 |
29 | You can use phpcbf to fix the code to match our expectations:
30 |
31 | ```
32 | composer run phpcbf
33 | ```
34 |
35 | ## Testsuite
36 |
37 | Our code comes with quite comprehensive testsuite, it is automatically executed
38 | on every commit and pull request, you can also run it locally:
39 |
40 | ```
41 | composer run phpunit
42 | ```
43 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 2, June 1991
3 |
4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | Preamble
10 |
11 | The licenses for most software are designed to take away your
12 | freedom to share and change it. By contrast, the GNU General Public
13 | License is intended to guarantee your freedom to share and change free
14 | software--to make sure the software is free for all its users. This
15 | General Public License applies to most of the Free Software
16 | Foundation's software and to any other program whose authors commit to
17 | using it. (Some other Free Software Foundation software is covered by
18 | the GNU Lesser General Public License instead.) You can apply it to
19 | your programs, too.
20 |
21 | When we speak of free software, we are referring to freedom, not
22 | price. Our General Public Licenses are designed to make sure that you
23 | have the freedom to distribute copies of free software (and charge for
24 | this service if you wish), that you receive source code or can get it
25 | if you want it, that you can change the software or use pieces of it
26 | in new free programs; and that you know you can do these things.
27 |
28 | To protect your rights, we need to make restrictions that forbid
29 | anyone to deny you these rights or to ask you to surrender the rights.
30 | These restrictions translate to certain responsibilities for you if you
31 | distribute copies of the software, or if you modify it.
32 |
33 | For example, if you distribute copies of such a program, whether
34 | gratis or for a fee, you must give the recipients all the rights that
35 | you have. You must make sure that they, too, receive or can get the
36 | source code. And you must show them these terms so they know their
37 | rights.
38 |
39 | We protect your rights with two steps: (1) copyright the software, and
40 | (2) offer you this license which gives you legal permission to copy,
41 | distribute and/or modify the software.
42 |
43 | Also, for each author's protection and ours, we want to make certain
44 | that everyone understands that there is no warranty for this free
45 | software. If the software is modified by someone else and passed on, we
46 | want its recipients to know that what they have is not the original, so
47 | that any problems introduced by others will not reflect on the original
48 | authors' reputations.
49 |
50 | Finally, any free program is threatened constantly by software
51 | patents. We wish to avoid the danger that redistributors of a free
52 | program will individually obtain patent licenses, in effect making the
53 | program proprietary. To prevent this, we have made it clear that any
54 | patent must be licensed for everyone's free use or not licensed at all.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | GNU GENERAL PUBLIC LICENSE
60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61 |
62 | 0. This License applies to any program or other work which contains
63 | a notice placed by the copyright holder saying it may be distributed
64 | under the terms of this General Public License. The "Program", below,
65 | refers to any such program or work, and a "work based on the Program"
66 | means either the Program or any derivative work under copyright law:
67 | that is to say, a work containing the Program or a portion of it,
68 | either verbatim or with modifications and/or translated into another
69 | language. (Hereinafter, translation is included without limitation in
70 | the term "modification".) Each licensee is addressed as "you".
71 |
72 | Activities other than copying, distribution and modification are not
73 | covered by this License; they are outside its scope. The act of
74 | running the Program is not restricted, and the output from the Program
75 | is covered only if its contents constitute a work based on the
76 | Program (independent of having been made by running the Program).
77 | Whether that is true depends on what the Program does.
78 |
79 | 1. You may copy and distribute verbatim copies of the Program's
80 | source code as you receive it, in any medium, provided that you
81 | conspicuously and appropriately publish on each copy an appropriate
82 | copyright notice and disclaimer of warranty; keep intact all the
83 | notices that refer to this License and to the absence of any warranty;
84 | and give any other recipients of the Program a copy of this License
85 | along with the Program.
86 |
87 | You may charge a fee for the physical act of transferring a copy, and
88 | you may at your option offer warranty protection in exchange for a fee.
89 |
90 | 2. You may modify your copy or copies of the Program or any portion
91 | of it, thus forming a work based on the Program, and copy and
92 | distribute such modifications or work under the terms of Section 1
93 | above, provided that you also meet all of these conditions:
94 |
95 | a) You must cause the modified files to carry prominent notices
96 | stating that you changed the files and the date of any change.
97 |
98 | b) You must cause any work that you distribute or publish, that in
99 | whole or in part contains or is derived from the Program or any
100 | part thereof, to be licensed as a whole at no charge to all third
101 | parties under the terms of this License.
102 |
103 | c) If the modified program normally reads commands interactively
104 | when run, you must cause it, when started running for such
105 | interactive use in the most ordinary way, to print or display an
106 | announcement including an appropriate copyright notice and a
107 | notice that there is no warranty (or else, saying that you provide
108 | a warranty) and that users may redistribute the program under
109 | these conditions, and telling the user how to view a copy of this
110 | License. (Exception: if the Program itself is interactive but
111 | does not normally print such an announcement, your work based on
112 | the Program is not required to print an announcement.)
113 |
114 | These requirements apply to the modified work as a whole. If
115 | identifiable sections of that work are not derived from the Program,
116 | and can be reasonably considered independent and separate works in
117 | themselves, then this License, and its terms, do not apply to those
118 | sections when you distribute them as separate works. But when you
119 | distribute the same sections as part of a whole which is a work based
120 | on the Program, the distribution of the whole must be on the terms of
121 | this License, whose permissions for other licensees extend to the
122 | entire whole, and thus to each and every part regardless of who wrote it.
123 |
124 | Thus, it is not the intent of this section to claim rights or contest
125 | your rights to work written entirely by you; rather, the intent is to
126 | exercise the right to control the distribution of derivative or
127 | collective works based on the Program.
128 |
129 | In addition, mere aggregation of another work not based on the Program
130 | with the Program (or with a work based on the Program) on a volume of
131 | a storage or distribution medium does not bring the other work under
132 | the scope of this License.
133 |
134 | 3. You may copy and distribute the Program (or a work based on it,
135 | under Section 2) in object code or executable form under the terms of
136 | Sections 1 and 2 above provided that you also do one of the following:
137 |
138 | a) Accompany it with the complete corresponding machine-readable
139 | source code, which must be distributed under the terms of Sections
140 | 1 and 2 above on a medium customarily used for software interchange; or,
141 |
142 | b) Accompany it with a written offer, valid for at least three
143 | years, to give any third party, for a charge no more than your
144 | cost of physically performing source distribution, a complete
145 | machine-readable copy of the corresponding source code, to be
146 | distributed under the terms of Sections 1 and 2 above on a medium
147 | customarily used for software interchange; or,
148 |
149 | c) Accompany it with the information you received as to the offer
150 | to distribute corresponding source code. (This alternative is
151 | allowed only for noncommercial distribution and only if you
152 | received the program in object code or executable form with such
153 | an offer, in accord with Subsection b above.)
154 |
155 | The source code for a work means the preferred form of the work for
156 | making modifications to it. For an executable work, complete source
157 | code means all the source code for all modules it contains, plus any
158 | associated interface definition files, plus the scripts used to
159 | control compilation and installation of the executable. However, as a
160 | special exception, the source code distributed need not include
161 | anything that is normally distributed (in either source or binary
162 | form) with the major components (compiler, kernel, and so on) of the
163 | operating system on which the executable runs, unless that component
164 | itself accompanies the executable.
165 |
166 | If distribution of executable or object code is made by offering
167 | access to copy from a designated place, then offering equivalent
168 | access to copy the source code from the same place counts as
169 | distribution of the source code, even though third parties are not
170 | compelled to copy the source along with the object code.
171 |
172 | 4. You may not copy, modify, sublicense, or distribute the Program
173 | except as expressly provided under this License. Any attempt
174 | otherwise to copy, modify, sublicense or distribute the Program is
175 | void, and will automatically terminate your rights under this License.
176 | However, parties who have received copies, or rights, from you under
177 | this License will not have their licenses terminated so long as such
178 | parties remain in full compliance.
179 |
180 | 5. You are not required to accept this License, since you have not
181 | signed it. However, nothing else grants you permission to modify or
182 | distribute the Program or its derivative works. These actions are
183 | prohibited by law if you do not accept this License. Therefore, by
184 | modifying or distributing the Program (or any work based on the
185 | Program), you indicate your acceptance of this License to do so, and
186 | all its terms and conditions for copying, distributing or modifying
187 | the Program or works based on it.
188 |
189 | 6. Each time you redistribute the Program (or any work based on the
190 | Program), the recipient automatically receives a license from the
191 | original licensor to copy, distribute or modify the Program subject to
192 | these terms and conditions. You may not impose any further
193 | restrictions on the recipients' exercise of the rights granted herein.
194 | You are not responsible for enforcing compliance by third parties to
195 | this License.
196 |
197 | 7. If, as a consequence of a court judgment or allegation of patent
198 | infringement or for any other reason (not limited to patent issues),
199 | conditions are imposed on you (whether by court order, agreement or
200 | otherwise) that contradict the conditions of this License, they do not
201 | excuse you from the conditions of this License. If you cannot
202 | distribute so as to satisfy simultaneously your obligations under this
203 | License and any other pertinent obligations, then as a consequence you
204 | may not distribute the Program at all. For example, if a patent
205 | license would not permit royalty-free redistribution of the Program by
206 | all those who receive copies directly or indirectly through you, then
207 | the only way you could satisfy both it and this License would be to
208 | refrain entirely from distribution of the Program.
209 |
210 | If any portion of this section is held invalid or unenforceable under
211 | any particular circumstance, the balance of the section is intended to
212 | apply and the section as a whole is intended to apply in other
213 | circumstances.
214 |
215 | It is not the purpose of this section to induce you to infringe any
216 | patents or other property right claims or to contest validity of any
217 | such claims; this section has the sole purpose of protecting the
218 | integrity of the free software distribution system, which is
219 | implemented by public license practices. Many people have made
220 | generous contributions to the wide range of software distributed
221 | through that system in reliance on consistent application of that
222 | system; it is up to the author/donor to decide if he or she is willing
223 | to distribute software through any other system and a licensee cannot
224 | impose that choice.
225 |
226 | This section is intended to make thoroughly clear what is believed to
227 | be a consequence of the rest of this License.
228 |
229 | 8. If the distribution and/or use of the Program is restricted in
230 | certain countries either by patents or by copyrighted interfaces, the
231 | original copyright holder who places the Program under this License
232 | may add an explicit geographical distribution limitation excluding
233 | those countries, so that distribution is permitted only in or among
234 | countries not thus excluded. In such case, this License incorporates
235 | the limitation as if written in the body of this License.
236 |
237 | 9. The Free Software Foundation may publish revised and/or new versions
238 | of the General Public License from time to time. Such new versions will
239 | be similar in spirit to the present version, but may differ in detail to
240 | address new problems or concerns.
241 |
242 | Each version is given a distinguishing version number. If the Program
243 | specifies a version number of this License which applies to it and "any
244 | later version", you have the option of following the terms and conditions
245 | either of that version or of any later version published by the Free
246 | Software Foundation. If the Program does not specify a version number of
247 | this License, you may choose any version ever published by the Free Software
248 | Foundation.
249 |
250 | 10. If you wish to incorporate parts of the Program into other free
251 | programs whose distribution conditions are different, write to the author
252 | to ask for permission. For software which is copyrighted by the Free
253 | Software Foundation, write to the Free Software Foundation; we sometimes
254 | make exceptions for this. Our decision will be guided by the two goals
255 | of preserving the free status of all derivatives of our free software and
256 | of promoting the sharing and reuse of software generally.
257 |
258 | NO WARRANTY
259 |
260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 | REPAIR OR CORRECTION.
269 |
270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 | POSSIBILITY OF SUCH DAMAGES.
279 |
280 | END OF TERMS AND CONDITIONS
281 |
282 | How to Apply These Terms to Your New Programs
283 |
284 | If you develop a new program, and you want it to be of the greatest
285 | possible use to the public, the best way to achieve this is to make it
286 | free software which everyone can redistribute and change under these terms.
287 |
288 | To do so, attach the following notices to the program. It is safest
289 | to attach them to the start of each source file to most effectively
290 | convey the exclusion of warranty; and each file should have at least
291 | the "copyright" line and a pointer to where the full notice is found.
292 |
293 | {description}
294 | Copyright (C) {year} {fullname}
295 |
296 | This program is free software; you can redistribute it and/or modify
297 | it under the terms of the GNU General Public License as published by
298 | the Free Software Foundation; either version 2 of the License, or
299 | (at your option) any later version.
300 |
301 | This program is distributed in the hope that it will be useful,
302 | but WITHOUT ANY WARRANTY; without even the implied warranty of
303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 | GNU General Public License for more details.
305 |
306 | You should have received a copy of the GNU General Public License along
307 | with this program; if not, write to the Free Software Foundation, Inc.,
308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309 |
310 | Also add information on how to contact you by electronic and paper mail.
311 |
312 | If the program is interactive, make it output a short notice like this
313 | when it starts in an interactive mode:
314 |
315 | Gnomovision version 69, Copyright (C) year name of author
316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317 | This is free software, and you are welcome to redistribute it
318 | under certain conditions; type `show c' for details.
319 |
320 | The hypothetical commands `show w' and `show c' should show the appropriate
321 | parts of the General Public License. Of course, the commands you use may
322 | be called something other than `show w' and `show c'; they could even be
323 | mouse-clicks or menu items--whatever suits your program.
324 |
325 | You should also get your employer (if you work as a programmer) or your
326 | school, if any, to sign a "copyright disclaimer" for the program, if
327 | necessary. Here is a sample; alter the names:
328 |
329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330 | `Gnomovision' (which makes passes at compilers) written by James Hacker.
331 |
332 | {signature of Ty Coon}, 1 April 1989
333 | Ty Coon, President of Vice
334 |
335 | This General Public License does not permit incorporating your program into
336 | proprietary programs. If your program is a subroutine library, you may
337 | consider it more useful to permit linking proprietary applications with the
338 | library. If this is what you want to do, use the GNU Lesser General
339 | Public License instead of this License.
340 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # shapefile
2 | ShapeFile library for PHP
3 |
4 | [](https://github.com/phpmyadmin/shapefile/actions/workflows/tests.yml?query=branch%3Amaster)
5 | [](https://codecov.io/github/phpmyadmin/shapefile?branch=master)
6 | [](https://scrutinizer-ci.com/g/phpmyadmin/shapefile/?branch=master)
7 | [](https://packagist.org/packages/phpmyadmin/shapefile)
8 |
9 | ## Features
10 |
11 | This library supports the 2D and 3D variants, except MultiPatch, of the ShapeFile format as
12 | defined in https://www.esri.com/library/whitepapers/pdfs/shapefile.pdf. It can read and edit ShapeFiles and the associated
13 | information (DBF file). There are a lot of things that can be improved in the
14 | code, if you are interested in developing, helping with the documentation,
15 | making translations or offering new ideas please contact us.
16 |
17 | ## Installation
18 |
19 | Please use [Composer][1] to install:
20 |
21 | ```sh
22 | composer require phpmyadmin/shapefile
23 | ```
24 |
25 | To be able to read and write the associated DBF file you need the ``dbase``
26 | extension:
27 |
28 | ```sh
29 | pecl install dbase
30 | echo "extension=dbase.so" > /etc/php8/conf.d/dbase.ini
31 | ```
32 |
33 | ## Documentation
34 |
35 | API documentation is available at
36 | .
37 |
38 | ## Usage
39 |
40 | To read a shape file:
41 |
42 | ```php
43 | use PhpMyAdmin\ShapeFile\ShapeFile;
44 | use PhpMyAdmin\ShapeFile\ShapeType;
45 |
46 | $shp = new ShapeFile(ShapeType::Null);
47 | $shp->loadFromFile('path/file.*');
48 | ```
49 |
50 | ## History
51 |
52 | This library is based on BytesFall ShapeFiles library written by Ovidio (ovidio
53 | AT users.sourceforge.net). It has been embedded in phpMyAdmin for
54 | years and slowly developed there. At one point people started to use our
55 | version rather than the original library and that was when we decided to
56 | make it a separate package.
57 |
58 | [1]:https://getcomposer.org/
59 |
--------------------------------------------------------------------------------
/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "phpmyadmin/shapefile",
3 | "description": "ESRI ShapeFile library for PHP",
4 | "license": "GPL-2.0-or-later",
5 | "keywords": ["shapefile", "shp", "geo", "geospatial", "dbf", "ESRI", "shape"],
6 | "homepage": "https://github.com/phpmyadmin/shapefile",
7 | "authors": [
8 | {
9 | "name": "The phpMyAdmin Team",
10 | "email": "developers@phpmyadmin.net",
11 | "homepage": "https://www.phpmyadmin.net/team/"
12 | }
13 | ],
14 | "support": {
15 | "issues": "https://github.com/phpmyadmin/shapefile/issues",
16 | "source": "https://github.com/phpmyadmin/shapefile"
17 | },
18 | "scripts": {
19 | "phpcbf": "@php phpcbf",
20 | "phpcs": "@php phpcs",
21 | "phpstan": "@php phpstan analyse",
22 | "phpunit": "@php phpunit --color=always",
23 | "psalm": "@php psalm",
24 | "test": [
25 | "@phpcs",
26 | "@phpstan",
27 | "@psalm",
28 | "@phpunit"
29 | ],
30 | "update:baselines": [
31 | "@php phpstan analyse --generate-baseline"
32 | ]
33 | },
34 | "require": {
35 | "php": "^8.2"
36 | },
37 | "suggest": {
38 | "ext-dbase": "For dbf files parsing"
39 | },
40 | "require-dev": {
41 | "phpmyadmin/coding-standard": "^4.0",
42 | "phpstan/extension-installer": "^1.4",
43 | "phpstan/phpstan": "^1.12",
44 | "phpstan/phpstan-deprecation-rules": "^1.2",
45 | "phpstan/phpstan-phpunit": "^1.4",
46 | "phpstan/phpstan-strict-rules": "^1.6",
47 | "phpunit/phpunit": "^10.5",
48 | "psalm/plugin-phpunit": "^0.18.4",
49 | "vimeo/psalm": "^5.15"
50 | },
51 | "autoload": {
52 | "psr-4": {
53 | "PhpMyAdmin\\ShapeFile\\": "src"
54 | }
55 | },
56 | "autoload-dev": {
57 | "psr-4": {
58 | "PhpMyAdminTest\\ShapeFile\\": "tests"
59 | }
60 | },
61 | "config":{
62 | "sort-packages": true,
63 | "allow-plugins": {
64 | "dealerdirect/phpcodesniffer-composer-installer": true,
65 | "phpstan/extension-installer": true
66 | }
67 | },
68 | "extra": {
69 | "branch-alias": {
70 | "dev-master": "4.0-dev"
71 | }
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/data/Czech_Republic_AL2.dbf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phpmyadmin/shapefile/6aab9173201b992a90ad36b5ee6b001f35760284/data/Czech_Republic_AL2.dbf
--------------------------------------------------------------------------------
/data/Czech_Republic_AL2.prj:
--------------------------------------------------------------------------------
1 | GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]]
--------------------------------------------------------------------------------
/data/Czech_Republic_AL2.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phpmyadmin/shapefile/6aab9173201b992a90ad36b5ee6b001f35760284/data/Czech_Republic_AL2.shp
--------------------------------------------------------------------------------
/data/Czech_Republic_AL2.shx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phpmyadmin/shapefile/6aab9173201b992a90ad36b5ee6b001f35760284/data/Czech_Republic_AL2.shx
--------------------------------------------------------------------------------
/data/bc_hospitals.dbf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phpmyadmin/shapefile/6aab9173201b992a90ad36b5ee6b001f35760284/data/bc_hospitals.dbf
--------------------------------------------------------------------------------
/data/bc_hospitals.prj:
--------------------------------------------------------------------------------
1 | PROJCS["BC_Albers",GEOGCS["GCS_North_American_1983",DATUM["D_North_American_1983",SPHEROID["GRS_1980",6378137,298.257222101]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]],PROJECTION["Albers"],PARAMETER["False_Easting",1000000],PARAMETER["False_Northing",0],PARAMETER["Central_Meridian",-126],PARAMETER["Standard_Parallel_1",50],PARAMETER["Standard_Parallel_2",58.5],PARAMETER["Latitude_Of_Origin",45],UNIT["Meter",1]]
--------------------------------------------------------------------------------
/data/bc_hospitals.qix:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phpmyadmin/shapefile/6aab9173201b992a90ad36b5ee6b001f35760284/data/bc_hospitals.qix
--------------------------------------------------------------------------------
/data/bc_hospitals.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phpmyadmin/shapefile/6aab9173201b992a90ad36b5ee6b001f35760284/data/bc_hospitals.shp
--------------------------------------------------------------------------------
/data/bc_hospitals.shx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phpmyadmin/shapefile/6aab9173201b992a90ad36b5ee6b001f35760284/data/bc_hospitals.shx
--------------------------------------------------------------------------------
/data/capitals.dbf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phpmyadmin/shapefile/6aab9173201b992a90ad36b5ee6b001f35760284/data/capitals.dbf
--------------------------------------------------------------------------------
/data/capitals.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phpmyadmin/shapefile/6aab9173201b992a90ad36b5ee6b001f35760284/data/capitals.shp
--------------------------------------------------------------------------------
/data/capitals.shx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phpmyadmin/shapefile/6aab9173201b992a90ad36b5ee6b001f35760284/data/capitals.shx
--------------------------------------------------------------------------------
/data/invalid-dbf.dbf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phpmyadmin/shapefile/6aab9173201b992a90ad36b5ee6b001f35760284/data/invalid-dbf.dbf
--------------------------------------------------------------------------------
/data/invalid-dbf.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phpmyadmin/shapefile/6aab9173201b992a90ad36b5ee6b001f35760284/data/invalid-dbf.shp
--------------------------------------------------------------------------------
/data/invalid-dbf.shx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phpmyadmin/shapefile/6aab9173201b992a90ad36b5ee6b001f35760284/data/invalid-dbf.shx
--------------------------------------------------------------------------------
/data/invalid-shp.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phpmyadmin/shapefile/6aab9173201b992a90ad36b5ee6b001f35760284/data/invalid-shp.shp
--------------------------------------------------------------------------------
/data/mexico.dbf:
--------------------------------------------------------------------------------
1 | d At W AREA N CODE C NAME C POP1990 N POP90_SQMI N
P_URBAN90 N
P_ING_LANG N
P_EMPL_SEC N
HSE_UNIT90 N
28002.325MX02Baja California Norte 1660855 61.537060 90.904620 1.300000 31.700000 362727 27898.191MX03Baja California Sur 317764 11.204120 78.254620 1.000000 18.800000 67304 10547.762MX18Nayarit 824643 79.186840 62.054850 3.400000 17.600000 168451 30736.386MX14Jalisco 5302689 169.943300 81.853420 0.500000 32.700000 1029178 2110.761MX01Aguascalientes 719659 340.778900 76.521930 0.100000 34.200000 129853 11715.793MX11Guanajuato 3982593 338.381600 63.414290 0.300000 35.000000 687136 4645.565MX22Queretaro de Arteaga 1051235 237.872900 59.723950 2.300000 37.300000 193434 8198.684MX13Hidalgo 1888366 235.052100 44.785700 19.500000 25.200000 362933 22961.931MX16Michoacan de Ocampo 3548199 153.387800 61.618700 3.500000 23.200000 663496 8291.708MX15Mexico 9815795 1190.799000 84.406890 3.700000 36.800000 1876545 512.050MX09Distrito Federal 8235744 14426.050000 99.734080 1.500000 27.000000 1789171 2211.033MX08Colima 428510 213.856600 83.319880 0.400000 21.400000 88627 1951.676MX17Morelos 1195059 625.456100 85.621540 1.900000 27.900000 244958 14628.106MX31Yucatan 1362940 91.946590 78.625470 44.200000 24.500000 273958 19369.415MX04Campeche 535185 27.286660 70.024380 19.000000 19.400000 107894 13227.318MX21Puebla 4126101 315.302400 64.292630 14.100000 24.900000 772461 19782.748MX23Quintana Roo 493277 25.450490 73.868030 32.200000 15.500000 102859 1534.069MX29Tlaxcala 761277 491.090700 76.496600 3.400000 33.900000 137135 25001.188MX12Guerrero 2620637 105.617700 52.259660 13.400000 16.900000 501725 35786.813MX20Oaxaca 3019560 83.262670 39.452870 39.100000 16.400000 587131 9364.727MX27Tabasco 1501744 153.976700 49.656800 3.700000 20.500000 285319 28335.571MX05Chiapas 3210496 112.077000 40.390700 26.400000 11.100000 594025 69542.455MX26Sonora 1823606 25.950650 79.132610 3.000000 25.400000 378587 95771.458MX06Chihuahua 2441873 25.827340 77.390020 2.900000 35.900000 529799 57988.415MX07Coahuila De Zaragoza 1972340 34.068680 86.056210 0.200000 37.700000 404691 22315.678MX25Sinaloa 2204054 97.894390 64.084050 1.600000 17.200000 422242 46463.611MX10Durango 1349378 28.379360 57.390660 1.600000 26.600000 262164 28881.617MX32Zacatecas 1276323 45.139200 45.937980 0.100000 21.500000 238779 24767.049MX24San Luis Potosi 2003187 82.285840 55.163250 11.900000 26.000000 379336 25139.835MX19Nuevo Leon 3098736 123.649400 91.994190 0.200000 40.200000 642298 30503.273MX28Tamaulipas 2249581 73.414430 81.068610 0.400000 30.500000 488508 27564.808MX30Veracruz-Llave 6228239 225.042700 56.223370 10.700000 21.200000 1262509
--------------------------------------------------------------------------------
/data/mexico.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phpmyadmin/shapefile/6aab9173201b992a90ad36b5ee6b001f35760284/data/mexico.shp
--------------------------------------------------------------------------------
/data/mexico.shx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phpmyadmin/shapefile/6aab9173201b992a90ad36b5ee6b001f35760284/data/mexico.shx
--------------------------------------------------------------------------------
/data/multipoint.dbf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phpmyadmin/shapefile/6aab9173201b992a90ad36b5ee6b001f35760284/data/multipoint.dbf
--------------------------------------------------------------------------------
/data/multipoint.prj:
--------------------------------------------------------------------------------
1 | PROJCS["MGI_Slovene_National_Grid_deprecated",GEOGCS["GCS_MGI",DATUM["D_MGI",SPHEROID["Bessel_1841",6377397.155,299.1528128]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",15],PARAMETER["scale_factor",0.9999],PARAMETER["false_easting",500000],PARAMETER["false_northing",-5000000],UNIT["Meter",1]]
--------------------------------------------------------------------------------
/data/multipoint.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phpmyadmin/shapefile/6aab9173201b992a90ad36b5ee6b001f35760284/data/multipoint.shp
--------------------------------------------------------------------------------
/data/multipoint.shx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phpmyadmin/shapefile/6aab9173201b992a90ad36b5ee6b001f35760284/data/multipoint.shx
--------------------------------------------------------------------------------
/data/no-dbf.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phpmyadmin/shapefile/6aab9173201b992a90ad36b5ee6b001f35760284/data/no-dbf.shp
--------------------------------------------------------------------------------
/data/no-dbf.shx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phpmyadmin/shapefile/6aab9173201b992a90ad36b5ee6b001f35760284/data/no-dbf.shx
--------------------------------------------------------------------------------
/data/no-shp.dbf:
--------------------------------------------------------------------------------
1 | d At W AREA N CODE C NAME C POP1990 N POP90_SQMI N
P_URBAN90 N
P_ING_LANG N
P_EMPL_SEC N
HSE_UNIT90 N
28002.325MX02Baja California Norte 1660855 61.537060 90.904620 1.300000 31.700000 362727 27898.191MX03Baja California Sur 317764 11.204120 78.254620 1.000000 18.800000 67304 10547.762MX18Nayarit 824643 79.186840 62.054850 3.400000 17.600000 168451 30736.386MX14Jalisco 5302689 169.943300 81.853420 0.500000 32.700000 1029178 2110.761MX01Aguascalientes 719659 340.778900 76.521930 0.100000 34.200000 129853 11715.793MX11Guanajuato 3982593 338.381600 63.414290 0.300000 35.000000 687136 4645.565MX22Queretaro de Arteaga 1051235 237.872900 59.723950 2.300000 37.300000 193434 8198.684MX13Hidalgo 1888366 235.052100 44.785700 19.500000 25.200000 362933 22961.931MX16Michoacan de Ocampo 3548199 153.387800 61.618700 3.500000 23.200000 663496 8291.708MX15Mexico 9815795 1190.799000 84.406890 3.700000 36.800000 1876545 512.050MX09Distrito Federal 8235744 14426.050000 99.734080 1.500000 27.000000 1789171 2211.033MX08Colima 428510 213.856600 83.319880 0.400000 21.400000 88627 1951.676MX17Morelos 1195059 625.456100 85.621540 1.900000 27.900000 244958 14628.106MX31Yucatan 1362940 91.946590 78.625470 44.200000 24.500000 273958 19369.415MX04Campeche 535185 27.286660 70.024380 19.000000 19.400000 107894 13227.318MX21Puebla 4126101 315.302400 64.292630 14.100000 24.900000 772461 19782.748MX23Quintana Roo 493277 25.450490 73.868030 32.200000 15.500000 102859 1534.069MX29Tlaxcala 761277 491.090700 76.496600 3.400000 33.900000 137135 25001.188MX12Guerrero 2620637 105.617700 52.259660 13.400000 16.900000 501725 35786.813MX20Oaxaca 3019560 83.262670 39.452870 39.100000 16.400000 587131 9364.727MX27Tabasco 1501744 153.976700 49.656800 3.700000 20.500000 285319 28335.571MX05Chiapas 3210496 112.077000 40.390700 26.400000 11.100000 594025 69542.455MX26Sonora 1823606 25.950650 79.132610 3.000000 25.400000 378587 95771.458MX06Chihuahua 2441873 25.827340 77.390020 2.900000 35.900000 529799 57988.415MX07Coahuila De Zaragoza 1972340 34.068680 86.056210 0.200000 37.700000 404691 22315.678MX25Sinaloa 2204054 97.894390 64.084050 1.600000 17.200000 422242 46463.611MX10Durango 1349378 28.379360 57.390660 1.600000 26.600000 262164 28881.617MX32Zacatecas 1276323 45.139200 45.937980 0.100000 21.500000 238779 24767.049MX24San Luis Potosi 2003187 82.285840 55.163250 11.900000 26.000000 379336 25139.835MX19Nuevo Leon 3098736 123.649400 91.994190 0.200000 40.200000 642298 30503.273MX28Tamaulipas 2249581 73.414430 81.068610 0.400000 30.500000 488508 27564.808MX30Veracruz-Llave 6228239 225.042700 56.223370 10.700000 21.200000 1262509
--------------------------------------------------------------------------------
/data/no-shp.shx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phpmyadmin/shapefile/6aab9173201b992a90ad36b5ee6b001f35760284/data/no-shp.shx
--------------------------------------------------------------------------------
/data/w001n05f.dbf:
--------------------------------------------------------------------------------
1 | h A FACC_CODE C
2 |
BH080 BH080 BH080 BH080 BH080 BA040 BH080 BH080 BH080 BH080 BH080 BH080 BH080 BH080 BH080 BA040
--------------------------------------------------------------------------------
/data/w001n05f.shp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phpmyadmin/shapefile/6aab9173201b992a90ad36b5ee6b001f35760284/data/w001n05f.shp
--------------------------------------------------------------------------------
/data/w001n05f.shx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phpmyadmin/shapefile/6aab9173201b992a90ad36b5ee6b001f35760284/data/w001n05f.shx
--------------------------------------------------------------------------------
/examples/create_shapefile.php:
--------------------------------------------------------------------------------
1 | .
8 | *
9 | * Copyright 2006-2007 Ovidio
10 | * Copyright 2016 - 2017 Michal Čihař
11 | *
12 | * This program is free software; you can redistribute it and/or
13 | * modify it under the terms of the GNU General Public License
14 | * as published by the Free Software Foundation.
15 | *
16 | * This program is distributed in the hope that it will be useful,
17 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 | * GNU General Public License for more details.
20 | *
21 | * You should have received a copy of the GNU General Public License
22 | * along with this program; if not, you can download one from
23 | * https://www.gnu.org/copyleft/gpl.html.
24 | */
25 |
26 | use PhpMyAdmin\ShapeFile\ShapeFile;
27 | use PhpMyAdmin\ShapeFile\ShapeRecord;
28 | use PhpMyAdmin\ShapeFile\ShapeType;
29 |
30 | require_once __DIR__ . '/../vendor/autoload.php';
31 |
32 | $shp = new ShapeFile(ShapeType::Point, [
33 | 'xmin' => 464079.002268,
34 | 'ymin' => 2120153.74792,
35 | 'xmax' => 505213.52849,
36 | 'ymax' => 2163205.70036,
37 | ]);
38 |
39 | $record0 = new ShapeRecord(ShapeType::Point);
40 | $record0->addPoint([
41 | 'x' => 482131.764567,
42 | 'y' => 2143634.39608,
43 | ]);
44 |
45 | $record1 = new ShapeRecord(ShapeType::Point);
46 | $record1->addPoint([
47 | 'x' => 472131.764567,
48 | 'y' => 2143634.39608,
49 | ]);
50 |
51 | $record2 = new ShapeRecord(ShapeType::Point);
52 | $record2->addPoint([
53 | 'x' => 492131.764567,
54 | 'y' => 2143634.39608,
55 | ]);
56 |
57 | $shp->addRecord($record0);
58 | $shp->addRecord($record1);
59 | $shp->addRecord($record2);
60 |
61 | $shp->setDBFHeader(
62 | [
63 | [
64 | 'ID',
65 | 'N',
66 | 8,
67 | 0,
68 | ],
69 | [
70 | 'DESC',
71 | 'C',
72 | 50,
73 | 0,
74 | ],
75 | ],
76 | );
77 |
78 | $shp->records[0]->dbfData['ID'] = '1';
79 | $shp->records[0]->dbfData['DESC'] = 'AAAAAAAAA';
80 |
81 | $shp->records[1]->dbfData['ID'] = '2';
82 | $shp->records[1]->dbfData['DESC'] = 'BBBBBBBBBB';
83 |
84 | $shp->records[2]->dbfData['ID'] = '3';
85 | $shp->records[2]->dbfData['DESC'] = 'CCCCCCCCCCC';
86 |
87 | $shp->saveToFile('../data/new_shape.*');
88 |
89 | echo "The ShapeFile was created. \n";
90 | echo 'Return to the index.';
91 |
--------------------------------------------------------------------------------
/examples/index.php:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | ShapeFiles demo
6 |
7 |
8 |
9 | This demo illustrates some of the possibile uses of ShapeFiles. There are several more, just check the source code to see the methods implemented in the classes ShapeFile and ShapeRecord.
10 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/examples/read.php:
--------------------------------------------------------------------------------
1 | .
8 | *
9 | * Copyright 2006-2007 Ovidio
10 | * Copyright 2016 - 2017 Michal Čihař
11 | *
12 | * This program is free software; you can redistribute it and/or
13 | * modify it under the terms of the GNU General Public License
14 | * as published by the Free Software Foundation.
15 | *
16 | * This program is distributed in the hope that it will be useful,
17 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 | * GNU General Public License for more details.
20 | *
21 | * You should have received a copy of the GNU General Public License
22 | * along with this program; if not, you can download one from
23 | * https://www.gnu.org/copyleft/gpl.html.
24 | */
25 |
26 | use PhpMyAdmin\ShapeFile\ShapeFile;
27 | use PhpMyAdmin\ShapeFile\ShapeType;
28 |
29 | /**
30 | * Displays content of given file.
31 | *
32 | * @param string $filename File to open
33 | */
34 | // phpcs:ignore Squiz.Functions.GlobalFunction.Found
35 | function display_file(string $filename): void
36 | {
37 | $shp = new ShapeFile(ShapeType::Point);
38 | $shp->loadFromFile($filename);
39 |
40 | $i = 1;
41 | foreach ($shp->records as $i => $record) {
42 | echo '
';
43 | echo 'Record No. ' . $i . ':' . "\n\n\n";
44 | // All the data related to the record
45 | echo 'SHP Data = ';
46 | print_r($record->shpData);
47 | print_r("\n\n\n");
48 | // All the information related to each record
49 | echo 'DBF Data = ';
50 | print_r($record->dbfData);
51 | print_r("\n\n\n");
52 | echo '
';
53 | }
54 |
55 | echo 'The ShapeFile was completely read. ' . "\n";
56 | echo 'Return to the index.';
57 | }
58 |
--------------------------------------------------------------------------------
/examples/read_point.php:
--------------------------------------------------------------------------------
1 | .
8 | *
9 | * Copyright 2006-2007 Ovidio
10 | * Copyright 2016 - 2017 Michal Čihař
11 | *
12 | * This program is free software; you can redistribute it and/or
13 | * modify it under the terms of the GNU General Public License
14 | * as published by the Free Software Foundation.
15 | *
16 | * This program is distributed in the hope that it will be useful,
17 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 | * GNU General Public License for more details.
20 | *
21 | * You should have received a copy of the GNU General Public License
22 | * along with this program; if not, you can download one from
23 | * https://www.gnu.org/copyleft/gpl.html.
24 | */
25 |
26 | require_once __DIR__ . '/../vendor/autoload.php';
27 | require_once __DIR__ . '/read.php';
28 |
29 | display_file(__DIR__ . '/../data/capitals.*');
30 |
--------------------------------------------------------------------------------
/examples/read_polygon.php:
--------------------------------------------------------------------------------
1 | .
8 | *
9 | * Copyright 2006-2007 Ovidio
10 | * Copyright 2016 - 2017 Michal Čihař
11 | *
12 | * This program is free software; you can redistribute it and/or
13 | * modify it under the terms of the GNU General Public License
14 | * as published by the Free Software Foundation.
15 | *
16 | * This program is distributed in the hope that it will be useful,
17 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 | * GNU General Public License for more details.
20 | *
21 | * You should have received a copy of the GNU General Public License
22 | * along with this program; if not, you can download one from
23 | * https://www.gnu.org/copyleft/gpl.html.
24 | */
25 | require_once __DIR__ . '/../vendor/autoload.php';
26 | require_once __DIR__ . '/read.php';
27 |
28 | display_file(__DIR__ . '/../data/mexico.*');
29 |
--------------------------------------------------------------------------------
/phpunit.xml.dist:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
9 | src
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 | tests
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/src/ShapeFile.php:
--------------------------------------------------------------------------------
1 | .
8 | *
9 | * Copyright 2006-2007 Ovidio
10 | * Copyright 2016 - 2017 Michal Čihař
11 | *
12 | * This program is free software; you can redistribute it and/or
13 | * modify it under the terms of the GNU General Public License
14 | * as published by the Free Software Foundation.
15 | *
16 | * This program is distributed in the hope that it will be useful,
17 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 | * GNU General Public License for more details.
20 | *
21 | * You should have received a copy of the GNU General Public License
22 | * along with this program; if not, you can download one from
23 | * https://www.gnu.org/copyleft/gpl.html.
24 | */
25 |
26 | namespace PhpMyAdmin\ShapeFile;
27 |
28 | use function chr;
29 | use function count;
30 | use function dbase_close;
31 | use function dbase_create;
32 | use function dbase_delete_record;
33 | use function dbase_open;
34 | use function dbase_pack;
35 | use function extension_loaded;
36 | use function fclose;
37 | use function feof;
38 | use function file_exists;
39 | use function fopen;
40 | use function fread;
41 | use function fwrite;
42 | use function in_array;
43 | use function is_readable;
44 | use function ord;
45 | use function pack;
46 | use function sprintf;
47 | use function str_replace;
48 | use function strpos;
49 | use function strtoupper;
50 | use function substr;
51 | use function trim;
52 | use function unlink;
53 |
54 | /**
55 | * ShapeFile class.
56 | */
57 | class ShapeFile
58 | {
59 | public final const MAGIC = 0x270a;
60 |
61 | /** @var resource|false */
62 | private $shpFile = false;
63 |
64 | /** @var resource|false */
65 | private $shxFile = false;
66 |
67 | /** @var resource|false */
68 | private $dbfFile = false;
69 |
70 | /** @var mixed[]|null */
71 | private array|null $dbfHeader = null;
72 |
73 | public string $lastError = '';
74 |
75 | /**
76 | * The value for file length is the total length of the file in 16-bit words
77 | * (including the fifty 16-bit words that make up the header).
78 | */
79 | private int $fileLength = 50;
80 |
81 | /** @var array */
82 | public array $records = [];
83 |
84 | private bool $allowNoDbf = false;
85 |
86 | /**
87 | * Checks whether dbase manipulations are supported.
88 | */
89 | public static function supportsDbase(): bool
90 | {
91 | return extension_loaded('dbase');
92 | }
93 |
94 | /**
95 | * @param ShapeType $shapeType File shape type, should be same as all records
96 | * @param mixed[] $boundingBox File bounding box
97 | * @param string|null $fileName File name
98 | */
99 | public function __construct(
100 | public ShapeType $shapeType,
101 | public array $boundingBox = [
102 | 'xmin' => 0.0,
103 | 'ymin' => 0.0,
104 | 'xmax' => 0.0,
105 | 'ymax' => 0.0,
106 | ],
107 | public string|null $fileName = null,
108 | ) {
109 | }
110 |
111 | public function setAllowNoDbf(bool $allowNoDbf): void
112 | {
113 | $this->allowNoDbf = $allowNoDbf;
114 | }
115 |
116 | /**
117 | * Loads shapefile and dbase (if supported).
118 | *
119 | * @param string $fileName File mask to load (eg. example.*)
120 | */
121 | public function loadFromFile(string $fileName): bool
122 | {
123 | if ($fileName !== '') {
124 | $this->fileName = $fileName;
125 | $result = $this->openSHPFile();
126 | } else {
127 | /* We operate on buffer emulated by readSHP / eofSHP */
128 | $result = true;
129 | }
130 |
131 | if ($result && ($this->openDBFFile())) {
132 | if (! $this->loadHeaders()) {
133 | $this->closeSHPFile();
134 | $this->closeDBFFile();
135 |
136 | return false;
137 | }
138 |
139 | if (! $this->loadRecords()) {
140 | $this->closeSHPFile();
141 | $this->closeDBFFile();
142 |
143 | return false;
144 | }
145 |
146 | $this->closeSHPFile();
147 | $this->closeDBFFile();
148 |
149 | return true;
150 | }
151 |
152 | return false;
153 | }
154 |
155 | /**
156 | * Saves shapefile.
157 | *
158 | * @param string|null $fileName Name of file, otherwise existing is used
159 | */
160 | public function saveToFile(string|null $fileName = null): bool
161 | {
162 | if ($fileName !== null) {
163 | $this->fileName = $fileName;
164 | }
165 |
166 | if (! $this->openSHPFile(true) || (! $this->openSHXFile(true)) || (! $this->createDBFFile())) {
167 | return false;
168 | }
169 |
170 | $this->saveHeaders();
171 | $this->saveRecords();
172 | $this->closeSHPFile();
173 | $this->closeSHXFile();
174 | $this->closeDBFFile();
175 |
176 | return true;
177 | }
178 |
179 | /**
180 | * Generates filename with given extension.
181 | *
182 | * @param string $extension Extension to use (including dot)
183 | */
184 | private function getFilename(string $extension): string
185 | {
186 | return str_replace('.*', $extension, (string) $this->fileName);
187 | }
188 |
189 | /**
190 | * Updates bounding box based on shpData.
191 | *
192 | * @param string $type Type of box
193 | * @param mixed[] $data ShapeRecord shpData
194 | */
195 | private function updateBBox(string $type, array $data): void
196 | {
197 | $min = $type . 'min';
198 | $max = $type . 'max';
199 |
200 | if (
201 | ! isset($this->boundingBox[$min])
202 | || $this->boundingBox[$min] == 0.0 // phpcs:ignore SlevomatCodingStandard.Operators.DisallowEqualOperators
203 | || ($this->boundingBox[$min] > $data[$min])
204 | ) {
205 | $this->boundingBox[$min] = $data[$min];
206 | }
207 |
208 | if (
209 | isset($this->boundingBox[$max])
210 | && $this->boundingBox[$max] != 0.0 // phpcs:ignore SlevomatCodingStandard.Operators.DisallowEqualOperators
211 | && ($this->boundingBox[$max] >= $data[$max])
212 | ) {
213 | return;
214 | }
215 |
216 | $this->boundingBox[$max] = $data[$max];
217 | }
218 |
219 | /**
220 | * Adds record to shape file.
221 | *
222 | * @return int Number of added record
223 | */
224 | public function addRecord(ShapeRecord $record): int
225 | {
226 | if ($this->dbfHeader !== null) {
227 | $record->updateDBFInfo($this->dbfHeader);
228 | }
229 |
230 | $this->fileLength += $record->getContentLength() + 4;
231 | $this->records[] = $record;
232 | $this->records[count($this->records) - 1]->recordNumber = count($this->records);
233 |
234 | $this->updateBBox('x', $record->shpData);
235 | $this->updateBBox('y', $record->shpData);
236 |
237 | if (in_array($this->shapeType, ShapeType::MEASURED_TYPES, true)) {
238 | $this->updateBBox('m', $record->shpData);
239 | }
240 |
241 | if (in_array($this->shapeType, ShapeType::TYPES_WITH_Z, true)) {
242 | $this->updateBBox('z', $record->shpData);
243 | }
244 |
245 | return count($this->records) - 1;
246 | }
247 |
248 | /**
249 | * Deletes record from shapefile.
250 | */
251 | public function deleteRecord(int $index): void
252 | {
253 | if (! isset($this->records[$index])) {
254 | return;
255 | }
256 |
257 | $this->fileLength -= $this->records[$index]->getContentLength() + 4;
258 | $count = count($this->records) - 1;
259 | for ($i = $index; $i < $count; ++$i) {
260 | $this->records[$i] = $this->records[$i + 1];
261 | }
262 |
263 | unset($this->records[count($this->records) - 1]);
264 | $this->deleteRecordFromDBF($index);
265 | }
266 |
267 | /**
268 | * Returns array defining fields in DBF file.
269 | *
270 | * @return mixed[]|null see setDBFHeader for more information
271 | */
272 | public function getDBFHeader(): array|null
273 | {
274 | return $this->dbfHeader;
275 | }
276 |
277 | /**
278 | * Changes array defining fields in DBF file, used in dbase_create call.
279 | *
280 | * @param mixed[] $header An array of arrays, each array describing the
281 | * format of one field of the database. Each
282 | * field consists of a name, a character indicating
283 | * the field type, and optionally, a length,
284 | * a precision and a nullable flag.
285 | */
286 | public function setDBFHeader(array $header): void
287 | {
288 | $this->dbfHeader = $header;
289 |
290 | foreach ($this->records as $record) {
291 | $record->updateDBFInfo($header);
292 | }
293 | }
294 |
295 | /**
296 | * Lookups value in the DBF file and returns index.
297 | */
298 | public function getIndexFromDBFData(string $field, string $value): int
299 | {
300 | foreach ($this->records as $index => $record) {
301 | if (
302 | isset($record->dbfData[$field]) &&
303 | (trim(strtoupper($record->dbfData[$field])) === strtoupper($value))
304 | ) {
305 | return $index;
306 | }
307 | }
308 |
309 | return -1;
310 | }
311 |
312 | /**
313 | * Loads DBF metadata.
314 | *
315 | * @return array{string, string, int, int}[]
316 | */
317 | private function loadDBFHeader(): array
318 | {
319 | if (! self::supportsDbase()) {
320 | return [];
321 | }
322 |
323 | $dbfName = $this->getFilename('.dbf');
324 | if (! file_exists($dbfName)) {
325 | return [];
326 | }
327 |
328 | $dbfFile = fopen($dbfName, 'r');
329 | if ($dbfFile === false) {
330 | return [];
331 | }
332 |
333 | $result = [];
334 | $i = 1;
335 |
336 | while (true) {
337 | if (feof($dbfFile)) {
338 | break;
339 | }
340 |
341 | $buff32 = fread($dbfFile, 32);
342 | if ($i > 1) {
343 | if (substr($buff32, 0, 1) === chr(13)) {
344 | break;
345 | }
346 |
347 | $pos = strpos(substr($buff32, 0, 10), chr(0));
348 | $pos = ($pos === false ? 10 : $pos);
349 |
350 | $fieldName = substr($buff32, 0, $pos);
351 | $fieldType = substr($buff32, 11, 1);
352 | $fieldLen = ord(substr($buff32, 16, 1));
353 | $fieldDec = ord(substr($buff32, 17, 1));
354 |
355 | $result[] = [$fieldName, $fieldType, $fieldLen, $fieldDec];
356 | }
357 |
358 | ++$i;
359 | }
360 |
361 | fclose($dbfFile);
362 |
363 | return $result;
364 | }
365 |
366 | /**
367 | * Deletes record from the DBF file.
368 | */
369 | private function deleteRecordFromDBF(int $index): void
370 | {
371 | if ($this->dbfFile === false || ! @dbase_delete_record($this->dbfFile, $index)) {
372 | return;
373 | }
374 |
375 | dbase_pack($this->dbfFile);
376 | }
377 |
378 | /**
379 | * Loads SHP file metadata.
380 | */
381 | private function loadHeaders(): bool
382 | {
383 | if (Util::loadData('N', $this->readSHP(4)) !== self::MAGIC) {
384 | $this->setError('Not a SHP file (file code mismatch)');
385 |
386 | return false;
387 | }
388 |
389 | /* Skip 20 unused bytes */
390 | $this->readSHP(20);
391 |
392 | $this->fileLength = (int) Util::loadData('N', $this->readSHP(4));
393 |
394 | /* We currently ignore version */
395 | $this->readSHP(4);
396 |
397 | $shapeType = Util::loadData('V', $this->readSHP(4));
398 | if ($shapeType === false) {
399 | $this->shapeType = ShapeType::Unknown;
400 | } else {
401 | $this->shapeType = ShapeType::tryFrom((int) $shapeType) ?? ShapeType::Unknown;
402 | }
403 |
404 | $this->boundingBox = [];
405 | $this->boundingBox['xmin'] = Util::loadData('d', $this->readSHP(8));
406 | $this->boundingBox['ymin'] = Util::loadData('d', $this->readSHP(8));
407 | $this->boundingBox['xmax'] = Util::loadData('d', $this->readSHP(8));
408 | $this->boundingBox['ymax'] = Util::loadData('d', $this->readSHP(8));
409 | $this->boundingBox['zmin'] = Util::loadData('d', $this->readSHP(8));
410 | $this->boundingBox['zmax'] = Util::loadData('d', $this->readSHP(8));
411 | $this->boundingBox['mmin'] = Util::loadData('d', $this->readSHP(8));
412 | $this->boundingBox['mmax'] = Util::loadData('d', $this->readSHP(8));
413 |
414 | $this->dbfHeader = $this->loadDBFHeader();
415 |
416 | return true;
417 | }
418 |
419 | /**
420 | * Saves bounding box record, possibly using 0 instead of not set values.
421 | *
422 | * @param resource $file File object
423 | * @param string $type Bounding box dimension (eg. xmax, mmin...)
424 | */
425 | private function saveBBoxRecord($file, string $type): void
426 | {
427 | fwrite($file, Util::packDouble(
428 | $this->boundingBox[$type] ?? 0,
429 | ));
430 | }
431 |
432 | /**
433 | * Saves bounding box to a file.
434 | *
435 | * @param resource $file File object
436 | */
437 | private function saveBBox($file): void
438 | {
439 | $this->saveBBoxRecord($file, 'xmin');
440 | $this->saveBBoxRecord($file, 'ymin');
441 | $this->saveBBoxRecord($file, 'xmax');
442 | $this->saveBBoxRecord($file, 'ymax');
443 | $this->saveBBoxRecord($file, 'zmin');
444 | $this->saveBBoxRecord($file, 'zmax');
445 | $this->saveBBoxRecord($file, 'mmin');
446 | $this->saveBBoxRecord($file, 'mmax');
447 | }
448 |
449 | /**
450 | * Saves SHP and SHX file metadata.
451 | */
452 | private function saveHeaders(): void
453 | {
454 | if ($this->shpFile === false) {
455 | return;
456 | }
457 |
458 | fwrite($this->shpFile, pack('NNNNNN', self::MAGIC, 0, 0, 0, 0, 0));
459 | fwrite($this->shpFile, pack('N', $this->fileLength));
460 | fwrite($this->shpFile, pack('V', 1000));
461 | fwrite($this->shpFile, pack('V', $this->shapeType->value));
462 | $this->saveBBox($this->shpFile);
463 |
464 | if ($this->shxFile === false) {
465 | return;
466 | }
467 |
468 | fwrite($this->shxFile, pack('NNNNNN', self::MAGIC, 0, 0, 0, 0, 0));
469 | fwrite($this->shxFile, pack('N', 50 + 4 * count($this->records)));
470 | fwrite($this->shxFile, pack('V', 1000));
471 | fwrite($this->shxFile, pack('V', $this->shapeType->value));
472 | $this->saveBBox($this->shxFile);
473 | }
474 |
475 | /**
476 | * Loads records from SHP file (and DBF).
477 | */
478 | private function loadRecords(): bool
479 | {
480 | /* Need to start at offset 100 */
481 | while (! $this->eofSHP()) {
482 | $record = new ShapeRecord(ShapeType::Unknown);
483 | $record->loadFromFile($this, $this->dbfFile);
484 | if ($record->lastError !== '') {
485 | $this->setError($record->lastError);
486 |
487 | return false;
488 | }
489 |
490 | if (($record->shapeType === ShapeType::Unknown) && $this->eofSHP()) {
491 | break;
492 | }
493 |
494 | $this->records[] = $record;
495 | }
496 |
497 | return true;
498 | }
499 |
500 | /**
501 | * Saves records to SHP and SHX files.
502 | */
503 | private function saveRecords(): void
504 | {
505 | $offset = 50;
506 | if ($this->records === [] || $this->shxFile === false || $this->shpFile === false) {
507 | return;
508 | }
509 |
510 | foreach ($this->records as $index => $record) {
511 | //Save the record to the .shp file
512 | $record->saveToFile($this->shpFile, $this->dbfFile, $index + 1);
513 |
514 | //Save the record to the .shx file
515 | fwrite($this->shxFile, pack('N', $offset));
516 | fwrite($this->shxFile, pack('N', $record->getContentLength()));
517 | $offset += 4 + $record->getContentLength();
518 | }
519 | }
520 |
521 | /**
522 | * Generic interface to open files.
523 | *
524 | * @param bool $toWrite Whether file should be opened for writing
525 | * @param string $extension File extension
526 | * @param string $name Verbose file name to report errors
527 | *
528 | * @return resource|false File handle
529 | */
530 | private function openFile(bool $toWrite, string $extension, string $name)
531 | {
532 | $shpName = $this->getFilename($extension);
533 | $result = @fopen($shpName, ($toWrite ? 'wb+' : 'rb'));
534 | if (! $result) {
535 | $this->setError(sprintf('It wasn\'t possible to open the %s file "%s"', $name, $shpName));
536 |
537 | return false;
538 | }
539 |
540 | return $result;
541 | }
542 |
543 | /**
544 | * Opens SHP file.
545 | *
546 | * @param bool $toWrite Whether file should be opened for writing
547 | */
548 | private function openSHPFile(bool $toWrite = false): bool
549 | {
550 | $this->shpFile = $this->openFile($toWrite, '.shp', 'Shape');
551 |
552 | return (bool) $this->shpFile;
553 | }
554 |
555 | /**
556 | * Closes SHP file.
557 | */
558 | private function closeSHPFile(): void
559 | {
560 | if ($this->shpFile === false) {
561 | return;
562 | }
563 |
564 | fclose($this->shpFile);
565 | $this->shpFile = false;
566 | }
567 |
568 | /**
569 | * Opens SHX file.
570 | *
571 | * @param bool $toWrite Whether file should be opened for writing
572 | */
573 | private function openSHXFile(bool $toWrite = false): bool
574 | {
575 | $this->shxFile = $this->openFile($toWrite, '.shx', 'Index');
576 |
577 | return (bool) $this->shxFile;
578 | }
579 |
580 | /**
581 | * Closes SHX file.
582 | */
583 | private function closeSHXFile(): void
584 | {
585 | if ($this->shxFile === false) {
586 | return;
587 | }
588 |
589 | fclose($this->shxFile);
590 | $this->shxFile = false;
591 | }
592 |
593 | /**
594 | * Creates DBF file.
595 | */
596 | private function createDBFFile(): bool
597 | {
598 | if (! self::supportsDbase() || $this->dbfHeader === null || $this->dbfHeader === []) {
599 | $this->dbfFile = false;
600 |
601 | return true;
602 | }
603 |
604 | $dbfName = $this->getFilename('.dbf');
605 |
606 | /* Unlink existing file */
607 | if (file_exists($dbfName)) {
608 | unlink($dbfName);
609 | }
610 |
611 | /* Create new file */
612 | $this->dbfFile = @dbase_create($dbfName, $this->dbfHeader);
613 | if ($this->dbfFile === false) {
614 | $this->setError(sprintf('It wasn\'t possible to create the DBase file "%s"', $dbfName));
615 |
616 | return false;
617 | }
618 |
619 | return true;
620 | }
621 |
622 | /**
623 | * Loads DBF file if supported.
624 | */
625 | private function openDBFFile(): bool
626 | {
627 | if (! self::supportsDbase()) {
628 | $this->dbfFile = false;
629 |
630 | return true;
631 | }
632 |
633 | $dbfName = $this->getFilename('.dbf');
634 | if (! is_readable($dbfName)) {
635 | if ($this->allowNoDbf) {
636 | return true;
637 | }
638 |
639 | $this->setError(sprintf('It wasn\'t possible to find the DBase file "%s"', $dbfName));
640 |
641 | return false;
642 | }
643 |
644 | $this->dbfFile = @dbase_open($dbfName, 0);
645 | if ($this->dbfFile === false) {
646 | $this->setError(sprintf('It wasn\'t possible to open the DBase file "%s"', $dbfName));
647 |
648 | return false;
649 | }
650 |
651 | return true;
652 | }
653 |
654 | /**
655 | * Closes DBF file.
656 | */
657 | private function closeDBFFile(): void
658 | {
659 | if ($this->dbfFile === false) {
660 | return;
661 | }
662 |
663 | dbase_close($this->dbfFile);
664 | $this->dbfFile = false;
665 | }
666 |
667 | /**
668 | * Sets error message.
669 | */
670 | public function setError(string $error): void
671 | {
672 | $this->lastError = $error;
673 | }
674 |
675 | /**
676 | * Reads given number of bytes from SHP file.
677 | *
678 | * @param int<0, max> $bytes
679 | */
680 | public function readSHP(int $bytes): string|false
681 | {
682 | if ($this->shpFile === false) {
683 | return false;
684 | }
685 |
686 | return fread($this->shpFile, $bytes);
687 | }
688 |
689 | /**
690 | * Checks whether file is at EOF.
691 | */
692 | public function eofSHP(): bool
693 | {
694 | return feof($this->shpFile);
695 | }
696 |
697 | /**
698 | * Returns shape name.
699 | *
700 | * @psalm-return non-empty-string
701 | */
702 | public function getShapeName(): string
703 | {
704 | return ShapeType::name($this->shapeType);
705 | }
706 |
707 | /**
708 | * Check whether file contains measure data.
709 | *
710 | * For some reason this is distinguished by zero bounding box in the
711 | * specification.
712 | */
713 | public function hasMeasure(): bool
714 | {
715 | // phpcs:ignore SlevomatCodingStandard.Operators.DisallowEqualOperators.DisallowedNotEqualOperator
716 | return $this->boundingBox['mmin'] != 0 || $this->boundingBox['mmax'] != 0;
717 | }
718 | }
719 |
--------------------------------------------------------------------------------
/src/ShapeRecord.php:
--------------------------------------------------------------------------------
1 | .
8 | *
9 | * Copyright 2006-2007 Ovidio
10 | * Copyright 2016 - 2017 Michal Čihař
11 | *
12 | * This program is free software; you can redistribute it and/or
13 | * modify it under the terms of the GNU General Public License
14 | * as published by the Free Software Foundation.
15 | *
16 | * This program is distributed in the hope that it will be useful,
17 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 | * GNU General Public License for more details.
20 | *
21 | * You should have received a copy of the GNU General Public License
22 | * along with this program; if not, you can download one from
23 | * https://www.gnu.org/copyleft/gpl.html.
24 | */
25 |
26 | namespace PhpMyAdmin\ShapeFile;
27 |
28 | use function array_values;
29 | use function count;
30 | use function dbase_add_record;
31 | use function dbase_get_record_with_names;
32 | use function dbase_numrecords;
33 | use function dbase_replace_record;
34 | use function fwrite;
35 | use function in_array;
36 | use function is_array;
37 | use function pack;
38 | use function strlen;
39 |
40 | /**
41 | * ShapeFile record class.
42 | */
43 | class ShapeRecord
44 | {
45 | /** @var resource */
46 | private $shpFile;
47 |
48 | private ShapeFile|null $shapeFile = null;
49 |
50 | private int $size = 0;
51 |
52 | private int $read = 0;
53 |
54 | public int $recordNumber = 0;
55 |
56 | public string $lastError = '';
57 |
58 | /** @var mixed[] */
59 | public array $shpData = [];
60 |
61 | /** @var mixed[] */
62 | public array $dbfData = [];
63 |
64 | public function __construct(public ShapeType $shapeType)
65 | {
66 | }
67 |
68 | /**
69 | * Loads record from files.
70 | *
71 | * @param ShapeFile $shapeFile The ShapeFile object
72 | * @param resource|false $dbfFile Opened DBF file
73 | */
74 | public function loadFromFile(ShapeFile $shapeFile, $dbfFile): void
75 | {
76 | $this->shapeFile = $shapeFile;
77 | $this->loadHeaders();
78 |
79 | /* No header read */
80 | if ($this->read === 0) {
81 | return;
82 | }
83 |
84 | match ($this->shapeType) {
85 | ShapeType::Null => $this->loadNullRecord(),
86 | ShapeType::Point => $this->loadPointRecord(),
87 | ShapeType::PointM => $this->loadPointMRecord(),
88 | ShapeType::PointZ => $this->loadPointZRecord(),
89 | ShapeType::PolyLine => $this->loadPolyLineRecord(),
90 | ShapeType::PolyLineM => $this->loadPolyLineMRecord(),
91 | ShapeType::PolyLineZ => $this->loadPolyLineZRecord(),
92 | ShapeType::Polygon => $this->loadPolygonRecord(),
93 | ShapeType::PolygonM => $this->loadPolygonMRecord(),
94 | ShapeType::PolygonZ => $this->loadPolygonZRecord(),
95 | ShapeType::MultiPoint => $this->loadMultiPointRecord(),
96 | ShapeType::MultiPointM => $this->loadMultiPointMRecord(),
97 | ShapeType::MultiPointZ => $this->loadMultiPointZRecord(),
98 | default => $this->reportInvalidShapeTypeError(),
99 | };
100 |
101 | /* We need to skip rest of the record */
102 | while ($this->read < $this->size) {
103 | $this->loadData('V', 4);
104 | }
105 |
106 | /* Check if we didn't read too much */
107 | if ($this->read !== $this->size) {
108 | $this->reportInvalidShapeTypeError();
109 | }
110 |
111 | if (! ShapeFile::supportsDbase() || $dbfFile === false) {
112 | return;
113 | }
114 |
115 | $this->loadDBFData($dbfFile);
116 | }
117 |
118 | /**
119 | * Saves record to files.
120 | *
121 | * @param resource $shpFile Opened SHP file
122 | * @param resource|false $dbfFile Opened DBF file
123 | * @param int $recordNumber Record number
124 | */
125 | public function saveToFile($shpFile, $dbfFile, int $recordNumber): void
126 | {
127 | $this->shpFile = $shpFile;
128 | $this->recordNumber = $recordNumber;
129 | $this->saveHeaders();
130 |
131 | match ($this->shapeType) {
132 | ShapeType::Null => null, // Nothing to save
133 | ShapeType::Point => $this->savePointRecord(),
134 | ShapeType::PointM => $this->savePointMRecord(),
135 | ShapeType::PointZ => $this->savePointZRecord(),
136 | ShapeType::PolyLine => $this->savePolyLineRecord(),
137 | ShapeType::PolyLineM => $this->savePolyLineMRecord(),
138 | ShapeType::PolyLineZ => $this->savePolyLineZRecord(),
139 | ShapeType::Polygon => $this->savePolygonRecord(),
140 | ShapeType::PolygonM => $this->savePolygonMRecord(),
141 | ShapeType::PolygonZ => $this->savePolygonZRecord(),
142 | ShapeType::MultiPoint => $this->saveMultiPointRecord(),
143 | ShapeType::MultiPointM => $this->saveMultiPointMRecord(),
144 | ShapeType::MultiPointZ => $this->saveMultiPointZRecord(),
145 | default => $this->reportInvalidShapeTypeError(),
146 | };
147 |
148 | if (! ShapeFile::supportsDbase() || $dbfFile === false) {
149 | return;
150 | }
151 |
152 | $this->saveDBFData($dbfFile);
153 | }
154 |
155 | /**
156 | * Updates DBF data to match header.
157 | *
158 | * @param mixed[] $header DBF structure header
159 | */
160 | public function updateDBFInfo(array $header): void
161 | {
162 | $tmp = $this->dbfData;
163 | $this->dbfData = [];
164 | foreach ($header as [$value]) {
165 | $this->dbfData[$value] = $tmp[$value] ?? '';
166 | }
167 | }
168 |
169 | /**
170 | * Reads data.
171 | *
172 | * @param string $type type for unpack()
173 | * @param int<0, max> $count number of bytes
174 | */
175 | private function loadData(string $type, int $count): mixed
176 | {
177 | $data = $this->shapeFile->readSHP($count);
178 | if ($data === false) {
179 | return false;
180 | }
181 |
182 | $this->read += strlen($data);
183 |
184 | return Util::loadData($type, $data);
185 | }
186 |
187 | /**
188 | * Loads metadata header from a file.
189 | */
190 | private function loadHeaders(): void
191 | {
192 | $this->shapeType = ShapeType::Unknown;
193 | $recordNumber = $this->loadData('N', 4);
194 | if ($recordNumber === false) {
195 | return;
196 | }
197 |
198 | $this->recordNumber = (int) $recordNumber;
199 |
200 | // We read the length of the record
201 | $size = $this->loadData('N', 4);
202 | if ($size === false) {
203 | return;
204 | }
205 |
206 | $this->size = ($size * 2) + 8;
207 |
208 | $shapeType = $this->loadData('V', 4);
209 | if ($shapeType === false) {
210 | return;
211 | }
212 |
213 | $this->shapeType = ShapeType::tryFrom((int) $shapeType) ?? ShapeType::Unknown;
214 | }
215 |
216 | /**
217 | * Saves metadata header to a file.
218 | */
219 | private function saveHeaders(): void
220 | {
221 | fwrite($this->shpFile, pack('N', $this->recordNumber));
222 | fwrite($this->shpFile, pack('N', $this->getContentLength()));
223 | fwrite($this->shpFile, pack('V', $this->shapeType->value));
224 | }
225 |
226 | /** @return mixed[] */
227 | private function loadPoint(): array
228 | {
229 | return [
230 | 'x' => $this->loadData('d', 8),
231 | 'y' => $this->loadData('d', 8),
232 | ];
233 | }
234 |
235 | /** @return mixed[] */
236 | private function loadPointM(): array
237 | {
238 | $data = $this->loadPoint();
239 |
240 | $data['m'] = $this->loadData('d', 8);
241 |
242 | return $data;
243 | }
244 |
245 | /** @return mixed[] */
246 | private function loadPointZ(): array
247 | {
248 | $data = $this->loadPoint();
249 |
250 | $data['z'] = $this->loadData('d', 8);
251 | $data['m'] = $this->loadData('d', 8);
252 |
253 | return $data;
254 | }
255 |
256 | /** @param mixed[] $data */
257 | private function savePoint(array $data): void
258 | {
259 | fwrite($this->shpFile, Util::packDouble($data['x']));
260 | fwrite($this->shpFile, Util::packDouble($data['y']));
261 | }
262 |
263 | /** @param mixed[] $data */
264 | private function savePointM(array $data): void
265 | {
266 | fwrite($this->shpFile, Util::packDouble($data['x']));
267 | fwrite($this->shpFile, Util::packDouble($data['y']));
268 | fwrite($this->shpFile, Util::packDouble($data['m']));
269 | }
270 |
271 | /** @param mixed[] $data */
272 | private function savePointZ(array $data): void
273 | {
274 | fwrite($this->shpFile, Util::packDouble($data['x']));
275 | fwrite($this->shpFile, Util::packDouble($data['y']));
276 | fwrite($this->shpFile, Util::packDouble($data['z']));
277 | fwrite($this->shpFile, Util::packDouble($data['m']));
278 | }
279 |
280 | private function loadNullRecord(): void
281 | {
282 | $this->shpData = [];
283 | }
284 |
285 | private function loadPointRecord(): void
286 | {
287 | $this->shpData = $this->loadPoint();
288 | }
289 |
290 | private function loadPointMRecord(): void
291 | {
292 | $this->shpData = $this->loadPointM();
293 | }
294 |
295 | private function loadPointZRecord(): void
296 | {
297 | $this->shpData = $this->loadPointZ();
298 | }
299 |
300 | private function savePointRecord(): void
301 | {
302 | $this->savePoint($this->shpData);
303 | }
304 |
305 | private function savePointMRecord(): void
306 | {
307 | $this->savePointM($this->shpData);
308 | }
309 |
310 | private function savePointZRecord(): void
311 | {
312 | $this->savePointZ($this->shpData);
313 | }
314 |
315 | private function loadBBox(): void
316 | {
317 | $this->shpData['xmin'] = $this->loadData('d', 8);
318 | $this->shpData['ymin'] = $this->loadData('d', 8);
319 | $this->shpData['xmax'] = $this->loadData('d', 8);
320 | $this->shpData['ymax'] = $this->loadData('d', 8);
321 | }
322 |
323 | private function loadMultiPointRecord(): void
324 | {
325 | $this->shpData = [];
326 | $this->loadBBox();
327 |
328 | $this->shpData['numpoints'] = $this->loadData('V', 4);
329 |
330 | for ($i = 0; $i < $this->shpData['numpoints']; ++$i) {
331 | $this->shpData['points'][] = $this->loadPoint();
332 | }
333 | }
334 |
335 | private function loadMultiPointMZRecord(string $type): void
336 | {
337 | /* The m dimension is optional, depends on bounding box data */
338 | if ($type === 'm' && ! $this->shapeFile->hasMeasure()) {
339 | return;
340 | }
341 |
342 | $this->shpData[$type . 'min'] = $this->loadData('d', 8);
343 | $this->shpData[$type . 'max'] = $this->loadData('d', 8);
344 |
345 | for ($i = 0; $i < $this->shpData['numpoints']; ++$i) {
346 | $this->shpData['points'][$i][$type] = $this->loadData('d', 8);
347 | }
348 | }
349 |
350 | private function loadMultiPointMRecord(): void
351 | {
352 | $this->loadMultiPointRecord();
353 |
354 | $this->loadMultiPointMZRecord('m');
355 | }
356 |
357 | private function loadMultiPointZRecord(): void
358 | {
359 | $this->loadMultiPointRecord();
360 |
361 | $this->loadMultiPointMZRecord('z');
362 | $this->loadMultiPointMZRecord('m');
363 | }
364 |
365 | private function saveMultiPointRecord(): void
366 | {
367 | fwrite($this->shpFile, pack(
368 | 'dddd',
369 | $this->shpData['xmin'],
370 | $this->shpData['ymin'],
371 | $this->shpData['xmax'],
372 | $this->shpData['ymax'],
373 | ));
374 |
375 | fwrite($this->shpFile, pack('V', $this->shpData['numpoints']));
376 |
377 | for ($i = 0; $i < $this->shpData['numpoints']; ++$i) {
378 | $this->savePoint($this->shpData['points'][$i]);
379 | }
380 | }
381 |
382 | private function saveMultiPointMZRecord(string $type): void
383 | {
384 | fwrite($this->shpFile, pack('dd', $this->shpData[$type . 'min'], $this->shpData[$type . 'max']));
385 |
386 | for ($i = 0; $i < $this->shpData['numpoints']; ++$i) {
387 | fwrite($this->shpFile, Util::packDouble($this->shpData['points'][$i][$type]));
388 | }
389 | }
390 |
391 | private function saveMultiPointMRecord(): void
392 | {
393 | $this->saveMultiPointRecord();
394 |
395 | $this->saveMultiPointMZRecord('m');
396 | }
397 |
398 | private function saveMultiPointZRecord(): void
399 | {
400 | $this->saveMultiPointRecord();
401 |
402 | $this->saveMultiPointMZRecord('z');
403 | $this->saveMultiPointMZRecord('m');
404 | }
405 |
406 | private function loadPolyLineRecord(): void
407 | {
408 | $this->shpData = [];
409 | $this->loadBBox();
410 |
411 | $this->shpData['numparts'] = $this->loadData('V', 4);
412 | $this->shpData['numpoints'] = $this->loadData('V', 4);
413 |
414 | $numparts = $this->shpData['numparts'];
415 | $numpoints = $this->shpData['numpoints'];
416 |
417 | for ($i = 0; $i < $numparts; ++$i) {
418 | $this->shpData['parts'][$i] = $this->loadData('V', 4);
419 | }
420 |
421 | $part = 0;
422 | for ($i = 0; $i < $numpoints; ++$i) {
423 | if ($part + 1 < $numparts && $i === $this->shpData['parts'][$part + 1]) {
424 | ++$part;
425 | }
426 |
427 | if (
428 | ! isset($this->shpData['parts'][$part]['points'])
429 | || ! is_array($this->shpData['parts'][$part]['points'])
430 | ) {
431 | $this->shpData['parts'][$part] = ['points' => []];
432 | }
433 |
434 | $this->shpData['parts'][$part]['points'][] = $this->loadPoint();
435 | }
436 | }
437 |
438 | private function loadPolyLineMZRecord(string $type): void
439 | {
440 | /* The m dimension is optional, depends on bounding box data */
441 | if ($type === 'm' && ! $this->shapeFile->hasMeasure()) {
442 | return;
443 | }
444 |
445 | $this->shpData[$type . 'min'] = $this->loadData('d', 8);
446 | $this->shpData[$type . 'max'] = $this->loadData('d', 8);
447 |
448 | $numparts = $this->shpData['numparts'];
449 | $numpoints = $this->shpData['numpoints'];
450 |
451 | $part = 0;
452 | for ($i = 0; $i < $numpoints; ++$i) {
453 | if ($part + 1 < $numparts && $i === $this->shpData['parts'][$part + 1]) {
454 | ++$part;
455 | }
456 |
457 | $this->shpData['parts'][$part]['points'][$i][$type] = $this->loadData('d', 8);
458 | }
459 | }
460 |
461 | private function loadPolyLineMRecord(): void
462 | {
463 | $this->loadPolyLineRecord();
464 |
465 | $this->loadPolyLineMZRecord('m');
466 | }
467 |
468 | private function loadPolyLineZRecord(): void
469 | {
470 | $this->loadPolyLineRecord();
471 |
472 | $this->loadPolyLineMZRecord('z');
473 | $this->loadPolyLineMZRecord('m');
474 | }
475 |
476 | private function savePolyLineRecord(): void
477 | {
478 | fwrite($this->shpFile, pack(
479 | 'dddd',
480 | $this->shpData['xmin'],
481 | $this->shpData['ymin'],
482 | $this->shpData['xmax'],
483 | $this->shpData['ymax'],
484 | ));
485 |
486 | fwrite($this->shpFile, pack('VV', $this->shpData['numparts'], $this->shpData['numpoints']));
487 |
488 | $partIndex = 0;
489 | for ($i = 0; $i < $this->shpData['numparts']; ++$i) {
490 | fwrite($this->shpFile, pack('V', $partIndex));
491 | $partIndex += count($this->shpData['parts'][$i]['points']);
492 | }
493 |
494 | foreach ($this->shpData['parts'] as $partData) {
495 | foreach ($partData['points'] as $pointData) {
496 | $this->savePoint($pointData);
497 | }
498 | }
499 | }
500 |
501 | private function savePolyLineMZRecord(string $type): void
502 | {
503 | fwrite($this->shpFile, pack('dd', $this->shpData[$type . 'min'], $this->shpData[$type . 'max']));
504 |
505 | foreach ($this->shpData['parts'] as $partData) {
506 | foreach ($partData['points'] as $pointData) {
507 | fwrite($this->shpFile, Util::packDouble($pointData[$type]));
508 | }
509 | }
510 | }
511 |
512 | private function savePolyLineMRecord(): void
513 | {
514 | $this->savePolyLineRecord();
515 |
516 | $this->savePolyLineMZRecord('m');
517 | }
518 |
519 | private function savePolyLineZRecord(): void
520 | {
521 | $this->savePolyLineRecord();
522 |
523 | $this->savePolyLineMZRecord('z');
524 | $this->savePolyLineMZRecord('m');
525 | }
526 |
527 | private function loadPolygonRecord(): void
528 | {
529 | $this->loadPolyLineRecord();
530 | }
531 |
532 | private function loadPolygonMRecord(): void
533 | {
534 | $this->loadPolyLineMRecord();
535 | }
536 |
537 | private function loadPolygonZRecord(): void
538 | {
539 | $this->loadPolyLineZRecord();
540 | }
541 |
542 | private function savePolygonRecord(): void
543 | {
544 | $this->savePolyLineRecord();
545 | }
546 |
547 | private function savePolygonMRecord(): void
548 | {
549 | $this->savePolyLineMRecord();
550 | }
551 |
552 | private function savePolygonZRecord(): void
553 | {
554 | $this->savePolyLineZRecord();
555 | }
556 |
557 | /** @param mixed[] $point */
558 | private function adjustBBox(array $point): void
559 | {
560 | // Adjusts bounding box based on point
561 | foreach (['x', 'y', 'z', 'm'] as $direction) {
562 | if (! isset($point[$direction])) {
563 | continue;
564 | }
565 |
566 | $min = $direction . 'min';
567 | $max = $direction . 'max';
568 | if (! isset($this->shpData[$min]) || ($this->shpData[$min] > $point[$direction])) {
569 | $this->shpData[$min] = $point[$direction];
570 | }
571 |
572 | if (isset($this->shpData[$max]) && ($this->shpData[$max] >= $point[$direction])) {
573 | continue;
574 | }
575 |
576 | $this->shpData[$max] = $point[$direction];
577 | }
578 | }
579 |
580 | /**
581 | * Adjust point and bounding box when adding point.
582 | * Sets dimension to 0 if not set.
583 | *
584 | * @param mixed[] $point Point data
585 | *
586 | * @return mixed[] Fixed point data
587 | */
588 | private function adjustPoint(array $point): array
589 | {
590 | if (in_array($this->shapeType, ShapeType::MEASURED_TYPES, true)) {
591 | $point['m'] ??= 0.0;
592 | }
593 |
594 | if (in_array($this->shapeType, ShapeType::TYPES_WITH_Z, true)) {
595 | $point['z'] ??= 0.0;
596 | }
597 |
598 | return $point;
599 | }
600 |
601 | /**
602 | * Adds point to a record.
603 | *
604 | * @param mixed[] $point Point data
605 | * @param int $partIndex Part index
606 | */
607 | public function addPoint(array $point, int $partIndex = 0): void
608 | {
609 | $point = $this->adjustPoint($point);
610 | switch ($this->shapeType) {
611 | case ShapeType::Null:
612 | //Don't add anything
613 | return;
614 |
615 | case ShapeType::Point:
616 | case ShapeType::PointZ:
617 | case ShapeType::PointM:
618 | //Substitutes the value of the current point
619 | $this->shpData = $point;
620 | break;
621 | case ShapeType::PolyLine:
622 | case ShapeType::Polygon:
623 | case ShapeType::PolyLineZ:
624 | case ShapeType::PolygonZ:
625 | case ShapeType::PolyLineM:
626 | case ShapeType::PolygonM:
627 | //Adds a new point to the selected part
628 | $this->shpData['parts'][$partIndex]['points'][] = $point;
629 | $this->shpData['numparts'] = count($this->shpData['parts']);
630 | $this->shpData['numpoints'] = 1 + ($this->shpData['numpoints'] ?? 0);
631 | break;
632 | case ShapeType::MultiPoint:
633 | case ShapeType::MultiPointZ:
634 | case ShapeType::MultiPointM:
635 | //Adds a new point
636 | $this->shpData['points'][] = $point;
637 | $this->shpData['numpoints'] = 1 + ($this->shpData['numpoints'] ?? 0);
638 | break;
639 | default:
640 | $this->reportInvalidShapeTypeError();
641 |
642 | return;
643 | }
644 |
645 | $this->adjustBBox($point);
646 | }
647 |
648 | /**
649 | * Deletes point from a record.
650 | *
651 | * @param int $pointIndex Point index
652 | * @param int $partIndex Part index
653 | */
654 | public function deletePoint(int $pointIndex = 0, int $partIndex = 0): void
655 | {
656 | switch ($this->shapeType) {
657 | case ShapeType::Null:
658 | //Don't delete anything
659 | break;
660 | case ShapeType::Point:
661 | case ShapeType::PointZ:
662 | case ShapeType::PointM:
663 | //Sets the value of the point to zero
664 | $this->shpData['x'] = 0.0;
665 | $this->shpData['y'] = 0.0;
666 | if (in_array($this->shapeType, [ShapeType::PointZ, ShapeType::PointM], true)) {
667 | $this->shpData['m'] = 0.0;
668 | }
669 |
670 | if ($this->shapeType === ShapeType::PointZ) {
671 | $this->shpData['z'] = 0.0;
672 | }
673 |
674 | break;
675 | case ShapeType::PolyLine:
676 | case ShapeType::Polygon:
677 | case ShapeType::PolyLineZ:
678 | case ShapeType::PolygonZ:
679 | case ShapeType::PolyLineM:
680 | case ShapeType::PolygonM:
681 | //Deletes the point from the selected part, if exists
682 | if (
683 | isset($this->shpData['parts'][$partIndex])
684 | && isset($this->shpData['parts'][$partIndex]['points'][$pointIndex])
685 | ) {
686 | $count = count($this->shpData['parts'][$partIndex]['points']) - 1;
687 | for ($i = $pointIndex; $i < $count; ++$i) {
688 | $point = $this->shpData['parts'][$partIndex]['points'][$i + 1];
689 | $this->shpData['parts'][$partIndex]['points'][$i] = $point;
690 | }
691 |
692 | $count = count($this->shpData['parts'][$partIndex]['points']) - 1;
693 | unset($this->shpData['parts'][$partIndex]['points'][$count]);
694 |
695 | $this->shpData['numparts'] = count($this->shpData['parts']);
696 | --$this->shpData['numpoints'];
697 | }
698 |
699 | break;
700 | case ShapeType::MultiPoint:
701 | case ShapeType::MultiPointZ:
702 | case ShapeType::MultiPointM:
703 | //Deletes the point, if exists
704 | if (isset($this->shpData['points'][$pointIndex])) {
705 | $count = count($this->shpData['points']) - 1;
706 | for ($i = $pointIndex; $i < $count; ++$i) {
707 | $this->shpData['points'][$i] = $this->shpData['points'][$i + 1];
708 | }
709 |
710 | unset($this->shpData['points'][count($this->shpData['points']) - 1]);
711 |
712 | --$this->shpData['numpoints'];
713 | }
714 |
715 | break;
716 | default:
717 | $this->reportInvalidShapeTypeError();
718 | break;
719 | }
720 | }
721 |
722 | /**
723 | * Returns length of content.
724 | */
725 | public function getContentLength(): int|null
726 | {
727 | // The content length for a record is the length of the record contents section measured in 16-bit words.
728 | // one coordinate makes 4 16-bit words (64 bit double)
729 | switch ($this->shapeType) {
730 | case ShapeType::Null:
731 | $result = 0;
732 | break;
733 | case ShapeType::Point:
734 | $result = 10;
735 | break;
736 | case ShapeType::PointM:
737 | $result = 10 + 4;
738 | break;
739 | case ShapeType::PointZ:
740 | $result = 10 + 8;
741 | break;
742 | case ShapeType::PolyLine:
743 | case ShapeType::Polygon:
744 | $count = count($this->shpData['parts']);
745 | $result = 22 + 2 * $count;
746 | for ($i = 0; $i < $count; ++$i) {
747 | $result += 8 * count($this->shpData['parts'][$i]['points']);
748 | }
749 |
750 | break;
751 | case ShapeType::PolyLineM:
752 | case ShapeType::PolygonM:
753 | $count = count($this->shpData['parts']);
754 | $result = 22 + (2 * 4) + 2 * $count;
755 | for ($i = 0; $i < $count; ++$i) {
756 | $result += (8 + 4) * count($this->shpData['parts'][$i]['points']);
757 | }
758 |
759 | break;
760 | case ShapeType::PolyLineZ:
761 | case ShapeType::PolygonZ:
762 | $count = count($this->shpData['parts']);
763 | $result = 22 + (4 * 4) + 2 * $count;
764 | for ($i = 0; $i < $count; ++$i) {
765 | $result += (8 + 8) * count($this->shpData['parts'][$i]['points']);
766 | }
767 |
768 | break;
769 | case ShapeType::MultiPoint:
770 | $result = 20 + 8 * count($this->shpData['points']);
771 | break;
772 | case ShapeType::MultiPointM:
773 | $result = 20 + (2 * 4) + (8 + 4) * count($this->shpData['points']);
774 | break;
775 | case ShapeType::MultiPointZ:
776 | $result = 20 + (4 * 4) + (8 + 8) * count($this->shpData['points']);
777 | break;
778 | default:
779 | $result = null;
780 | $this->reportInvalidShapeTypeError();
781 | break;
782 | }
783 |
784 | return $result;
785 | }
786 |
787 | /** @param resource $dbfFile Opened DBF file */
788 | private function loadDBFData($dbfFile): void
789 | {
790 | $this->dbfData = @dbase_get_record_with_names($dbfFile, $this->recordNumber);
791 | unset($this->dbfData['deleted']);
792 | }
793 |
794 | /** @param resource $dbfFile */
795 | private function saveDBFData($dbfFile): void
796 | {
797 | if ($this->dbfData === []) {
798 | return;
799 | }
800 |
801 | unset($this->dbfData['deleted']);
802 | if ($this->recordNumber <= dbase_numrecords($dbfFile)) {
803 | if (! dbase_replace_record($dbfFile, array_values($this->dbfData), $this->recordNumber)) {
804 | $this->setError("I wasn't possible to update the information in the DBF file.");
805 | }
806 | } elseif (! dbase_add_record($dbfFile, array_values($this->dbfData))) {
807 | $this->setError("I wasn't possible to add the information to the DBF file.");
808 | }
809 | }
810 |
811 | /**
812 | * Sets error message.
813 | */
814 | public function setError(string $error): void
815 | {
816 | $this->lastError = $error;
817 | }
818 |
819 | /**
820 | * Returns shape name.
821 | *
822 | * @psalm-return non-empty-string
823 | */
824 | public function getShapeName(): string
825 | {
826 | return ShapeType::name($this->shapeType);
827 | }
828 |
829 | private function reportInvalidShapeTypeError(): void
830 | {
831 | $this->setError('Invalid Shape type.');
832 | }
833 | }
834 |
--------------------------------------------------------------------------------
/src/ShapeType.php:
--------------------------------------------------------------------------------
1 | value => 'Unknown Shape',
56 | self::Null->value => 'Null Shape',
57 | self::Point->value => 'Point',
58 | self::PolyLine->value => 'PolyLine',
59 | self::Polygon->value => 'Polygon',
60 | self::MultiPoint->value => 'MultiPoint',
61 | self::PointZ->value => 'PointZ',
62 | self::PolyLineZ->value => 'PolyLineZ',
63 | self::PolygonZ->value => 'PolygonZ',
64 | self::MultiPointZ->value => 'MultiPointZ',
65 | self::PointM->value => 'PointM',
66 | self::PolyLineM->value => 'PolyLineM',
67 | self::PolygonM->value => 'PolygonM',
68 | self::MultiPointM->value => 'MultiPointM',
69 | self::MultiPatch->value => 'MultiPatch',
70 | ];
71 |
72 | /** @psalm-return non-empty-string */
73 | public static function name(ShapeType $shapeType): string
74 | {
75 | return self::NAMES[$shapeType->value];
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/src/Util.php:
--------------------------------------------------------------------------------
1 | .
8 | *
9 | * Copyright 2006-2007 Ovidio
10 | * Copyright 2016 - 2017 Michal Čihař
11 | *
12 | * This program is free software; you can redistribute it and/or
13 | * modify it under the terms of the GNU General Public License
14 | * as published by the Free Software Foundation.
15 | *
16 | * This program is distributed in the hope that it will be useful,
17 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 | * GNU General Public License for more details.
20 | *
21 | * You should have received a copy of the GNU General Public License
22 | * along with this program; if not, you can download one from
23 | * https://www.gnu.org/copyleft/gpl.html.
24 | */
25 |
26 | namespace PhpMyAdmin\ShapeFile;
27 |
28 | use function current;
29 | use function pack;
30 | use function strrev;
31 | use function unpack;
32 |
33 | class Util
34 | {
35 | private static bool|null $littleEndian = null;
36 |
37 | /**
38 | * Reads data.
39 | *
40 | * @param string $type type for unpack()
41 | * @param string|false $data Data to process
42 | */
43 | public static function loadData(string $type, string|false $data): mixed
44 | {
45 | if ($data === false || $data === '') {
46 | return false;
47 | }
48 |
49 | $tmp = unpack($type, $data);
50 |
51 | return $tmp === false ? false : current($tmp);
52 | }
53 |
54 | /**
55 | * Encodes double value to correct endianity.
56 | */
57 | public static function packDouble(float $value): string
58 | {
59 | $bin = pack('d', $value);
60 |
61 | if (self::$littleEndian === null) {
62 | self::$littleEndian = (pack('L', 1) === pack('V', 1));
63 | }
64 |
65 | if (self::$littleEndian) {
66 | return $bin;
67 | }
68 |
69 | return strrev($bin);
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/tests/ShapeFileTest.php:
--------------------------------------------------------------------------------
1 | .
8 | *
9 | * Copyright 2006-2007 Ovidio
10 | * Copyright 2016 - 2017 Michal Čihař
11 | *
12 | * This program is free software; you can redistribute it and/or
13 | * modify it under the terms of the GNU General Public License
14 | * as published by the Free Software Foundation.
15 | *
16 | * This program is distributed in the hope that it will be useful,
17 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 | * GNU General Public License for more details.
20 | *
21 | * You should have received a copy of the GNU General Public License
22 | * along with this program; if not, you can download one from
23 | * https://www.gnu.org/copyleft/gpl.html.
24 | */
25 |
26 | namespace PhpMyAdminTest\ShapeFile;
27 |
28 | use PhpMyAdmin\ShapeFile\ShapeFile;
29 | use PhpMyAdmin\ShapeFile\ShapeRecord;
30 | use PhpMyAdmin\ShapeFile\ShapeType;
31 | use PHPUnit\Framework\TestCase;
32 |
33 | use function count;
34 |
35 | class ShapeFileTest extends TestCase
36 | {
37 | /**
38 | * Tests loading of a file.
39 | *
40 | * @param string $filename Name of file
41 | * @param int $records Expected number of records
42 | * @param int|null $parts Expected number of parts in first record
43 | *
44 | * @dataProvider provideFiles
45 | */
46 | public function testLoad(string $filename, int $records, int|null $parts): void
47 | {
48 | $shp = new ShapeFile(ShapeType::Point);
49 | $shp->loadFromFile($filename);
50 | self::assertEquals('', $shp->lastError);
51 | self::assertEquals($records, count($shp->records));
52 | if ($parts === null) {
53 | return;
54 | }
55 |
56 | self::assertEquals($parts, count($shp->records[0]->shpData['parts']));
57 | }
58 |
59 | /**
60 | * Data provider for file loading tests.
61 | *
62 | * @psalm-return list
63 | */
64 | public static function provideFiles(): array
65 | {
66 | return [
67 | [
68 | 'data/capitals.*',
69 | 652,
70 | null,
71 | ],
72 | [
73 | 'data/mexico.*',
74 | 32,
75 | 3,
76 | ],
77 | [
78 | 'data/Czech_Republic_AL2.*',
79 | 1,
80 | 1,
81 | ],
82 | [
83 | 'data/w001n05f.*',
84 | 16,
85 | 1,
86 | ],
87 | [
88 | 'data/bc_hospitals.*',
89 | 44,
90 | null,
91 | ],
92 | [
93 | 'data/multipoint.*',
94 | 312,
95 | null,
96 | ],
97 | ];
98 | }
99 |
100 | /**
101 | * Test error handling in loader.
102 | *
103 | * @param string $filename name to load
104 | *
105 | * @dataProvider provideErrorFiles
106 | */
107 | public function testLoadError(string $filename): void
108 | {
109 | $shp = new ShapeFile(ShapeType::Point);
110 | $shp->loadFromFile($filename);
111 | self::assertNotEquals('', $shp->lastError);
112 | }
113 |
114 | /**
115 | * Test load an empty file name
116 | */
117 | public function testLoadEmptyFilename(): void
118 | {
119 | $shp = new ShapeFile(ShapeType::Point);
120 | $shp->loadFromFile('');
121 | if (ShapeFile::supportsDbase()) {
122 | self::assertEquals('It wasn\'t possible to find the DBase file ""', $shp->lastError);
123 |
124 | return;
125 | }
126 |
127 | self::assertEquals('Not a SHP file (file code mismatch)', $shp->lastError);
128 | }
129 |
130 | /**
131 | * Test to call getDBFHeader on a non loaded file
132 | */
133 | public function testGetDBFHeader(): void
134 | {
135 | $shp = new ShapeFile(ShapeType::Point);
136 | self::assertNull($shp->getDBFHeader());
137 | }
138 |
139 | /**
140 | * Data provider for file loading error tests.
141 | *
142 | * @psalm-return list
143 | */
144 | public static function provideErrorFiles(): array
145 | {
146 | $result = [
147 | ['data/no-shp.*'],
148 | ['data/missing.*'],
149 | ['data/invalid-shp.*'],
150 | ];
151 |
152 | if (ShapeFile::supportsDbase()) {
153 | $result[] = ['data/no-dbf.*'];
154 | $result[] = ['data/invalid-dbf.*'];
155 | }
156 |
157 | return $result;
158 | }
159 |
160 | /**
161 | * Creates test data.
162 | */
163 | private function createTestData(): void
164 | {
165 | $shp = new ShapeFile(ShapeType::Point);
166 |
167 | $record0 = new ShapeRecord(ShapeType::Point);
168 | $record0->addPoint(['x' => 482131.764567, 'y' => 2143634.39608]);
169 |
170 | $record1 = new ShapeRecord(ShapeType::PointZ);
171 | $record1->addPoint(['x' => 472131.764567, 'y' => 2143634.39608, 'z' => 220, 'm' => 120]);
172 |
173 | $record2 = new ShapeRecord(ShapeType::PointM);
174 | $record2->addPoint(['x' => 492131.764567, 'y' => 2143634.39608, 'z' => 150, 'm' => 80]);
175 |
176 | $record3 = new ShapeRecord(ShapeType::PolyLine);
177 | $record3->addPoint(['x' => 482131.764567, 'y' => 2143634.39608], 0);
178 | $record3->addPoint(['x' => 482132.764567, 'y' => 2143635.39608], 0);
179 | $record3->addPoint(['x' => 482131.764567, 'y' => 2143635.39608], 1);
180 | $record3->addPoint(['x' => 482132.764567, 'y' => 2143636.39608], 1);
181 |
182 | $shp->addRecord($record0);
183 | $shp->addRecord($record1);
184 | $shp->addRecord($record2);
185 | $shp->addRecord($record3);
186 |
187 | $shp->setDBFHeader(
188 | [
189 | [
190 | 'ID',
191 | 'N',
192 | 8,
193 | 0,
194 | ],
195 | [
196 | 'DESC',
197 | 'C',
198 | 50,
199 | 0,
200 | ],
201 | ],
202 | );
203 |
204 | $shp->records[0]->dbfData['ID'] = '1';
205 | $shp->records[0]->dbfData['DESC'] = 'AAAAAAAAA';
206 |
207 | $shp->records[1]->dbfData['ID'] = '2';
208 | $shp->records[1]->dbfData['DESC'] = 'BBBBBBBBBB';
209 |
210 | $shp->records[2]->dbfData['ID'] = '3';
211 | $shp->records[2]->dbfData['DESC'] = 'CCCCCCCCCCC';
212 |
213 | $shp->records[3]->dbfData['ID'] = '4';
214 | $shp->records[3]->dbfData['DESC'] = 'CCCCCCCCCCC';
215 |
216 | $shp->saveToFile('./data/test_shape.*');
217 | }
218 |
219 | /**
220 | * Tests creating file.
221 | */
222 | public function testCreate(): void
223 | {
224 | if (! ShapeFile::supportsDbase()) {
225 | self::markTestSkipped('dbase extension missing');
226 | }
227 |
228 | $this->createTestData();
229 |
230 | $shp = new ShapeFile(ShapeType::Point);
231 | $shp->loadFromFile('./data/test_shape.*');
232 | self::assertEquals(4, count($shp->records));
233 | }
234 |
235 | /**
236 | * Tests removing record from a file.
237 | */
238 | public function testDelete(): void
239 | {
240 | if (! ShapeFile::supportsDbase()) {
241 | self::markTestSkipped('dbase extension missing');
242 | }
243 |
244 | $this->createTestData();
245 |
246 | $shp = new ShapeFile(ShapeType::Point);
247 | $shp->loadFromFile('./data/test_shape.*');
248 | $shp->deleteRecord(1);
249 | $shp->saveToFile();
250 | self::assertEquals(3, count($shp->records));
251 |
252 | $shp = new ShapeFile(ShapeType::Point);
253 | $shp->loadFromFile('./data/test_shape.*');
254 | self::assertEquals(3, count($shp->records));
255 | }
256 |
257 | /**
258 | * Test adding record to a file.
259 | */
260 | public function testAdd(): void
261 | {
262 | if (! ShapeFile::supportsDbase()) {
263 | self::markTestSkipped('dbase extension missing');
264 | }
265 |
266 | $this->createTestData();
267 |
268 | $shp = new ShapeFile(ShapeType::Point);
269 | $shp->loadFromFile('./data/test_shape.*');
270 |
271 | $record0 = new ShapeRecord(ShapeType::Point);
272 | $record0->addPoint(['x' => 482131.764567, 'y' => 2143634.39608]);
273 |
274 | $shp->addRecord($record0);
275 | $shp->records[4]->dbfData['ID'] = '4';
276 | $shp->records[4]->dbfData['DESC'] = 'CCCCCCCCCCC';
277 |
278 | $shp->saveToFile();
279 | self::assertEquals(5, count($shp->records));
280 |
281 | $shp = new ShapeFile(ShapeType::Point);
282 | $shp->loadFromFile('./data/test_shape.*');
283 | self::assertEquals(5, count($shp->records));
284 | }
285 |
286 | /**
287 | * Tests saving without DBF.
288 | */
289 | public function testSaveNoDBF(): void
290 | {
291 | $shp = new ShapeFile(ShapeType::Point);
292 | $shp->saveToFile('./data/test_nodbf.*');
293 |
294 | self::assertFileDoesNotExist('./data/test_nodbf.dbf');
295 | }
296 |
297 | /**
298 | * Test shape naming.
299 | */
300 | public function testShapeName(): void
301 | {
302 | $obj = new ShapeRecord(ShapeType::Point);
303 | self::assertEquals('Point', $obj->getShapeName());
304 | $obj = new ShapeFile(ShapeType::Point);
305 | self::assertEquals('Point', $obj->getShapeName());
306 | $obj = new ShapeRecord(ShapeType::Null);
307 | self::assertEquals('Null Shape', $obj->getShapeName());
308 | $obj = new ShapeRecord(ShapeType::Unknown);
309 | self::assertEquals('Unknown Shape', $obj->getShapeName());
310 | }
311 |
312 | /**
313 | * Test shapes save/load round-robin.
314 | *
315 | * @psalm-param list $points
316 | *
317 | * @dataProvider shapesProvider
318 | */
319 | public function testShapeSaveLoad(ShapeType $shapeType, array $points): void
320 | {
321 | $filename = './data/test_shape-' . $shapeType->value . '.*';
322 | $shp = new ShapeFile($shapeType);
323 | $shp->setDBFHeader([['ID', 'N', 19, 0], ['DESC', 'C', 14, 0]]);
324 |
325 | $record0 = new ShapeRecord($shapeType);
326 |
327 | foreach ($points as $point) {
328 | $record0->addPoint($point[0], $point[1]);
329 | }
330 |
331 | $shp->addRecord($record0);
332 |
333 | $shp->saveToFile($filename);
334 |
335 | $shp2 = new ShapeFile($shapeType);
336 | $shp2->loadFromFile($filename);
337 |
338 | self::assertEquals(count($shp->records), count($shp2->records));
339 |
340 | $record = $shp->records[0];
341 | $record2 = $shp2->records[0];
342 |
343 | $items = ['numparts', 'numpoints'];
344 | foreach ($items as $item) {
345 | if (! isset($record->shpData[$item])) {
346 | continue;
347 | }
348 |
349 | self::assertEquals($record->shpData[$item], $record2->shpData[$item]);
350 | }
351 |
352 | /* Test deletion works */
353 | $record->deletePoint();
354 | }
355 |
356 | /**
357 | * Data provider for save/load testing.
358 | *
359 | * @psalm-return list}>
360 | */
361 | public static function shapesProvider(): array
362 | {
363 | $pointsForPointType = [[['x' => 10, 'y' => 20], 0]];
364 |
365 | $pointsForPolyLineType = [
366 | [['x' => 10, 'y' => 20], 0],
367 | [['x' => 20, 'y' => 20], 0],
368 | [['x' => 20, 'y' => 20], 1],
369 | [['x' => 20, 'y' => 10], 1],
370 | ];
371 |
372 | $pointsForPolygonType = [
373 | [['x' => 10, 'y' => 20], 0],
374 | [['x' => 20, 'y' => 20], 0],
375 | [['x' => 20, 'y' => 20], 1],
376 | [['x' => 20, 'y' => 10], 1],
377 | [['x' => 20, 'y' => 10], 2],
378 | [['x' => 10, 'y' => 20], 2],
379 | ];
380 |
381 | $pointsForMultiPointType = [
382 | [['x' => 10, 'y' => 20], 0],
383 | [['x' => 20, 'y' => 20], 0],
384 | [['x' => 20, 'y' => 10], 0],
385 | ];
386 |
387 | return [
388 | [ShapeType::Point, $pointsForPointType],
389 | [ShapeType::PolyLine, $pointsForPolyLineType],
390 | [ShapeType::Polygon, $pointsForPolygonType],
391 | [ShapeType::MultiPoint, $pointsForMultiPointType],
392 | [ShapeType::PointZ, $pointsForPointType],
393 | [ShapeType::PolyLineZ, $pointsForPolyLineType],
394 | [ShapeType::PolygonZ, $pointsForPolygonType],
395 | [ShapeType::MultiPointZ, $pointsForMultiPointType],
396 | [ShapeType::PointM, $pointsForPointType],
397 | [ShapeType::PolyLineM, $pointsForPolyLineType],
398 | [ShapeType::PolygonM, $pointsForPolygonType],
399 | [ShapeType::MultiPointM, $pointsForMultiPointType],
400 | ];
401 | }
402 |
403 | public function testSearch(): void
404 | {
405 | $shp = new ShapeFile(ShapeType::Null);
406 | $shp->loadFromFile('data/capitals.*');
407 | /* Nonexisting entry or no dbase support */
408 | self::assertEquals(
409 | -1,
410 | $shp->getIndexFromDBFData('CNTRY_NAME', 'nonexisting'),
411 | );
412 | if (! ShapeFile::supportsDbase()) {
413 | return;
414 | }
415 |
416 | self::assertEquals(
417 | 218,
418 | $shp->getIndexFromDBFData('CNTRY_NAME', 'Czech Republic'),
419 | );
420 | }
421 |
422 | public function testAllowsNoDbf(): void
423 | {
424 | if (! ShapeFile::supportsDbase()) {
425 | self::markTestSkipped();
426 | }
427 |
428 | $shp = new ShapeFile(ShapeType::Null);
429 | $shp->setAllowNoDbf(true);
430 | self::assertTrue($shp->loadFromFile('data/no-dbf.*'));
431 | }
432 | }
433 |
--------------------------------------------------------------------------------
/tests/UtilTest.php:
--------------------------------------------------------------------------------
1 | .
8 | *
9 | * Copyright 2016 - 2017 Michal Čihař
10 | *
11 | * This program is free software; you can redistribute it and/or
12 | * modify it under the terms of the GNU General Public License
13 | * as published by the Free Software Foundation.
14 | *
15 | * This program is distributed in the hope that it will be useful,
16 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 | * GNU General Public License for more details.
19 | *
20 | * You should have received a copy of the GNU General Public License
21 | * along with this program; if not, you can download one from
22 | * https://www.gnu.org/copyleft/gpl.html.
23 | */
24 |
25 | namespace PhpMyAdminTest\ShapeFile;
26 |
27 | use PhpMyAdmin\ShapeFile\Util;
28 | use PHPUnit\Framework\TestCase;
29 |
30 | class UtilTest extends TestCase
31 | {
32 | /**
33 | * Test data loading.
34 | *
35 | * @param string $type Data type
36 | * @param string|false $data Data to parse
37 | * @param mixed $expected Expected result
38 | *
39 | * @dataProvider data
40 | */
41 | public function testLoadData(string $type, string|false $data, mixed $expected): void
42 | {
43 | self::assertEquals(
44 | $expected,
45 | Util::loadData($type, $data),
46 | );
47 | }
48 |
49 | /**
50 | * Data provider for loadData tests.
51 | *
52 | * @psalm-return list
53 | */
54 | public static function data(): array
55 | {
56 | return [
57 | [
58 | 'N',
59 | '',
60 | false,
61 | ],
62 | [
63 | 'N',
64 | false,
65 | false,
66 | ],
67 | [
68 | 'N',
69 | "\x01\x02\x03\x04",
70 | 0x01020304,
71 | ],
72 | ];
73 | }
74 | }
75 |
--------------------------------------------------------------------------------