* Read and write functionality for metadata.
--- /dev/null
+Andy Street <andy@street.me.uk>
--- /dev/null
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License along
+ with this program; if not, write to the Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+ Gnomovision version 69, Copyright (C) year name of author
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+ <signature of Ty Coon>, 1 April 1989
+ Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs. If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<gpx version="1.0" creator="libgpx" xsi:schemaLocation="http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd" xmlns="http://www.topografix.com/GPX/1/0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <name>full-1.0</name>
+ <desc>This is a sample file containing all parts of the GPX 1.0 specification supported by libgpx.</desc>
+ <author>John Doe</author>
+ <email>john.doe@example.com</email>
+ <url>https://www.example.com/</url>
+ <urlname>Example Inc.</urlname>
+ <time>2018-11-25T10:07:47Z</time>
+ <keywords>Example, GPX</keywords>
+ <bounds minlat="-1.234" minlon="-1.234" maxlat="1.234" maxlon="1.234"/>
+</gpx>
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>\r
+<gpx version="1.1" creator="libgpx" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd" xmlns="http://www.topografix.com/GPX/1/1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <metadata>\r
+ <name>full-1.1</name>\r
+ <desc>This is a sample file containing all parts of the GPX 1.1 specification supported by libgpx.</desc>\r
+ <author>\r
+ <name>John Doe</name>\r
+ <email id="john.doe" domain="example.com"/>\r
+ <link href="https://www.example.com/~john.doe/">\r
+ <text>John Doe's Homepage</text>\r
+ <type>text/html</type>\r
+ </link>\r
+ </author>\r
+ <copyright author="John Doe">\r
+ <year>2018</year>\r
+ <license>https://creativecommons.org/publicdomain/zero/1.0/</license>\r
+ </copyright>\r
+ <link href="https://www.example.com/">\r
+ <text>Example Inc.</text>\r
+ <type>text/html</type>\r
+ </link>\r
+ <time>2018-11-25T10:07:47Z</time>\r
+ <keywords>Example, GPX</keywords>\r
+ <bounds minlat="-1.234" minlon="-1.234" maxlat="1.234" maxlon="1.234"/>\r
+ </metadata>\r
+</gpx>\r
--- /dev/null
+<?xml version="1.0" encoding="UTF-8" ?>
+<phpdoc>
+ <title>GPX</title>
+ <parser>
+ <target>/tmp/phpdoc</target>
+ <visibility>public</visibility>
+ </parser>
+ <transformer>
+ <target>docs/phpdoc</target>
+ </transformer>
+ <transformations>
+ <template name="clean" />
+ </transformations>
+ <files>
+ <directory>src</directory>
+ </files>
+</phpdoc>
--- /dev/null
+<?php
+/**
+ * bounds.php
+ *
+ * Copyright 2018 Andy Street <andy@street.me.uk>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
+ * MA 02110-1301, USA.
+ *
+ *
+ */
+
+namespace libgpx;
+
+/**
+ * A 2D rectangular bounding box.
+ *
+ * @author Andy Street <andy@street.me.uk>
+ */
+class Bounds
+{
+
+ /**
+ * Minimum latitude.
+ *
+ * @var float
+ */
+ protected $minlat;
+
+ /**
+ * Minimum longitude.
+ *
+ * @var float
+ */
+ protected $minlon;
+
+ /**
+ * Maximum latitude.
+ *
+ * @var float
+ */
+ protected $maxlat;
+
+ /**
+ * Maxumum longitude.
+ *
+ * @var float
+ */
+ protected $maxlon;
+
+ /**
+ * Create a new bounding box.
+ *
+ * @param float $minlat Minimum latitude.
+ * @param float $minlon Minimum longitude.
+ * @param float $maxlat Maximum latitude.
+ * @param float $maxlon Maximum longitude.
+ */
+ public function __construct(
+ float $minlat,
+ float $minlon,
+ float $maxlat,
+ float $maxlon
+ ) {
+ $this->minlat = $minlat;
+ $this->minlon = $minlon;
+ $this->maxlat = $maxlat;
+ $this->maxlon = $maxlon;
+ }
+
+ /**
+ * Fetch minimum latitude.
+ *
+ * @return float
+ */
+ public function getMinLat()
+ {
+ return $this->minlat;
+ }
+
+ /**
+ * Fetch minimum longitude.
+ *
+ * @return float
+ */
+ public function getMinLon()
+ {
+ return $this->minlon;
+ }
+
+ /**
+ * Fetch maximum latitude.
+ *
+ * @return float
+ */
+ public function getMaxLat()
+ {
+ return $this->maxlat;
+ }
+
+ /**
+ * Fetch maximum longitude.
+ *
+ * @return float
+ */
+ public function getMaxLon()
+ {
+ return $this->maxlon;
+ }
+
+ /**
+ * Extend bounding box to cover another bounding box.
+ *
+ * @param Bounds $bounds The bounding box to cover.
+ * @return void
+ */
+ public function extend(Bounds $bounds)
+ {
+ if ($bounds->minlat < $this->minlat) $this->minlat = $bounds->minlat;
+ if ($bounds->minlon < $this->minlon) $this->minlon = $bounds->minlon;
+ if ($bounds->maxlat > $this->maxlat) $this->maxlat = $bounds->maxlat;
+ if ($bounds->maxlon > $this->maxlon) $this->maxlon = $bounds->maxlon;
+ }
+
+}
--- /dev/null
+<?php
+/**
+ * copyright.php
+ *
+ * Copyright 2018 Andy Street <andy@street.me.uk>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
+ * MA 02110-1301, USA.
+ *
+ *
+ */
+
+namespace libgpx;
+
+use \InvalidArgumentException;
+
+/**
+ * Information about the copyright holder and any license governing use of
+ * the file.
+ *
+ * @see https://www.topografix.com/GPX/1/1/#type_copyrightType
+ *
+ * @author Andy Street <andy@street.me.uk>
+ */
+class Copyright
+{
+
+ /**
+ * The copyright holder.
+ *
+ * @var string
+ */
+ protected $author;
+
+ /**
+ * The year of copyright.
+ *
+ * @var string
+ */
+ protected $year;
+
+ /**
+ * Link to external file containing license text.
+ *
+ * @var string
+ */
+ protected $license;
+
+ /**
+ * Create new copyright information.
+ *
+ * @param string $author The copyright holder.
+ */
+ public function __construct(string $author)
+ {
+ $this->setAuthor($author);
+ }
+
+ /**
+ * Fetch the name of the copyright holder.
+ *
+ * @return string The copyright holder.
+ */
+ public function getAuthor()
+ {
+ return $this->author;
+ }
+
+ /**
+ * Set the name of the copyright holder.
+ *
+ * @param string $author The name of the copyright holder.
+ * @return void
+ */
+ public function setAuthor(string $author)
+ {
+ $this->author = $author;
+ }
+
+ /**
+ * Fetch the year of copyright.
+ *
+ * NOTE: The GPX 1.1 schema defines this field as type "xsd:gYear". It is
+ * therefore possible that this function will return a timezone as
+ * part of the string.
+ *
+ * @param boolean $asint Make the return value an integer (any timezones will
+ * be stripped).
+ * @return string|int|null The copyright year or null if not set.
+ */
+ public function getYear(bool $asint = false)
+ {
+ return ($asint ? intval($this->year) : $this->year);
+ }
+
+ /**
+ * Set the year of copyright.
+ *
+ * @param string|null $year The copyright year in xsd:gYear format or null to
+ * delete.
+ * @return void
+ * @throws InvalidArgumentException If the year is an invalid format.
+ */
+ public function setYear(string $year = null)
+ {
+ if ($year !== null) {
+ $year = trim($year);
+ $regex = '/^(-?)([0-9]+)(Z|[+-][0-9]{2}:[0-9]{2})?$/';
+ if (preg_match($regex, $year, $matches)) {
+ $year =
+ $matches[1] .
+ str_pad($matches[2], 4, '0', STR_PAD_LEFT);
+ if (isset($matches[3]))
+ $year .= $matches[3];
+ } else {
+ throw new InvalidArgumentException(
+ sprintf('Copyright year is an invalid format "%s".', $year)
+ );
+ }
+ }
+ $this->year = $year;
+ }
+
+ /**
+ * Fetch the URL of the license terms.
+ *
+ * @return string|null The URL or null if not set.
+ */
+ public function getLicense()
+ {
+ return $this->license;
+ }
+
+ /**
+ * Set the URL of the license terms.
+ *
+ * @param string|null $license The URL or null to delete.
+ * @return null
+ */
+ public function setLicense(string $license = null)
+ {
+ $this->license = $license;
+ }
+
+}
--- /dev/null
+<?php
+/**
+ * geographic.php
+ *
+ * Copyright 2018 Andy Street <andy@street.me.uk>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
+ * MA 02110-1301, USA.
+ *
+ *
+ */
+
+namespace libgpx;
+
+/**
+ * Common functions for geographic elements.
+ *
+ * @author Andy Street <andy@street.me.uk>
+ */
+interface Geographic
+{
+
+ /**
+ * Fetch a bounding box that covers the feature.
+ *
+ * @return Bounds|null A bounding box covering the extent of the feature or
+ * null if not applicable.
+ */
+ public function getBounds();
+}
--- /dev/null
+<?php
+/**
+ * gpx.php
+ *
+ * Copyright 2018 Andy Street <andy@street.me.uk>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
+ * MA 02110-1301, USA.
+ *
+ *
+ */
+
+namespace libgpx;
+
+use \DateTimeInterface;
+
+/**
+ * A GPX file.
+ *
+ * @see https://www.topografix.com/gpx.asp
+ *
+ * @author Andy Street <andy@street.me.uk>
+ */
+class GPX implements Geographic
+{
+
+ /**
+ * The program that created the GPX file.
+ *
+ * @var string
+ */
+ protected $creator;
+
+ /**
+ * The name of the GPX file.
+ *
+ * @var string
+ */
+ protected $name;
+
+ /**
+ * A description of the contents of the GPX file.
+ *
+ * @var string
+ */
+ protected $desc;
+
+ /**
+ * The person or organization who created the GPX file.
+ *
+ * @var Person
+ */
+ protected $author;
+
+ /**
+ * Copyright and license information governing use of the file.
+ *
+ * @var Copyright
+ */
+ protected $copyright;
+
+ /**
+ * Links to other resources that describe this GPX file.
+ *
+ * @var Link[]
+ */
+ protected $links = [];
+
+ /**
+ * The creation time of the file.
+ *
+ * @var DateTimeInterface
+ */
+ protected $time;
+
+ /**
+ * A list of keywords classifying this GPX file.
+ *
+ * @var string[]
+ */
+ protected $keywords = [];
+
+ /**
+ * Fetch the name of the program that created the GPX file.
+ *
+ * @return string|null The creator or null if not set.
+ */
+ public function getCreator()
+ {
+ return $this->creator;
+ }
+
+ /**
+ * Set the name of the program that created the GPX file.
+ *
+ * @param string|null $creator The program name or null to delete.
+ * @return void
+ */
+ public function setCreator(string $creator = null)
+ {
+ $this->creator = $creator;
+ }
+
+ /**
+ * Fetch the file name.
+ *
+ * @return string|null The name or null if not set.
+ */
+ public function getName()
+ {
+ return $this->name;
+ }
+
+ /**
+ * Set the name of the file.
+ *
+ * @param string|null $name The file name or null to delete.
+ * @return void
+ */
+ public function setName(string $name = null)
+ {
+ $this->name = $name;
+ }
+
+ /**
+ * Fetch the description of the file.
+ *
+ * @return string|null The description or null if not set.
+ */
+ public function getDesc()
+ {
+ return $this->desc;
+ }
+
+ /**
+ * Set the description of the file.
+ *
+ * @param string|null $desc The description or null to delete.
+ * @return void
+ */
+ public function setDesc(string $desc = null)
+ {
+ $this->desc = $desc;
+ }
+
+ /**
+ * Fetch the author of the file.
+ *
+ * @return Person|null The author or null if not set.
+ */
+ public function getAuthor()
+ {
+ return $this->author;
+ }
+
+ /**
+ * Set the author of the file.
+ *
+ * @param Person|null $author The author or null to delete.
+ * @return void
+ */
+ public function setAuthor(Person $author = null)
+ {
+ $this->author = $author;
+ }
+
+ /**
+ * Fetch the copyright details for the file.
+ *
+ * @return Copyright|null The copyright or null if not set.
+ */
+ public function getCopyright()
+ {
+ return $this->copyright;
+ }
+
+ /**
+ * Set the copyright details for the file.
+ *
+ * @param Copyright|null $copyright The copyright detail or null to delete.
+ * @return void
+ */
+ public function setCopyright(Copyright $copyright = null)
+ {
+ $this->copyright = $copyright;
+ }
+
+ /**
+ * Fetch links to other resources.
+ *
+ * @return Link[]
+ */
+ public function getLinks()
+ {
+ return $this->links;
+ }
+
+ /**
+ * Add a link to an related resource.
+ *
+ * @param Link $link The link to add.
+ * @return void
+ */
+ public function addLink(Link $link)
+ {
+ if (!in_array($link, $this->links, true))
+ $this->links[] = $link;
+ }
+
+ /**
+ * Remove an existing link from the list.
+ *
+ * @param Link $link The link to remove.
+ * @return void
+ */
+ public function removeLink(Link $link)
+ {
+ $key = array_search($link, $this->links, true);
+ if ($key !== null)
+ unset($this->links[$key]);
+ }
+
+ /**
+ * Fetch the time the GPX file was created.
+ *
+ * @return DateTimeInterface|null A timestamp or null if not set.
+ */
+ public function getTime()
+ {
+ return $this->time;
+ }
+
+ /**
+ * Set the time at which the file was created.
+ *
+ * @param DateTimeInterface $time The creation time or null to delete.
+ */
+ public function setTime(DateTimeInterface $time = null)
+ {
+ $this->time = $time;
+ }
+
+ /**
+ * Fetch a list of keywords for this GPX file.
+ *
+ * @return string[] The keywords
+ */
+ public function getKeywords()
+ {
+ return $this->keywords;
+ }
+
+ /**
+ * Add a keyword for this GPX file.
+ *
+ * @param string $keyword The keyword to add.
+ * @return void
+ */
+ public function addKeyword(string $keyword)
+ {
+ if (!in_array($keyword, $this->keywords))
+ $this->keywords[] = $keyword;
+ }
+
+ /**
+ * Remove an existing keyword from the list.
+ *
+ * @param string $keyword The keyword to remove.
+ * @return void
+ */
+ public function removeKeyword(string $keyword)
+ {
+ $key = array_search($keyword, $this->keywords);
+ if ($key !== null)
+ unset($this->keywords[$key]);
+ }
+
+ /**
+ * Fetch a bounding box that covers the feature.
+ *
+ * @return Bounds|null A bounding box covering the extent of the feature or
+ * null if not applicable.
+ */
+ public function getBounds()
+ {
+ //TODO: Implement this properly when waypoints, routes and tracks have
+ // been implemented.
+ return null;
+ }
+
+}
--- /dev/null
+<?php
+/**
+ * gpxreader.php
+ *
+ * Copyright 2018 Andy Street <andy@street.me.uk>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
+ * MA 02110-1301, USA.
+ *
+ *
+ */
+
+namespace libgpx;
+
+use \DateTime;
+use \DateTimeZone;
+use \Exception;
+use \InvalidArgumentException;
+use \RuntimeException;
+
+/**
+ * Read GPX files.
+ *
+ * @author Andy Street <andy@street.me.uk>
+ */
+class GPXReader
+{
+
+ /**
+ * The namespace of the XML currently being parsed.
+ *
+ * @var string
+ */
+ protected $ns;
+
+ /**
+ * The GPX version of the XML currently being parsed.
+ *
+ * @var string
+ */
+ protected $version;
+
+ /**
+ * The reader currently reading the XML.
+ *
+ * @var XMLReader
+ */
+ protected $xml;
+
+ /**
+ * Read GPX from a string.
+ *
+ * @param string $xml The GPX XML data.
+ * @return GPX The GPX data.
+ * @throws RuntimeException If the XML could not be read.
+ * @throws MalformedGPXException If the GPX file is invalid.
+ */
+ public function readString(string $xml)
+ {
+ try {
+ $this->xml = new XMLReader();
+ if (!$this->xml->XML($xml, null, LIBXML_NOERROR | LIBXML_NOWARNING)) {
+ throw new RuntimeException('Unable to read XML from string.');
+ }
+ return $this->read();
+ } finally {
+ $this->xml = null;
+ }
+ }
+
+ /**
+ * Read GPX from a file.
+ *
+ * This function is an alias of `GPXReader::readURI()`.
+ *
+ * @param string $filename The name of the file containing GPX XML data.
+ * @return GPX The GPX data.
+ * @throws RuntimeException If the XML could not be read.
+ * @throws MalformedGPXException If the GPX file is invalid.
+ */
+ public function readFile(string $filename)
+ {
+ return $this->readURI($filename);
+ }
+
+ /**
+ * Read GPX from a URI.
+ *
+ * @param string $uri The location of the file containing GPX XML data.
+ * @return GPX The GPX data.
+ * @throws RuntimeException If the XML could not be read.
+ * @throws MalformedGPXException If the GPX file is invalid.
+ */
+ public function readURI(string $uri)
+ {
+ try {
+ $this->xml = new XMLReader();
+ if (!$this->xml->open($uri, null, LIBXML_NOERROR | LIBXML_NOWARNING)) {
+ throw new RuntimeException(sprintf('Unable to read XML from: %s', $uri));
+ }
+ return $this->read();
+ } finally {
+ $this->xml = null;
+ }
+ }
+
+ /**
+ * Read GPX data from XML.
+ *
+ * @param XMLReader $xml Where to read the GPX data from.
+ * @return GPX The data that was read.
+ * @throws MalformedGPXException If the GPX file was invalid or not supported.
+ */
+ protected function read()
+ {
+ $xml = $this->xml;
+ try {
+ // Fast forward to the root element.
+ while ($xml->nodeType !== XMLReader::ELEMENT) {
+ $xml->read();
+ }
+
+ // Detect file version
+ switch ($xml->namespaceURI) {
+ case libgpx::NAMESPACE_GPX_1_0:
+ $this->version = '1.0';
+ $this->ns = libgpx::NAMESPACE_GPX_1_0;
+ break;
+ case libgpx::NAMESPACE_GPX_1_1:
+ $this->version = '1.1';
+ $this->ns = libgpx::NAMESPACE_GPX_1_1;
+ break;
+ default:
+ throw new MalformedGPXException('Unknown or unsupported file format.');
+ }
+
+ // Read GPX element.
+ if ($xml->localName == 'gpx')
+ return $this->readGPX();
+ else
+ throw new MalformedGPXException('Root element must be "gpx".');
+
+ } finally {
+ $this->version = null;
+ $this->ns = null;
+ }
+ }
+
+ /**
+ * Read a gpx type.
+ *
+ * @return GPX The GPX data.
+ * @throws MalformedGPXException If the GPX file was invalid or not supported.
+ */
+ protected function readGPX()
+ {
+ // Sanity check - ensure version attribute and schema declaration match.
+ if ($this->xml->getAttribute('version') != $this->version)
+ throw new MalformedGPXException(
+ 'GPX version attribute does not match namespace declaration.'
+ );
+
+ $result = new GPX();
+ $result->setCreator($this->xml->getAttribute('creator'));
+
+ $struct = [
+ 'elements' => []
+ ];
+ if ($this->version == '1.1') {
+ $struct['elements']['metadata'] = function ($gpx) {
+ $this->readMetadata($gpx);
+ };
+ } else {
+ $struct['elements']['name'] = function ($gpx) {
+ $gpx->setName($this->readXSDString());
+ };
+ $struct['elements']['desc'] = function ($gpx) {
+ $gpx->setDesc($this->readXSDString());
+ };
+ $struct['elements']['author'] = function ($gpx) {
+ $author = $gpx->getAuthor();
+ if ($author === null) {
+ $author = new Person();
+ $gpx->setAuthor($author);
+ }
+ $author->setName($this->readXSDString());
+ };
+ $struct['elements']['email'] = function ($gpx) {
+ $author = $gpx->getAuthor();
+ if ($author === null) {
+ $author = new Person();
+ $gpx->setAuthor($author);
+ }
+ $author->setEmail($this->readXSDString());
+ };
+ $struct['elements']['url'] = function ($gpx, &$state) {
+ $href = $this->readXSDString();
+ $links = $gpx->getLinks();
+ if (isset($links[0])) {
+ $links[0]->setHref($href);
+ } else {
+ $link = new Link($href);
+ if (isset($state['urlname'])) {
+ $link->setText($state['urlname']);
+ unset($state['urlname']);
+ }
+ $gpx->addLink($link);
+ }
+ };
+ $struct['elements']['urlname'] = function ($gpx, &$state) {
+ $text = $this->readXSDString();
+ $links = $gpx->getLinks();
+ if (isset($links[0])) {
+ $links[0]->setText($text);
+ } else {
+ $state['urlname'] = $text;
+ }
+ };
+ $struct['elements']['time'] = function ($gpx) {
+ $gpx->setTime($this->string2DateTime($this->readXSDString()));
+ };
+ $struct['elements']['keywords'] = function ($gpx) {
+ $keywords = explode(',', $this->readXSDString());
+ foreach ($keywords as $keyword)
+ $gpx->addKeyword(trim($keyword));
+ };
+ $struct['elements']['bounds'] = false;
+ }
+
+ $this->readStruct($struct, $result);
+ return $result;
+ }
+
+ /**
+ * Read a metadata type.
+ *
+ * Note: This is GPX 1.1 only as GPX 1.0 does not have a metadata type.
+ *
+ * @param GPX $gpx The gpx object to populate.
+ * @return void
+ * @throws MalformedGPXException If the GPX file was invalid or not supported.
+ */
+ protected function readMetadata(GPX $gpx)
+ {
+ $struct = [
+ 'elements' => [
+ 'name' => function ($gpx) {
+ $gpx->setName($this->readXSDString());
+ },
+ 'desc' => function ($gpx) {
+ $gpx->setDesc($this->readXSDString());
+ },
+ 'author' => function ($gpx) {
+ $gpx->setAuthor($this->readPerson());
+ },
+ 'copyright' => function ($gpx) {
+ $gpx->setCopyright($this->readCopyright());
+ },
+ 'link' => function ($gpx) {
+ $gpx->addLink($this->readLink());
+ },
+ 'time' => function ($gpx) {
+ $gpx->setTime($this->string2DateTime($this->readXSDString()));
+ },
+ 'keywords' => function ($gpx) {
+ $keywords = explode(',', $this->readXSDString());
+ foreach ($keywords as $keyword)
+ $gpx->addKeyword(trim($keyword));
+ },
+ 'bounds' => false
+ ]
+ ];
+ $this->readStruct($struct, $gpx);
+ }
+
+ /**
+ * Read a person type.
+ *
+ * @return Person The person data.
+ * @throws MalformedGPXException If the GPX file was invalid or not supported.
+ */
+ protected function readPerson()
+ {
+ $struct = [
+ 'elements' => [
+ 'name' => function ($person) {
+ $person->setName($this->readXSDString());
+ },
+ 'email' => function ($person) {
+ $id = $this->xml->getAttribute('id');
+ if ($id === null)
+ throw new MalformedGPXException(
+ 'Missing required attribute "id" in "email"'
+ );
+ $domain = $this->xml->getAttribute('domain');
+ if ($domain === null)
+ throw new MalformedGPXException(
+ 'Missing required attribute "domain" in "email"'
+ );
+ $person->setEmail($id . '@' . $domain);
+ $this->xml->read();
+ },
+ 'link' => function ($person) {
+ $person->setLink($this->readLink());
+ }
+ ]
+ ];
+ $person = new Person();
+ $this->readStruct($struct, $person);
+ return $person;
+ }
+
+ /**
+ * Read a link type.
+ *
+ * @return Link The link data.
+ * @throws MalformedGPXException If the GPX file was invalid or not supported.
+ */
+ protected function readLink()
+ {
+ $href = $this->xml->getAttribute('href');
+ if ($href === null)
+ throw new MalformedGPXException(
+ 'Missing required attribute "href" in "link"'
+ );
+ $struct = [
+ 'elements' => [
+ 'text' => function ($link) {
+ $link->setText($this->readXSDString());
+ },
+ 'type' => function ($link) {
+ $link->setType($this->readXSDString());
+ }
+ ]
+ ];
+ $link = new Link($href);
+ $this->readStruct($struct, $link);
+ return $link;
+ }
+
+ /**
+ * Read a copyright type.
+ *
+ * @return Copyright The copyright data.
+ * @throws MalformedGPXException If the GPX file was invalid or not supported.
+ */
+ protected function readCopyright()
+ {
+ $author = $this->xml->getAttribute('author');
+ if ($author === null)
+ throw new MalformedGPXException(
+ 'Missing required attribute "author" in "copyright"'
+ );
+ $struct = [
+ 'elements' => [
+ 'year' => function ($copyright) {
+ try {
+ $year = $this->readXSDString();
+ $copyright->setYear($year);
+ } catch (InvalidArgumentException $e) {
+ throw new MalformedGPXException(
+ sprintf('"%s" is not a valid year', $year)
+ );
+ }
+ },
+ 'license' => function ($copyright) {
+ $copyright->setLicense($this->readXSDString());
+ }
+ ]
+ ];
+ $copyright = new Copyright($author);
+ $this->readStruct($struct, $copyright);
+ return $copyright;
+ }
+
+ /**
+ * Read a data structure from XML.
+ *
+ * This is a generalized function for parsing XML data structures and
+ * populating values based on data retrieved. The main control element is the
+ * `$struct` array which holds a list of callable functions which are used to
+ * modify the supplied object. The structure of the array is:
+ *
+ * [
+ * 'elements' => [
+ * 'tagname' => function($object, &$state) {...}
+ * ]
+ * ]
+ *
+ * The anonymous function parameters are as follows:
+ *
+ * * `$object` - The object to be populated (as passed to this function)
+ * * `$state` - An array that can be used to store data temporarily while
+ * the structure is being written. This is useful if a value
+ * that is being read is split across several XML elements.
+ *
+ * @param array $struct a data structure as defined above.
+ * @param object $object The object to populate with data.
+ * @return void
+ * @throws MalformedGPXException If the GPX file was invalid or not supported.
+ */
+ protected function readStruct($struct, $object)
+ {
+ $xml = $this->xml;
+ if ($xml->isEmptyElement) {
+ $xml->read();
+ return;
+ }
+ $element = $xml->localName;
+ $xml->read();
+ $state = [];
+ while (true) {
+ if (
+ $xml->nodeType == XMLReader::END_ELEMENT
+ && $xml->namespaceURI == $this->ns
+ && $xml->localName == $element
+ ) return;
+ if ($xml->nodeType != XMLReader::ELEMENT) {
+ $xml->read();
+ continue;
+ }
+ if (
+ $xml->namespaceURI == $this->ns
+ && isset($struct['elements'][$xml->localName])
+ ) {
+ if (is_callable($struct['elements'][$xml->localName])) {
+ $struct['elements'][$xml->localName]($object, $state);
+ } else {
+ $xml->read();
+ }
+ continue;
+ }
+ throw new MalformedGPXException(
+ sprintf(
+ 'Unknown element "%s" in element "%s"',
+ $xml->localName,
+ $element
+ )
+ );
+ }
+ }
+
+ /**
+ * Read an `xsd:string` type from XML.
+ *
+ * @return string The text string.
+ * @throws MalformedGPXException If the element has non-text children.
+ */
+ protected function readXSDString()
+ {
+ $xml = $this->xml;
+ $result = '';
+ if ($xml->nodeType != XMLReader::ELEMENT || $xml->isEmptyElement)
+ return $result;
+ $element = $xml->name;
+ while ($xml->read()) {
+ switch ($xml->nodeType) {
+ case XMLReader::TEXT:
+ case XMLReader::CDATA:
+ $result .= $xml->value;
+ break;
+ case XMLReader::END_ELEMENT:
+ $xml->read();
+ break 2;
+ default:
+ throw new MalformedGPXException(
+ sprintf('Element "%s" contains non-text data.', $element)
+ );
+ }
+
+ }
+ return $result;
+ }
+
+ /**
+ * Convert a string to DateTime.
+ *
+ * @param string $timestamp The timestamp to convert.
+ * @return DateTime The parsed DateTime.
+ * @throws MalformedGPXException If the timestamp could not be parsed.
+ */
+ protected function string2DateTime(string $timestamp)
+ {
+ try {
+ $result = new DateTime($timestamp, new DateTimeZone('Z'));
+ } catch (Exception $e) {
+ throw new MalformedGPXException(
+ sprintf('Unknown datetime format "%s"', $timestamp)
+ );
+ }
+ return $result;
+ }
+
+}
--- /dev/null
+<?php
+/**
+ * gpxwriter.php
+ *
+ * Copyright 2018 Andy Street <andy@street.me.uk>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
+ * MA 02110-1301, USA.
+ *
+ *
+ */
+
+namespace libgpx;
+
+use \DateTime;
+use \DateTimeInterface;
+use \DateTimeZone;
+use \RuntimeException;
+use \UnexpectedValueException;
+use \XMLWriter;
+
+/**
+ * Write GPX files.
+ *
+ * @author Andy Street <andy@street.me.uk>
+ */
+class GPXWriter
+{
+
+ /**
+ * Who to credit as the document creator in the GPX root element.
+ *
+ * @var string
+ * @see http://www.topografix.com/GPX/1/1/#type_gpxType
+ */
+ protected $creator = 'libgpx';
+
+ /**
+ * The version of the GPX standard to generate.
+ *
+ * @var string
+ */
+ protected $format = '1.1';
+
+ /**
+ * Whether to indent the XML output for readability.
+ *
+ * @var boolean
+ */
+ protected $indent = true;
+
+ /**
+ * Whether to include milliseconds in timestamps.
+ *
+ * @var boolean
+ */
+ protected $milliseconds = true;
+
+ /**
+ * Fetch the name credited as the creator of the XML files.
+ *
+ * @return string The creator.
+ */
+ public function getCreator()
+ {
+ return $this->creator;
+ }
+
+ /**
+ * Set the name to be credited as the XML document creator.
+ *
+ * @param string $creator The name to credit as the creator.
+ * @return void
+ */
+ public function setCreator(string $creator)
+ {
+ $this->creator = $creator;
+ }
+
+ /**
+ * Fetch the GPX file format that this class generates.
+ *
+ * @return string The GPX file format.
+ */
+ public function getFormat()
+ {
+ return $this->format;
+ }
+
+ /**
+ * Set the GPX file format that this class generates.
+ *
+ * @param string $format Accepted values are "1.0" or "1.1".
+ * @return void
+ * @throws UnexpectedValueException If $format is not a known GPX version.
+ */
+ public function setFormat(string $format)
+ {
+ switch ($format) {
+ case '1.0':
+ case '1.1':
+ $this->format = $format;
+ break;
+ default:
+ throw new UnexpectedValueException(
+ sprintf('Unknown GPX version "%s"', $format)
+ );
+ }
+ }
+
+ /**
+ * Whether this class will indent output for readability.
+ *
+ * @return boolean If the output will be indented.
+ */
+ public function getIndent()
+ {
+ return $this->indent;
+ }
+
+ /**
+ * Set whether to indent output for readability.
+ *
+ * @param boolean $indent Whether to indent.
+ * @return void
+ */
+ public function setIndent(bool $indent)
+ {
+ $this->indent = $indent;
+ }
+
+ /**
+ * Whether timestamps are written to include milliseconds.
+ *
+ * @return boolean
+ */
+ public function getTimestampUseMilliseconds()
+ {
+ return $this->milliseconds;
+ }
+
+ /**
+ * Set whether to output milliseconds in timestamps.
+ *
+ * @param boolean $milliseconds Whether to use milliseconds.
+ * @return void
+ */
+ public function setTimestampUseMilliseconds(bool $milliseconds)
+ {
+ $this->milliseconds = $milliseconds;
+ }
+
+ /**
+ * Fetch an XML representation as a string.
+ *
+ * @param GPX $gpx The source for the XML.
+ * @return string An XML representation of the GPX object.
+ */
+ public function fetch(GPX $gpx)
+ {
+ $xml = new XMLWriter();
+ $xml->openMemory();
+ $this->write($gpx, $xml);
+ return $xml->outputMemory();
+ }
+
+ /**
+ * Write XML to standard out.
+ *
+ * @param GPX $gpx The source for the XML.
+ * @return void
+ */
+ public function output(GPX $gpx)
+ {
+ $xml = new XMLWriter();
+ $xml->openURI('php://output');
+ $this->write($gpx, $xml);
+ }
+
+ /**
+ * Write XML to a file.
+ *
+ * @param GPX $gpx The source for the XML.
+ * @param string $filename Where to write the XML.
+ * @return void
+ * @throws RuntimeException If the file cannot be written to.
+ */
+ public function save(GPX $gpx, string $filename)
+ {
+ $xml = new XMLWriter();
+ if (!$xml->openURI('php://output'))
+ throw RuntimeException(sprintf('Unable to write to "%s"', $filename));
+ $this->write($gpx, $xml);
+ }
+
+ /**
+ * Generate the XML.
+ *
+ * @param GPX $gpx The source for the XML.
+ * @param XMLWriter $xml The instance to use to generate the XML.
+ * @return void
+ */
+ protected function write(GPX $gpx, XMLWriter $xml)
+ {
+ $xml->setIndent($this->indent);
+ $xml->startDocument('1.0', 'UTF-8');
+ if ($this->format == '1.1') {
+ $namespace = libgpx::NAMESPACE_GPX_1_1;
+ $schema = libgpx::SCHEMA_GPX_1_1;
+ } else {
+ $namespace = libgpx::NAMESPACE_GPX_1_0;
+ $schema = libgpx::SCHEMA_GPX_1_0;
+ }
+ $xml->startElementNs(null, 'gpx', $namespace);
+ $xml->writeAttribute('version', $this->format);
+ $xml->writeAttribute('creator', $this->creator);
+ $xml->writeAttributeNS(
+ 'xsi',
+ 'schemaLocation',
+ libgpx::NAMESPACE_XMLSCHEMA,
+ $namespace . ' ' . $schema
+ );
+ $this->writeMetadata($gpx, $xml);
+ $xml->endElement();
+ $xml->endDocument();
+ $xml->flush();
+ }
+
+ /**
+ * Generate XML for Metadata elements.
+ *
+ * @param GPX $gpx The object to source the metadata from.
+ * @param XMLWriter $xml Where to write the metadata.
+ * @return void
+ */
+ protected function writeMetadata(GPX $gpx, XMLWriter $xml)
+ {
+ if ($this->format == '1.1')
+ $xml->startElement('metadata');
+ $name = $gpx->getName();
+ if (!empty($name))
+ $xml->writeElement('name', $name);
+ $desc = $gpx->getDesc();
+ if (!empty($desc))
+ $xml->writeElement('desc', $desc);
+ $author = $gpx->getAuthor();
+ if ($author instanceof Person)
+ $this->writePerson($author, $xml);
+ if ($this->format == '1.1') {
+ $copyright = $gpx->getCopyright();
+ if ($copyright instanceof Copyright)
+ $this->writeCopyright($copyright, $xml);
+ }
+ foreach($gpx->getLinks() as $link) {
+ $this->writeLink($link, $xml);
+ if ($this->format == '1.0')
+ break;
+ }
+ $xml->writeElement('time', $this->createTimestamp(new DateTime()));
+ if (!empty($gpx->getKeywords()))
+ $xml->writeElement('keywords', implode(', ', $gpx->getKeywords()));
+ $bounds = $gpx->getBounds();
+ if ($bounds instanceof Bounds) {
+ $xml->startElement('bounds');
+ $xml->writeAttribute('minlat', $bounds->getMinLat());
+ $xml->writeAttribute('minlon', $bounds->getMinLon());
+ $xml->writeAttribute('maxlat', $bounds->getMaxLat());
+ $xml->writeAttribute('maxlon', $bounds->getMaxLon());
+ $xml->endElement();
+ }
+ if ($this->format == '1.1')
+ $xml->endElement();
+ }
+
+ /**
+ * Generate XML for GPX Person type.
+ *
+ * @param Person $person The person object to source data from.
+ * @param XMLWriter $xml Where to write the data.
+ * @return void
+ */
+ protected function writePerson(Person $person, XMLWriter $xml)
+ {
+ if ($this->format == '1.1') {
+ $xml->startElement('author');
+ $name = $person->getName();
+ if (!empty($name))
+ $xml->writeElement('name', $name);
+ $email = $person->getEmail();
+ if (!empty($email)) {
+ $email = explode('@', $email, 2);
+ $xml->startElement('email');
+ $xml->writeAttribute('id', $email[0]);
+ $xml->writeAttribute('domain', $email[1]);
+ $xml->endElement();
+ }
+ $link = $person->getLink();
+ if (!empty($link))
+ $this->writeLink($link, $xml);
+ $xml->endElement();
+ } else {
+ $name = $person->getName();
+ if (!empty($name))
+ $xml->writeElement('author', $name);
+ $email = $person->getEmail();
+ if (!empty($email))
+ $xml->writeElement('email', $email);
+ }
+ }
+
+ /**
+ * Generate XML for a GPX Link type.
+ *
+ * @param Link $link The link object to source data from.
+ * @param XMLWriter $xml Where to write the data.
+ * @return void
+ */
+ protected function writeLink(Link $link, XMLWriter $xml)
+ {
+ if ($this->format == '1.1') {
+ $xml->startElement('link');
+ $xml->writeAttribute('href', $link->getHref());
+ $text = $link->getText();
+ if (!empty($text))
+ $xml->writeElement('text', $text);
+ $type = $link->getType();
+ if (!empty($type))
+ $xml->writeElement('type', $type);
+ $xml->endElement();
+ } else {
+ $xml->writeElement('url', $link->getHref());
+ $text = $link->getText();
+ if (!empty($text))
+ $xml->writeElement('urlname', $text);
+ }
+ }
+
+ /**
+ * Generate XML for GPX Copyright type.
+ *
+ * @param Copyright $copyright Object to source copyright data from.
+ * @param XMLWriter $xml Where to write the data.
+ * @return void
+ */
+ protected function writeCopyright(Copyright $copyright, XMLWriter $xml)
+ {
+ $xml->startElement('copyright');
+ $xml->writeAttribute('author', $copyright->getAuthor());
+ $year = $copyright->getYear();
+ if (!empty($year))
+ $xml->writeElement('year', $year);
+ $license = $copyright->getLicense();
+ if (!empty($license))
+ $xml->writeElement('license', $license);
+ $xml->endElement();
+ }
+
+ /**
+ * Create an ISO 8601 timestamp.
+ *
+ * @param DateTimeInterface $timestamp The timestamp to format.
+ * @param boolean $millis Include milliseconds.
+ * @return string A timestamp.
+ */
+ protected function createTimestamp(
+ DateTimeInterface $timestamp,
+ bool $millis = null
+ ) {
+ if ($millis === null)
+ $millis = $this->milliseconds;
+ if (!$timestamp->getTimezone()->getOffset($timestamp))
+ $timestamp = $timestamp->setTimezone(new DateTimeZone('UTC'));
+ $format = 'Y-m-d\TH:i:s' . ($millis ? '.v\Z' : '\Z');
+ return $timestamp->format($format);
+ }
+
+}
--- /dev/null
+<?php
+/**
+ * libgpx.php
+ *
+ * Copyright 2018 Andy Street <andy@street.me.uk>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
+ * MA 02110-1301, USA.
+ *
+ *
+ */
+
+namespace libgpx;
+
+use \DateTimeZone;
+use \RuntimeException;
+
+/**
+ * Constants and miscellaneous functions for the libgpx library.
+ *
+ * @static
+ * @author Andy Street <andy@street.me.uk>
+ */
+final class libGPX
+{
+
+ /**
+ * The XML namespace for GPX 1.0.
+ */
+ const NAMESPACE_GPX_1_0 = 'http://www.topografix.com/GPX/1/0';
+
+ /**
+ * The XML namespace for GPX 1.1.
+ */
+ const NAMESPACE_GPX_1_1 = 'http://www.topografix.com/GPX/1/1';
+
+ /**
+ * The XML namespace for XML Schema.
+ */
+ const NAMESPACE_XMLSCHEMA = 'http://www.w3.org/2001/XMLSchema-instance';
+
+ /**
+ * The URL of the schema document for GPX 1.0.
+ */
+ const SCHEMA_GPX_1_0 = 'http://www.topografix.com/GPX/1/0/gpx.xsd';
+
+ /**
+ * The URL of the schema document for GPX 1.1.
+ */
+ const SCHEMA_GPX_1_1 = 'http://www.topografix.com/GPX/1/1/gpx.xsd';
+
+ /**
+ * If libgpx::init() has been completed successfully.
+ *
+ * @var boolean
+ */
+ private static $initialized = false;
+
+ /**
+ * Empty constructor - class is static.
+ */
+ private function __construct() {}
+
+ /**
+ * Check if the system has the required dependencies.
+ *
+ * @param boolean $throw If true, throw an exception when dependencies are unmet.
+ * @return boolean If all dependencies are met.
+ * @throws RuntimeException
+ */
+ public static function checkDependencies($throw = false)
+ {
+ // Define dependencies
+ $php_version = '7.0.0';
+ $modules = ['xmlreader', 'xmlwriter'];
+
+ // Check for PHP
+ if (version_compare(PHP_VERSION, $php_version) < 0) {
+ if ($throw)
+ throw new RuntimeException(
+ sprintf('PHP version %s required.', $php_version)
+ );
+ else
+ return false;
+ }
+
+ // Check for modules
+ foreach ($modules as $module) {
+ if (!extension_loaded($module)) {
+ if ($throw)
+ throw new RuntimeException(sprintf(
+ 'PHP module "%s" required but not installed.',
+ $module
+ ));
+ else
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * Ensure that dependencies are met and an autoloader is registered.
+ *
+ * @return void
+ * @throws RuntimeException If the dependencies are not met.
+ */
+ public static function init()
+ {
+ if (self::$initialized) return;
+ self::checkDependencies(true);
+ spl_autoload_register(
+ function ($class) {
+ if (strncmp($class, 'libgpx\\', 7) !== 0) return;
+ $class = strtolower(substr($class, 7));
+ $filename = __DIR__ . DIRECTORY_SEPARATOR . $class . '.php';
+ if (is_readable($filename)) {
+ include $filename;
+ }
+ }
+ );
+ self::$initialized = true;
+ }
+
+}
--- /dev/null
+<?php
+/**
+ * libxmlexception.php
+ *
+ * Copyright 2018 Andy Street <andy@street.me.uk>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
+ * MA 02110-1301, USA.
+ *
+ *
+ */
+
+namespace libgpx;
+
+use \LibXMLError;
+use \RuntimeException;
+
+/**
+ * An exception triggered by a libxml error.
+ *
+ * @author Andy Street <andy@street.me.uk>
+ */
+class LibXMLException extends RuntimeException
+{
+
+ /**
+ * The error that triggered this exception.
+ *
+ * @var LibXMLError
+ */
+ protected $xmlError;
+
+ /**
+ * Create a new exception.
+ *
+ * @param LibXMLError $error The error that triggered this exception.
+ */
+ public function __construct(LibXMLError $error)
+ {
+ parent::__construct($error->message, $error->code);
+ $this->xmlError = $error;
+ }
+
+ /**
+ * Fetch the error that triggered this exception.
+ *
+ * @return LibXMLError The error.
+ */
+ public function getLibXMLError()
+ {
+ return $this->xmlError;
+ }
+
+}
--- /dev/null
+<?php
+/**
+ * link.php
+ *
+ * Copyright 2018 Andy Street <andy@street.me.uk>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
+ * MA 02110-1301, USA.
+ *
+ *
+ */
+
+namespace libgpx;
+
+/**
+ * A link to an external resource (Web page, digital photo, video clip, etc)
+ * with additional information.
+ *
+ * @see https://www.topografix.com/GPX/1/1/#type_linkType
+ *
+ * @author Andy Street <andy@street.me.uk>
+ */
+class Link
+{
+
+ /**
+ * URL of hyperlink.
+ *
+ * @var string
+ */
+ protected $href;
+
+ /**
+ * Text of hyperlink.
+ *
+ * @var string
+ */
+ protected $text;
+
+ /**
+ * Mime type of content (image/jpeg).
+ *
+ * @var string
+ */
+ protected $type;
+
+ /**
+ * Create a new link.
+ *
+ * @param string $href The URL of the link.
+ */
+ public function __construct(string $href)
+ {
+ $this->setHref($href);
+ }
+
+ /**
+ * Fetch the URL of the link.
+ *
+ * @return string
+ */
+ public function getHref()
+ {
+ return $this->href;
+ }
+
+ /**
+ * Set the URL of the link.
+ *
+ * @param string $href The URL of the link.
+ * @return void
+ */
+ public function setHref(string $href)
+ {
+ $this->href = $href;
+ }
+
+ /**
+ * Fetch the text of the hyperlink.
+ *
+ * @return string|null The text or null if not set.
+ */
+ public function getText()
+ {
+ return $this->text;
+ }
+
+ /**
+ * Set the text of the hyperlink.
+ *
+ * @param string|null $text The text of the link or null to delete.
+ * @return void
+ */
+ public function setText(string $text = null)
+ {
+ $this->text = $text;
+ }
+
+ /**
+ * Fetch the mime type of the hyperlink.
+ *
+ * @return string|null The mime type or null if not set.
+ */
+ public function getType()
+ {
+ return $this->type;
+ }
+
+ /**
+ * Set the mime type of the hyperlink.
+ *
+ * @param string|null $type The mime type of the link or null to delete.
+ * @return void
+ */
+ public function setType(string $type = null)
+ {
+ $this->type = $type;
+ }
+
+}
--- /dev/null
+<?php
+/**
+ * malformedgpxexception.php
+ *
+ * Copyright 2018 Andy Street <andy@street.me.uk>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
+ * MA 02110-1301, USA.
+ *
+ *
+ */
+
+namespace libgpx;
+
+use \RuntimeException;
+
+/**
+ * An exception thrown when an error occurred whilst reading a GPX file.
+ *
+ * @author Andy Street <andy@street.me.uk>
+ */
+class MalformedGPXException extends RuntimeException
+{
+}
--- /dev/null
+<?php
+/**
+ * person.php
+ *
+ * Copyright 2018 Andy Street <andy@street.me.uk>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
+ * MA 02110-1301, USA.
+ *
+ *
+ */
+
+namespace libgpx;
+
+use \InvalidArgumentException;
+
+/**
+ * A GPX Person.
+ *
+ * @see https://www.topografix.com/GPX/1/1/#type_personType
+ *
+ * @author Andy Street <andy@street.me.uk>
+ */
+class Person
+{
+
+ /**
+ * Name of person or organization.
+ *
+ * @var string
+ */
+ protected $name;
+
+ /**
+ * Email address.
+ *
+ * @var string
+ */
+ protected $email;
+
+ /**
+ * Link to Web site or other external information about person.
+ *
+ * @var Link
+ */
+ protected $link;
+
+ /**
+ * Fetch the name of the person.
+ *
+ * @return string|null The name or null if not set.
+ */
+ public function getName()
+ {
+ return $this->name;
+ }
+
+ /**
+ * Set the name of the person.
+ *
+ * @param string|null $name The name or null to delete.
+ * @return void
+ */
+ public function setName(string $name = null)
+ {
+ $this->name = $name;
+ }
+
+ /**
+ * Fetch the email address of the person.
+ *
+ * @return string|null The email address or null if not set.
+ */
+ public function getEmail()
+ {
+ return $this->email;
+ }
+
+ /**
+ * Set the email address of the person.
+ *
+ * @param string|null $email The email address or null to delete.
+ * @return void
+ */
+ public function setEmail(string $email = null) {
+ $this->email = $email;
+ }
+
+ /**
+ * Fetch a link to a resource connected to the person.
+ *
+ * @return Link|null The link or null if not set.
+ */
+ public function getLink()
+ {
+ return $this->link;
+ }
+
+ /**
+ * Set the link to a resource connected to the person.
+ *
+ * @param Link|null $link The link or null to delete.
+ * @return void
+ */
+ public function setLink(Link $link = null)
+ {
+ $this->link = $link;
+ }
+
+}
--- /dev/null
+<?php
+/**
+ * xmlreader.php
+ *
+ * Copyright 2018 Andy Street <andy@street.me.uk>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
+ * MA 02110-1301, USA.
+ *
+ *
+ */
+
+namespace libgpx;
+
+use \LibXMLError;
+
+/**
+ * An extended version of the standard XMLReader class with enhanced error
+ * handling.
+ *
+ * @author Andy Street <andy@street.me.uk>
+ */
+class XMLReader extends \XMLReader
+{
+
+ /**
+ * The error level at which exceptions are thrown.
+ *
+ * @var int
+ */
+ protected $errorLevel = LIBXML_ERR_FATAL;
+
+ /**
+ * Fetch the error level at which exceptions will be thrown.
+ *
+ * @return int One of the LIB_XML_ERR_* constants.
+ */
+ public function getExceptionLevel()
+ {
+ return $this->errorLevel;
+ }
+
+ /**
+ * Set the error level at which exceptions will be thrown.
+ *
+ * @param int $level One of the LIB_XML_ERR_* constants.
+ * @return void
+ */
+ public function setExceptionLevel(int $level)
+ {
+ $this->errorLevel = $level;
+ }
+
+ /**
+ * Move to next node in document.
+ *
+ * When the standard implementation of `read` returns false it could either
+ * be because the end of the document has been reached or because an error
+ * has occurred. This implementation makes it easier to distinguish between
+ * the two by throwing and exception when an error occurs.
+ *
+ * @see \XMLReader::read()
+ *
+ * @return boolean Returns true on success or false on failure.
+ * @throws LibXMLException If an error of sufficient magnitude is detected.
+ */
+ public function read() {
+ libxml_clear_errors();
+ $result = parent::read();
+ $error = libxml_get_last_error();
+ if ($error instanceof LibXMLError && $error->level >= $this->errorLevel)
+ throw new LibXMLException($error);
+ return $result;
+ }
+
+}