first commit

This commit is contained in:
2025-07-18 16:20:14 +07:00
commit 98af45c018
16382 changed files with 3148096 additions and 0 deletions

View File

@@ -0,0 +1,4 @@
{
"default": true,
"MD013": false
}

View File

@@ -0,0 +1,504 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 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.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
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 and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, 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 library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete 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 distribute a copy of this License along with the
Library.
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 Library or any portion
of it, thus forming a work based on the Library, 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) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
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 Library, 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 Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you 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.
If distribution of 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 satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be 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.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library 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.
9. 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 Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
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 with
this License.
11. 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 Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library 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 Library.
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.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library 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.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser 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 Library
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 Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
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
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "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
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. 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 LIBRARY 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
LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), 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 Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. 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 library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; 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.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random
Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!

View File

@@ -0,0 +1,6 @@
# xml-common
![Build Status](https://github.com/simplesamlphp/xml-common/actions/workflows/php.yml/badge.svg)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/simplesamlphp/xml-common/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/simplesamlphp/xml-common/?branch=master)
[![Coverage Status](https://codecov.io/gh/simplesamlphp/xml-common/branch/master/graph/badge.svg)](https://codecov.io/gh/simplesamlphp/xml-common)
[![PHPStan Enabled](https://img.shields.io/badge/PHPStan-enabled-brightgreen.svg?style=flat)](https://github.com/simplesamlphp/xml-common)

View File

@@ -0,0 +1,56 @@
{
"name": "simplesamlphp/xml-common",
"description": "A library with classes and utilities for handling XML structures.",
"type": "simplesamlphp-xmlprovider",
"keywords": ["saml", "xml"],
"homepage": "http://simplesamlphp.org",
"license": "LGPL-2.1-or-later",
"authors": [
{
"name": "Jaime Perez",
"email": "jaime.perez@uninett.no"
},
{
"name": "Tim van Dijen",
"email": "tvdijen@gmail.com"
}
],
"autoload": {
"psr-4": {
"SimpleSAML\\XML\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"SimpleSAML\\Test\\XML\\": ["tests/XML", "tests/Utils"]
}
},
"require": {
"php": "^8.1",
"ext-date": "*",
"ext-dom": "*",
"ext-filter": "*",
"ext-libxml": "*",
"ext-pcre": "*",
"ext-spl": "*",
"simplesamlphp/assert": "~1.8.0",
"simplesamlphp/composer-xmlprovider-installer": "~1.0.0",
"symfony/finder": "^6.4"
},
"require-dev": {
"simplesamlphp/simplesamlphp-test-framework": "^1.7"
},
"support": {
"issues": "https://github.com/simplesamlphp/xml-common/issues",
"source": "https://github.com/simplesamlphp/xml-common"
},
"config": {
"allow-plugins": {
"composer/package-versions-deprecated": true,
"dealerdirect/phpcodesniffer-composer-installer": true,
"phpstan/extension-installer": true,
"simplesamlphp/composer-xmlprovider-installer": true
}
}
}

View File

@@ -0,0 +1,286 @@
<?xml version='1.0'?>
<?xml-stylesheet href="../../2008/09/xsd.xsl" type="text/xsl"?>
<xs:schema targetNamespace="http://www.w3.org/XML/1998/namespace"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns ="http://www.w3.org/1999/xhtml"
xml:lang="en">
<xs:annotation>
<xs:documentation>
<div>
<h1>About the XML namespace</h1>
<div class="bodytext">
<p>
This schema document describes the XML namespace, in a form
suitable for import by other schema documents.
</p>
<p>
See <a href="http://www.w3.org/XML/1998/namespace.html">
http://www.w3.org/XML/1998/namespace.html</a> and
<a href="http://www.w3.org/TR/REC-xml">
http://www.w3.org/TR/REC-xml</a> for information
about this namespace.
</p>
<p>
Note that local names in this namespace are intended to be
defined only by the World Wide Web Consortium or its subgroups.
The names currently defined in this namespace are listed below.
They should not be used with conflicting semantics by any Working
Group, specification, or document instance.
</p>
<p>
See further below in this document for more information about <a
href="#usage">how to refer to this schema document from your own
XSD schema documents</a> and about <a href="#nsversioning">the
namespace-versioning policy governing this schema document</a>.
</p>
</div>
</div>
</xs:documentation>
</xs:annotation>
<xs:attribute name="lang">
<xs:annotation>
<xs:documentation>
<div>
<h3>lang (as an attribute name)</h3>
<p>
denotes an attribute whose value
is a language code for the natural language of the content of
any element; its value is inherited. This name is reserved
by virtue of its definition in the XML specification.</p>
</div>
<div>
<h4>Notes</h4>
<p>
Attempting to install the relevant ISO 2- and 3-letter
codes as the enumerated possible values is probably never
going to be a realistic possibility.
</p>
<p>
See BCP 47 at <a href="http://www.rfc-editor.org/rfc/bcp/bcp47.txt">
http://www.rfc-editor.org/rfc/bcp/bcp47.txt</a>
and the IANA language subtag registry at
<a href="http://www.iana.org/assignments/language-subtag-registry">
http://www.iana.org/assignments/language-subtag-registry</a>
for further information.
</p>
<p>
The union allows for the 'un-declaration' of xml:lang with
the empty string.
</p>
</div>
</xs:documentation>
</xs:annotation>
<xs:simpleType>
<xs:union memberTypes="xs:language">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value=""/>
</xs:restriction>
</xs:simpleType>
</xs:union>
</xs:simpleType>
</xs:attribute>
<xs:attribute name="space">
<xs:annotation>
<xs:documentation>
<div>
<h3>space (as an attribute name)</h3>
<p>
denotes an attribute whose
value is a keyword indicating what whitespace processing
discipline is intended for the content of the element; its
value is inherited. This name is reserved by virtue of its
definition in the XML specification.</p>
</div>
</xs:documentation>
</xs:annotation>
<xs:simpleType>
<xs:restriction base="xs:NCName">
<xs:enumeration value="default"/>
<xs:enumeration value="preserve"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:attribute name="base" type="xs:anyURI"> <xs:annotation>
<xs:documentation>
<div>
<h3>base (as an attribute name)</h3>
<p>
denotes an attribute whose value
provides a URI to be used as the base for interpreting any
relative URIs in the scope of the element on which it
appears; its value is inherited. This name is reserved
by virtue of its definition in the XML Base specification.</p>
<p>
See <a
href="http://www.w3.org/TR/xmlbase/">http://www.w3.org/TR/xmlbase/</a>
for information about this attribute.
</p>
</div>
</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="id" type="xs:ID">
<xs:annotation>
<xs:documentation>
<div>
<h3>id (as an attribute name)</h3>
<p>
denotes an attribute whose value
should be interpreted as if declared to be of type ID.
This name is reserved by virtue of its definition in the
xml:id specification.</p>
<p>
See <a
href="http://www.w3.org/TR/xml-id/">http://www.w3.org/TR/xml-id/</a>
for information about this attribute.
</p>
</div>
</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attributeGroup name="specialAttrs">
<xs:attribute ref="xml:base"/>
<xs:attribute ref="xml:lang"/>
<xs:attribute ref="xml:space"/>
<xs:attribute ref="xml:id"/>
</xs:attributeGroup>
<xs:annotation>
<xs:documentation>
<div>
<h3>Father (in any context at all)</h3>
<div class="bodytext">
<p>
denotes Jon Bosak, the chair of
the original XML Working Group. This name is reserved by
the following decision of the W3C XML Plenary and
XML Coordination groups:
</p>
<blockquote>
<p>
In appreciation for his vision, leadership and
dedication the W3C XML Plenary on this 10th day of
February, 2000, reserves for Jon Bosak in perpetuity
the XML name "xml:Father".
</p>
</blockquote>
</div>
</div>
</xs:documentation>
</xs:annotation>
<xs:annotation>
<xs:documentation>
<div xml:id="usage" id="usage">
<h2><a name="usage">About this schema document</a></h2>
<div class="bodytext">
<p>
This schema defines attributes and an attribute group suitable
for use by schemas wishing to allow <code>xml:base</code>,
<code>xml:lang</code>, <code>xml:space</code> or
<code>xml:id</code> attributes on elements they define.
</p>
<p>
To enable this, such a schema must import this schema for
the XML namespace, e.g. as follows:
</p>
<pre>
&lt;schema . . .>
. . .
&lt;import namespace="http://www.w3.org/XML/1998/namespace"
schemaLocation="http://www.w3.org/2001/xml.xsd"/>
</pre>
<p>
or
</p>
<pre>
&lt;import namespace="http://www.w3.org/XML/1998/namespace"
schemaLocation="http://www.w3.org/2009/01/xml.xsd"/>
</pre>
<p>
Subsequently, qualified reference to any of the attributes or the
group defined below will have the desired effect, e.g.
</p>
<pre>
&lt;type . . .>
. . .
&lt;attributeGroup ref="xml:specialAttrs"/>
</pre>
<p>
will define a type which will schema-validate an instance element
with any of those attributes.
</p>
</div>
</div>
</xs:documentation>
</xs:annotation>
<xs:annotation>
<xs:documentation>
<div id="nsversioning" xml:id="nsversioning">
<h2><a name="nsversioning">Versioning policy for this schema document</a></h2>
<div class="bodytext">
<p>
In keeping with the XML Schema WG's standard versioning
policy, this schema document will persist at
<a href="http://www.w3.org/2009/01/xml.xsd">
http://www.w3.org/2009/01/xml.xsd</a>.
</p>
<p>
At the date of issue it can also be found at
<a href="http://www.w3.org/2001/xml.xsd">
http://www.w3.org/2001/xml.xsd</a>.
</p>
<p>
The schema document at that URI may however change in the future,
in order to remain compatible with the latest version of XML
Schema itself, or with the XML namespace itself. In other words,
if the XML Schema or XML namespaces change, the version of this
document at <a href="http://www.w3.org/2001/xml.xsd">
http://www.w3.org/2001/xml.xsd
</a>
will change accordingly; the version at
<a href="http://www.w3.org/2009/01/xml.xsd">
http://www.w3.org/2009/01/xml.xsd
</a>
will not change.
</p>
<p>
Previous dated (and unchanging) versions of this schema
document are at:
</p>
<ul>
<li><a href="http://www.w3.org/2009/01/xml.xsd">
http://www.w3.org/2009/01/xml.xsd</a></li>
<li><a href="http://www.w3.org/2007/08/xml.xsd">
http://www.w3.org/2007/08/xml.xsd</a></li>
<li><a href="http://www.w3.org/2004/10/xml.xsd">
http://www.w3.org/2004/10/xml.xsd</a></li>
<li><a href="http://www.w3.org/2001/03/xml.xsd">
http://www.w3.org/2001/03/xml.xsd</a></li>
</ul>
</div>
</div>
</xs:documentation>
</xs:annotation>
</xs:schema>

View File

@@ -0,0 +1,3 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo [<!ELEMENT foo ANY > <!ENTITY xxe SYSTEM "file:///dev/urandom" >]>
<foo>&xxe;</foo>

View File

@@ -0,0 +1 @@
this is not xml

View File

@@ -0,0 +1 @@
<ssp:Base64Element xmlns:ssp="urn:x-simplesamlphp:namespace">/CTj03d1DB5e2t7CTo9BEzCf5S9NRzwnBgZRlm32REI=</ssp:Base64Element>

View File

@@ -0,0 +1 @@
<ssp:Element xmlns:ssp="urn:x-simplesamlphp:namespace" integer="2" boolean="false" text="text" />

View File

@@ -0,0 +1 @@
<ssp:ExtendableAttributesElement xmlns:ssp="urn:x-simplesamlphp:namespace" ssp:attr1="testval1" ssp:attr2="testval2" />

View File

@@ -0,0 +1,4 @@
<ssp:ExtendableElement xmlns:ssp="urn:x-simplesamlphp:namespace">
<ssp:Chunk>some</ssp:Chunk>
<dummy:Chunk xmlns:dummy="urn:custom:dummy">some</dummy:Chunk>
</ssp:ExtendableElement>

View File

@@ -0,0 +1 @@
<ssp:LocalizedStringElement xmlns:ssp="urn:x-simplesamlphp:namespace" xml:lang="en">test</ssp:LocalizedStringElement>

View File

@@ -0,0 +1 @@
<ssp:QNameElement xmlns:ssp="urn:x-simplesamlphp:namespace" xmlns:env="http://www.w3.org/2003/05/soap-envelope">env:Sender</ssp:QNameElement>

View File

@@ -0,0 +1 @@
<ssp:StringElement xmlns:ssp="urn:x-simplesamlphp:namespace">test</ssp:StringElement>

View File

@@ -0,0 +1,314 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML;
use DOMElement;
use RuntimeException;
use SimpleSAML\XML\Assert\Assert;
use SimpleSAML\XML\Exception\MissingAttributeException;
use SimpleSAML\XML\Exception\SchemaViolationException;
use SimpleSAML\XML\SerializableElementTrait;
use function array_slice;
use function defined;
use function explode;
use function func_num_args;
use function in_array;
use function intval;
use function join;
use function strval;
/**
* Abstract class to be implemented by all classes
*
* @package simplesamlphp/xml-common
*/
abstract class AbstractElement implements SerializableElementInterface
{
use SerializableElementTrait;
/**
* Create a document structure for this element
*
* @param \DOMElement|null $parent The element we should append to.
* @return \DOMElement
*/
public function instantiateParentElement(?DOMElement $parent = null): DOMElement
{
$qualifiedName = $this->getQualifiedName();
$namespace = static::getNamespaceURI();
if ($parent === null) {
$parent = DOMDocumentFactory::create();
$e = $parent->createElementNS($namespace, $qualifiedName);
} else {
$doc = $parent->ownerDocument;
Assert::notNull($doc);
$e = $doc->createElementNS($namespace, $qualifiedName);
}
$parent->appendChild($e);
return $e;
}
/**
* Get the value of an attribute from a given element.
*
* @param \DOMElement $xml The element where we should search for the attribute.
* @param string $name The name of the attribute.
* @return string
*
* @throws \SimpleSAML\XML\Exception\MissingAttributeException if the attribute is missing from the element
*/
public static function getAttribute(DOMElement $xml, string $name): string
{
$prefix = static::getNamespacePrefix();
$localName = static::getLocalName();
$qName = $prefix ? ($prefix . ':' . $localName) : $localName;
Assert::true(
$xml->hasAttribute($name) && func_num_args() === 2,
sprintf('Missing \'%s\' attribute on %s.', $name, $qName),
MissingAttributeException::class,
);
return $xml->getAttribute($name);
}
/**
* Get the value of an attribute from a given element.
*
* @param \DOMElement $xml The element where we should search for the attribute.
* @param string $name The name of the attribute.
* @param string|null $default The default to return in case the attribute does not exist and it is optional.
* @return ($default is string ? string : string|null)
*/
public static function getOptionalAttribute(DOMElement $xml, string $name, ?string $default = null): ?string
{
if (!$xml->hasAttribute($name)) {
return $default;
}
return self::getAttribute($xml, $name);
}
/**
* @param \DOMElement $xml The element where we should search for the attribute.
* @param string $name The name of the attribute.
* @return bool
*
* @throws \SimpleSAML\XML\Exception\MissingAttributeException if the attribute is missing from the element
* @throws \SimpleSAML\Assert\AssertionFailedException if the attribute is not a boolean
*/
public static function getBooleanAttribute(DOMElement $xml, string $name): bool
{
$value = self::getAttribute($xml, $name);
$prefix = static::getNamespacePrefix();
$localName = static::getLocalName();
$qName = $prefix ? ($prefix . ':' . $localName) : $localName;
Assert::oneOf(
$value,
['0', '1', 'false', 'true'],
sprintf('The \'%s\' attribute of %s must be a boolean.', $name, $qName),
);
return in_array($value, ['1', 'true'], true);
}
/**
* @param \DOMElement $xml The element where we should search for the attribute.
* @param string $name The name of the attribute.
* @param bool|null $default The default to return in case the attribute does not exist and it is optional.
* @return ($default is bool ? bool : bool|null)
*
* @throws \SimpleSAML\Assert\AssertionFailedException if the attribute is not a boolean
*/
public static function getOptionalBooleanAttribute(DOMElement $xml, string $name, ?bool $default = null): ?bool
{
if (!$xml->hasAttribute($name)) {
return $default;
}
return self::getBooleanAttribute($xml, $name);
}
/**
* Get the integer value of an attribute from a given element.
*
* @param \DOMElement $xml The element where we should search for the attribute.
* @param string $name The name of the attribute.
* @return int
*
* @throws \SimpleSAML\XML\Exception\MissingAttributeException if the attribute is missing from the element
* @throws \SimpleSAML\Assert\AssertionFailedException if the attribute is not an integer
*/
public static function getIntegerAttribute(DOMElement $xml, string $name): int
{
$value = self::getAttribute($xml, $name);
$prefix = static::getNamespacePrefix();
$localName = static::getLocalName();
$qName = $prefix ? ($prefix . ':' . $localName) : $localName;
Assert::numeric(
$value,
sprintf('The \'%s\' attribute of %s must be numerical.', $name, $qName),
);
return intval($value);
}
/**
* Get the integer value of an attribute from a given element.
*
* @param \DOMElement $xml The element where we should search for the attribute.
* @param string $name The name of the attribute.
* @param int|null $default The default to return in case the attribute does not exist and it is optional.
* @return ($default is int ? int : int|null)
*
* @throws \SimpleSAML\Assert\AssertionFailedException if the attribute is not an integer
*/
public static function getOptionalIntegerAttribute(DOMElement $xml, string $name, ?int $default = null): ?int
{
if (!$xml->hasAttribute($name)) {
return $default;
}
return self::getIntegerAttribute($xml, $name);
}
/**
* Static method that processes a fully namespaced class name and returns the name of the class from it.
*
* @param string $class
* @return string
*/
public static function getClassName(string $class): string
{
$ncName = join('', array_slice(explode('\\', $class), -1));
Assert::validNCName($ncName, SchemaViolationException::class);
return $ncName;
}
/**
* Get the XML qualified name (prefix:name) of the element represented by this class.
*
* @return string
*/
public function getQualifiedName(): string
{
$prefix = static::getNamespacePrefix();
$qName = $prefix ? ($prefix . ':' . static::getLocalName()) : static::getLocalName();
Assert::validQName($qName, SchemaViolationException::class);
return $qName;
}
/**
* Extract localized names from the children of a given element.
*
* @param \DOMElement $parent The element we want to search.
* @return array<static> An array of objects of this class.
*/
public static function getChildrenOfClass(DOMElement $parent): array
{
$ret = [];
foreach ($parent->childNodes as $node) {
if (
$node instanceof DOMElement
&& $node->namespaceURI === static::getNamespaceURI()
&& $node->localName === static::getLocalName()
) {
// Normalize the DOMElement by importing it into a clean empty document
$newDoc = DOMDocumentFactory::create();
/** @var \DOMElement $node */
$node = $newDoc->appendChild($newDoc->importNode($node, true));
$ret[] = static::fromXML($node);
}
}
return $ret;
}
/**
* Get the namespace for the element.
*
* @return string|null
*/
public static function getNamespaceURI(): ?string
{
Assert::true(
defined('static::NS'),
self::getClassName(static::class)
. '::NS constant must be defined and set to the namespace for the XML-class it represents.',
RuntimeException::class,
);
// @phpstan-ignore classConstant.notFound
Assert::nullOrValidURI(static::NS, SchemaViolationException::class); // @phpstan-ignore-line
// @phpstan-ignore classConstant.notFound
return static::NS; // @phpstan-ignore-line
}
/**
* Get the namespace-prefix for the element.
*
* @return string
*/
public static function getNamespacePrefix(): string
{
Assert::true(
defined('static::NS_PREFIX'),
self::getClassName(static::class)
. '::NS_PREFIX constant must be defined and set to the namespace prefix for the XML-class it represents.',
RuntimeException::class,
);
// @phpstan-ignore classConstant.notFound
return strval(static::NS_PREFIX); // @phpstan-ignore-line
}
/**
* Get the local name for the element.
*
* @return string
*/
public static function getLocalName(): string
{
if (defined('static::LOCALNAME')) {
$ncName = static::LOCALNAME;
} else {
$ncName = self::getClassName(static::class);
}
Assert::validNCName($ncName, SchemaViolationException::class);
return $ncName;
}
/**
* Test if an object, at the state it's in, would produce an empty XML-element
*
* @codeCoverageIgnore
* @return bool
*/
public function isEmptyElement(): bool
{
return false;
}
}

View File

@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML;
/**
* interface class to be implemented by all the classes that represent an arrayizable XML element
*
* @package simplesamlphp/xml-common
*/
interface ArrayizableElementInterface
{
/**
* Create a class from an array
*
* @param array<string, mixed> $data
* @return static
*/
public static function fromArray(array $data): static;
/**
* Create an array from this class
*
* @return array<string, mixed>
*/
public function toArray(): array;
}

View File

@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML\Assert;
use SimpleSAML\Assert\Assert as BaseAssert;
/**
* @package simplesamlphp/xml-common
*
* @method static void validHexBinary(mixed $value, string $message = '', string $exception = '')
* @method static void validNMToken(mixed $value, string $message = '', string $exception = '')
* @method static void validNMTokens(mixed $value, string $message = '', string $exception = '')
* @method static void validDuration(mixed $value, string $message = '', string $exception = '')
* @method static void validDateTime(mixed $value, string $message = '', string $exception = '')
* @method static void validNCName(mixed $value, string $message = '', string $exception = '')
* @method static void validQName(mixed $value, string $message = '', string $exception = '')
* @method static void nullOrValidHexBinary(mixed $value, string $message = '', string $exception = '')
* @method static void nullOrValidNMToken(mixed $value, string $message = '', string $exception = '')
* @method static void nullOrValidNMTokens(mixed $value, string $message = '', string $exception = '')
* @method static void nullOrValidDuration(mixed $value, string $message = '', string $exception = '')
* @method static void nullOrValidDateTime(mixed $value, string $message = '', string $exception = '')
* @method static void nullOrValidNCName(mixed $value, string $message = '', string $exception = '')
* @method static void nullOrValidQName(mixed $value, string $message = '', string $exception = '')
* @method static void allValidHexBinary(mixed $value, string $message = '', string $exception = '')
* @method static void allValidNMToken(mixed $value, string $message = '', string $exception = '')
* @method static void allValidNMTokens(mixed $value, string $message = '', string $exception = '')
* @method static void allValidDuration(mixed $value, string $message = '', string $exception = '')
* @method static void allValidDateTime(mixed $value, string $message = '', string $exception = '')
* @method static void allValidNCName(mixed $value, string $message = '', string $exception = '')
* @method static void allValidQName(mixed $value, string $message = '', string $exception = '')
*/
class Assert extends BaseAssert
{
use DateTimeTrait;
use DurationTrait;
use HexBinTrait;
use NamesTrait;
use TokensTrait;
}

View File

@@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML\Assert;
use InvalidArgumentException;
use function filter_var;
use function sprintf;
/**
* @package simplesamlphp/xml-common
*/
trait DateTimeTrait
{
/** @var string */
private static string $datetime_regex = '/-?[0-9]{4}-(((0(1|3|5|7|8)|1(0|2))-(0[1-9]|(1|2)[0-9]|3[0-1]))|((0(4|6|9)|11)-(0[1-9]|(1|2)[0-9]|30))|(02-(0[1-9]|(1|2)[0-9])))T([0-1][0-9]|2[0-4]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9])(\.[0-999])?((\+|-)([0-1][0-9]|2[0-4]):(0[0-9]|[1-5][0-9])|Z)?/i';
/***********************************************************************************
* NOTE: Custom assertions may be added below this line. *
* They SHOULD be marked as `protected` to ensure the call is forced *
* through __callStatic(). *
* Assertions marked `public` are called directly and will *
* not handle any custom exception passed to it. *
***********************************************************************************/
/**
* @param string $value
* @param string $message
*/
protected static function validDateTime(string $value, string $message = ''): void
{
if (filter_var($value, FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => self::$datetime_regex]]) === false) {
throw new InvalidArgumentException(sprintf(
$message ?: '\'%s\' is not a valid xs:dateTime',
$value,
));
}
}
}

View File

@@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML\Assert;
use InvalidArgumentException;
use function filter_var;
use function sprintf;
/**
* @package simplesamlphp/xml-common
*/
trait DurationTrait
{
/** @var string */
private static string $duration_regex = '/^([-+]?)P(?!$)(?:(?<years>\d+(?:[\.\,]\d+)?)Y)?(?:(?<months>\d+(?:[\.\,]\d+)?)M)?(?:(?<weeks>\d+(?:[\.\,]\d+)?)W)?(?:(?<days>\d+(?:[\.\,]\d+)?)D)?(T(?=\d)(?:(?<hours>\d+(?:[\.\,]\d+)?)H)?(?:(?<minutes>\d+(?:[\.\,]\d+)?)M)?(?:(?<seconds>\d+(?:[\.\,]\d+)?)S)?)?$/D';
/***********************************************************************************
* NOTE: Custom assertions may be added below this line. *
* They SHOULD be marked as `protected` to ensure the call is forced *
* through __callStatic(). *
* Assertions marked `public` are called directly and will *
* not handle any custom exception passed to it. *
***********************************************************************************/
/**
* @param string $value
* @param string $message
*/
protected static function validDuration(string $value, string $message = ''): void
{
if (filter_var($value, FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => self::$duration_regex]]) === false) {
throw new InvalidArgumentException(sprintf(
$message ?: '\'%s\' is not a valid xs:duration',
$value,
));
}
}
}

View File

@@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML\Assert;
use InvalidArgumentException;
use function filter_var;
use function sprintf;
/**
* @package simplesamlphp/xml-common
*/
trait HexBinTrait
{
/** @var string */
private static string $hexbin_regex = '/^([0-9a-fA-F]{2})+$/D';
/***********************************************************************************
* NOTE: Custom assertions may be added below this line. *
* They SHOULD be marked as `protected` to ensure the call is forced *
* through __callStatic(). *
* Assertions marked `public` are called directly and will *
* not handle any custom exception passed to it. *
***********************************************************************************/
/**
* @param string $value
* @param string $message
*/
protected static function validHexBinary(string $value, string $message = ''): void
{
$result = true;
if (filter_var($value, FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => self::$hexbin_regex]]) === false) {
$result = false;
}
if ($result === false) {
throw new InvalidArgumentException(sprintf(
$message ?: '\'%s\' is not a valid hexBinary string',
$value,
));
}
}
}

View File

@@ -0,0 +1,63 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML\Assert;
use InvalidArgumentException;
use function filter_var;
use function sprintf;
/**
* @package simplesamlphp/xml-common
*/
trait NamesTrait
{
/** @var string */
private static string $ncname_regex = '/^[a-zA-Z_][\w.-]*$/D';
/** @var string */
private static string $qname_regex = '/^[a-zA-Z_][\w.-]*:[a-zA-Z_][\w.-]*$/D';
/***********************************************************************************
* NOTE: Custom assertions may be added below this line. *
* They SHOULD be marked as `protected` to ensure the call is forced *
* through __callStatic(). *
* Assertions marked `public` are called directly and will *
* not handle any custom exception passed to it. *
***********************************************************************************/
/**
* @param string $value
* @param string $message
*/
protected static function validNCName(string $value, string $message = ''): void
{
if (filter_var($value, FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => self::$ncname_regex]]) === false) {
throw new InvalidArgumentException(sprintf(
$message ?: '\'%s\' is not a valid non-colonized name (NCName)',
$value,
));
}
}
/**
* @param string $value
* @param string $message
*/
protected static function validQName(string $value, string $message = ''): void
{
if (
filter_var($value, FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => self::$qname_regex]]) === false &&
filter_var($value, FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => self::$ncname_regex]]) === false
) {
throw new InvalidArgumentException(sprintf(
$message ?: '\'%s\' is not a valid qualified name (QName)',
$value,
));
}
}
}

View File

@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML\Assert;
use InvalidArgumentException;
use function filter_var;
use function sprintf;
/**
* @package simplesamlphp/xml-common
*/
trait TokensTrait
{
/** @var string */
private static string $nmtoken_regex = '/^[\w.:-]+$/Du';
/** @var string */
private static string $nmtokens_regex = '/^([\w.:-]+)([\s][\w.:-]+)*$/Du';
/***********************************************************************************
* NOTE: Custom assertions may be added below this line. *
* They SHOULD be marked as `protected` to ensure the call is forced *
* through __callStatic(). *
* Assertions marked `public` are called directly and will *
* not handle any custom exception passed to it. *
***********************************************************************************/
/**
* @param string $value
* @param string $message
*/
protected static function validNMToken(string $value, string $message = ''): void
{
if (filter_var($value, FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => self::$nmtoken_regex]]) === false) {
throw new InvalidArgumentException(sprintf(
$message ?: '\'%s\' is not a valid xs:NMTOKEN',
$value,
));
}
}
/**
* @param string $value
* @param string $message
*/
protected static function validNMTokens(string $value, string $message = ''): void
{
if (filter_var($value, FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => self::$nmtokens_regex]]) === false) {
throw new InvalidArgumentException(sprintf(
$message ?: '\'%s\' is not a valid xs:NMTOKENS',
$value,
));
}
}
}

View File

@@ -0,0 +1,188 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML;
use DOMAttr;
use DOMElement;
use SimpleSAML\Assert\Assert;
use function array_keys;
/**
* Class to represent an arbitrary namespaced attribute.
*
* @package simplesamlphp/xml-common
*/
final class Attribute implements ArrayizableElementInterface
{
/**
* Create an Attribute class
*
* @param string|null $namespaceURI
* @param string|null $namespacePrefix
* @param string $attrName
* @param string $attrValue
*/
public function __construct(
protected ?string $namespaceURI,
protected ?string $namespacePrefix,
protected string $attrName,
protected string $attrValue,
) {
Assert::nullOrStringNotEmpty($namespaceURI);
if ($namespaceURI !== null) {
Assert::stringNotEmpty($namespacePrefix);
}
Assert::stringNotEmpty($attrName);
Assert::string($attrValue);
}
/**
* Collect the value of the namespaceURI-property
*
* @return string|null
*/
public function getNamespaceURI(): ?string
{
return $this->namespaceURI;
}
/**
* Collect the value of the namespacePrefix-property
*
* @return string|null
*/
public function getNamespacePrefix(): ?string
{
return $this->namespacePrefix;
}
/**
* Collect the value of the localName-property
*
* @return string
*/
public function getAttrName(): string
{
return $this->attrName;
}
/**
* Collect the value of the value-property
*
* @return string
*/
public function getAttrValue(): string
{
return $this->attrValue;
}
/**
* Create a class from XML
*
* @param \DOMAttr $attr
* @return static
*/
public static function fromXML(DOMAttr $attr): static
{
return new static($attr->namespaceURI, $attr->prefix, $attr->localName, $attr->value);
}
/**
* Create XML from this class
*
* @param \DOMElement $parent
* @return \DOMElement
*/
public function toXML(DOMElement $parent): DOMElement
{
$parent->setAttributeNS(
$this->getNamespaceURI(),
!in_array($this->getNamespacePrefix(), ['', null])
? ($this->getNamespacePrefix() . ':' . $this->getAttrName())
: $this->getAttrName(),
$this->getAttrValue(),
);
return $parent;
}
/**
* Create a class from an array
*
* @param array{namespaceURI: string, namespacePrefix: string|null, attrName: string, attrValue: mixed} $data
* @return static
*/
public static function fromArray(array $data): static
{
$data = self::processArrayContents($data);
return new static(
$data['namespaceURI'],
$data['namespacePrefix'],
$data['attrName'],
$data['attrValue'],
);
}
/**
* Validates an array representation of this object and returns the same array with rationalized keys
*
* @param array{namespaceURI: string, namespacePrefix: string|null, attrName: string, attrValue: mixed} $data
* @return array{namespaceURI: string, namespacePrefix: string|null, attrName: string, attrValue: mixed}
*/
private static function processArrayContents(array $data): array
{
$data = array_change_key_case($data, CASE_LOWER);
/** @var array{namespaceuri: string, namespaceprefix: string|null, attrname: string, attrvalue: mixed} $data */
Assert::allOneOf(
array_keys($data),
['namespaceuri', 'namespaceprefix', 'attrname', 'attrvalue'],
);
Assert::keyExists($data, 'namespaceuri');
Assert::keyExists($data, 'namespaceprefix');
Assert::keyExists($data, 'attrname');
Assert::keyExists($data, 'attrvalue');
Assert::nullOrStringNotEmpty($data['namespaceuri']);
Assert::string($data['namespaceprefix']);
Assert::stringNotEmpty($data['attrname']);
Assert::string($data['attrvalue']);
return [
'namespaceURI' => $data['namespaceuri'],
'namespacePrefix' => $data['namespaceprefix'],
'attrName' => $data['attrname'],
'attrValue' => $data['attrvalue'],
];
}
/**
* Create an array from this class
*
* @return array{attrName: string, attrValue: string, namespacePrefix: string, namespaceURI: null|string}
*/
public function toArray(): array
{
return [
'namespaceURI' => $this->getNamespaceURI(),
'namespacePrefix' => $this->getNamespacePrefix(),
'attrName' => $this->getAttrName(),
'attrValue' => $this->getAttrValue(),
];
}
}

View File

@@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML;
use DOMElement;
use SimpleSAML\Assert\Assert;
use SimpleSAML\XML\Exception\SchemaViolationException;
use function str_replace;
/**
* Trait grouping common functionality for simple elements with base64 textContent
*
* @package simplesamlphp/xml-common
*/
trait Base64ElementTrait
{
use StringElementTrait;
/**
* Sanitize the content of the element.
*
* @param string $content The unsanitized textContent
* @throws \Exception on failure
* @return string
*/
protected function sanitizeContent(string $content): string
{
return str_replace(["\f", "\r", "\n", "\t", "\v", ' '], '', $content);
}
/**
* Validate the content of the element.
*
* @param string $content The value to go in the XML textContent
* @throws \Exception on failure
* @return void
*/
protected function validateContent(string $content): void
{
// Note: content must already be sanitized before validating
Assert::validBase64(
$this->sanitizeContent($content),
SchemaViolationException::class,
);
}
/** @return string */
abstract public static function getLocalName(): string;
/**
* Create a document structure for this element
*
* @param \DOMElement|null $parent The element we should append to.
* @return \DOMElement
*/
abstract public function instantiateParentElement(?DOMElement $parent = null): DOMElement;
}

View File

@@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML;
use DOMElement;
use SimpleSAML\Assert\Assert;
use SimpleSAML\XML\Exception\InvalidDOMElementException;
use SimpleSAML\XML\Exception\SchemaViolationException;
/**
* Trait grouping common functionality for simple boolean elements
*
* @package simplesamlphp/xml-common
*/
trait BooleanElementTrait
{
use StringElementTrait;
/**
* Validate the content of the element.
*
* @param string $content The value to go in the XML textContent
* @throws \Exception on failure
* @return void
*/
protected function validateContent(string $content): void
{
Assert::oneOf(
$content,
['0', '1', 'false', 'true'],
sprintf('The value of %s must be a boolean, "%s" given.', $this->getQualifiedName(), $content),
SchemaViolationException::class,
);
}
/**
* Convert XML into a class instance
*
* @param \DOMElement $xml The XML element we should load
* @return static
*
* @throws \SimpleSAML\XML\Exception\InvalidDOMElementException
* If the qualified name of the supplied element is wrong
*/
public static function fromXML(DOMElement $xml): static
{
Assert::same($xml->localName, static::getLocalName(), InvalidDOMElementException::class);
Assert::same($xml->namespaceURI, static::NS, InvalidDOMElementException::class);
return new static($xml->textContent);
}
/**
* @param \DOMElement|null $parent
* @return \DOMElement
*/
final public function toXML(?DOMElement $parent = null): DOMElement
{
$e = $this->instantiateParentElement($parent);
$e->textContent = $this->getContent();
return $e;
}
}

View File

@@ -0,0 +1,324 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML;
use DOMElement;
use SimpleSAML\XML\Assert\Assert;
use SimpleSAML\XML\Exception\MissingAttributeException;
use SimpleSAML\XML\Exception\SchemaViolationException;
use SimpleSAML\XML\SerializableElementTrait;
use function in_array;
use function intval;
/**
* Serializable class used to hold an XML element.
*
* @package simplesamlphp/xml-common
*/
final class Chunk implements SerializableElementInterface
{
use SerializableElementTrait;
/**
* The localName of the element.
*
* @var string
*/
protected string $localName;
/**
* The namespaceURI of this element.
*
* @var string|null
*/
protected ?string $namespaceURI;
/**
* The prefix of this element.
*
* @var string
*/
protected string $prefix;
/**
* Create an XML Chunk from a copy of the given \DOMElement.
*
* @param \DOMElement $xml The element we should copy.
*/
public function __construct(
protected DOMElement $xml,
) {
$this->setLocalName($xml->localName);
$this->setNamespaceURI($xml->namespaceURI);
$this->setPrefix($xml->prefix);
}
/**
* Collect the value of the localName-property
*
* @return string
*/
public function getLocalName(): string
{
return $this->localName;
}
/**
* Set the value of the localName-property
*
* @param string $localName
* @throws \SimpleSAML\Assert\AssertionFailedException if $localName is an empty string
*/
public function setLocalName(string $localName): void
{
Assert::validNCName($localName, SchemaViolationException::class); // Covers the empty string
$this->localName = $localName;
}
/**
* Collect the value of the namespaceURI-property
*
* @return string|null
*/
public function getNamespaceURI(): ?string
{
return $this->namespaceURI;
}
/**
* Set the value of the namespaceURI-property
*
* @param string|null $namespaceURI
*/
protected function setNamespaceURI(?string $namespaceURI = null): void
{
Assert::nullOrValidURI($namespaceURI, SchemaViolationException::class);
$this->namespaceURI = $namespaceURI;
}
/**
* Get this \DOMElement.
*
* @return \DOMElement This element.
*/
public function getXML(): DOMElement
{
return $this->xml;
}
/**
* Collect the value of the prefix-property
*
* @return string
*/
public function getPrefix(): string
{
return $this->prefix;
}
/**
* Set the value of the prefix-property
*
* @param string|null $prefix
*/
protected function setPrefix(?string $prefix = null): void
{
$this->prefix = strval($prefix);
}
/**
* Get the XML qualified name (prefix:name, or just name when not prefixed)
* of the element represented by this class.
*
* @return string
*/
public function getQualifiedName(): string
{
$prefix = $this->getPrefix();
if (empty($prefix)) {
return $this->getLocalName();
} else {
return $prefix . ':' . $this->getLocalName();
}
}
/**
* @param \DOMElement $xml The element where we should search for the attribute.
* @param string $name The name of the attribute.
* @return string
*
* @throws \SimpleSAML\XML\Exception\MissingAttributeException if the attribute is missing from the element
*/
public static function getAttribute(DOMElement $xml, string $name): string
{
Assert::true(
$xml->hasAttribute($name),
'Missing \'' . $name . '\' attribute on ' . $xml->prefix . ':' . $xml->localName . '.',
MissingAttributeException::class,
);
return $xml->getAttribute($name);
}
/**
* @param \DOMElement $xml The element where we should search for the attribute.
* @param string $name The name of the attribute.
* @param string|null $default The default to return in case the attribute does not exist and it is optional.
* @return ($default is string ? string : null)
*/
public static function getOptionalAttribute(DOMElement $xml, string $name, ?string $default = null): ?string
{
if (!$xml->hasAttribute($name)) {
return $default;
}
return $xml->getAttribute($name);
}
/**
* @param \DOMElement $xml The element where we should search for the attribute.
* @param string $name The name of the attribute.
* @return bool
*
* @throws \SimpleSAML\XML\Exception\MissingAttributeException if the attribute is missing from the element
* @throws \SimpleSAML\Assert\AssertionFailedException if the attribute is not a boolean
*/
public static function getBooleanAttribute(DOMElement $xml, string $name): bool
{
$value = self::getAttribute($xml, $name);
Assert::oneOf(
$value,
['0', '1', 'false', 'true'],
'The \'' . $name . '\' attribute of ' . $xml->prefix . ':' . $xml->localName . ' must be boolean.',
);
return in_array($value, ['1', 'true'], true);
}
/**
* @param \DOMElement $xml The element where we should search for the attribute.
* @param string $name The name of the attribute.
* @param bool|null $default The default to return in case the attribute does not exist and it is optional.
* @return ($default is bool ? bool : null)
*
* @throws \SimpleSAML\Assert\AssertionFailedException if the attribute is not a boolean
*/
public static function getOptionalBooleanAttribute(DOMElement $xml, string $name, ?bool $default = null): ?bool
{
if (!$xml->hasAttribute($name)) {
return $default;
}
return self::getBooleanAttribute($xml, $name);
}
/**
* Get the integer value of an attribute from a given element.
*
* @param \DOMElement $xml The element where we should search for the attribute.
* @param string $name The name of the attribute.
* @return int
*
* @throws \SimpleSAML\XML\Exception\MissingAttributeException if the attribute is missing from the element
* @throws \SimpleSAML\Assert\AssertionFailedException if the attribute is not an integer
*/
public static function getIntegerAttribute(DOMElement $xml, string $name): int
{
$value = self::getAttribute($xml, $name);
Assert::numeric(
$value,
'The \'' . $name . '\' attribute of ' . $xml->prefix . ':' . $xml->localName . ' must be numerical.',
);
return intval($value);
}
/**
* Get the integer value of an attribute from a given element.
*
* @param \DOMElement $xml The element where we should search for the attribute.
* @param string $name The name of the attribute.
* @param int|null $default The default to return in case the attribute does not exist and it is optional.
* @return ($default is int ? int : null)
*
* @throws \SimpleSAML\Assert\AssertionFailedException if the attribute is not an integer
*/
public static function getOptionalIntegerAttribute(DOMElement $xml, string $name, ?int $default = null): ?int
{
if (!$xml->hasAttribute($name)) {
return $default;
}
return self::getIntegerAttribute($xml, $name);
}
/**
* Test if an object, at the state it's in, would produce an empty XML-element
*
* @return bool
*/
public function isEmptyElement(): bool
{
/** @var \DOMElement $xml */
$xml = $this->getXML();
return ($xml->childNodes->length === 0) && ($xml->attributes->count() === 0);
}
/**
* @param \DOMElement $xml
* @return static
*/
public static function fromXML(DOMElement $xml): static
{
return new static($xml);
}
/**
* Append this XML element to a different XML element.
*
* @param \DOMElement|null $parent The element we should append this element to.
* @return \DOMElement The new element.
*/
public function toXML(?DOMElement $parent = null): DOMElement
{
if ($parent === null) {
$doc = DOMDocumentFactory::create();
} else {
$doc = $parent->ownerDocument;
Assert::notNull($doc);
}
if ($parent === null) {
$parent = $doc;
}
$parent->appendChild($doc->importNode($this->getXML(), true));
return $doc->documentElement;
}
}

View File

@@ -0,0 +1,54 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML;
/**
* Various XML constants.
*
* @package simplesamlphp/xml-common
*/
class Constants
{
/**
* The namespace fox XML.
*/
public const NS_XML = 'http://www.w3.org/XML/1998/namespace';
/**
* The namespace fox XML schema.
*/
public const NS_XS = 'http://www.w3.org/2001/XMLSchema';
/**
* The namespace for XML schema instance.
*/
public const NS_XSI = 'http://www.w3.org/2001/XMLSchema-instance';
/**
* The maximum amount of child nodes this library is willing to handle.
* By specification, this limit is 150K, but that opens up for denial of service.
*/
public const UNBOUNDED_LIMIT = 10000;
/**
* The namespace for the XML Path Language 1.0
*/
public const XPATH10_URI = 'http://www.w3.org/TR/1999/REC-xpath-19991116';
/**
* The namespace for the XML Path Language 2.0
*/
public const XPATH20_URI = 'http://www.w3.org/TR/2010/REC-xpath20-20101214/';
/**
* The namespace for the XML Path Language 3.0
*/
public const XPATH30_URI = 'https://www.w3.org/TR/2014/REC-xpath-30-20140408/';
/**
* The namespace for the XML Path Language 3.1
*/
public const XPATH31_URI = 'https://www.w3.org/TR/2017/REC-xpath-31-20170321/';
}

View File

@@ -0,0 +1,119 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML;
use DOMDocument;
use SimpleSAML\Assert\Assert;
use SimpleSAML\XML\Exception\IOException;
use SimpleSAML\XML\Exception\RuntimeException;
use SimpleSAML\XML\Exception\UnparseableXMLException;
use function file_get_contents;
use function func_num_args;
use function libxml_clear_errors;
use function libxml_set_external_entity_loader;
use function libxml_use_internal_errors;
use function sprintf;
/**
* @package simplesamlphp/xml-common
*/
final class DOMDocumentFactory
{
/**
* @var non-negative-int
* TODO: Add LIBXML_NO_XXE to the defaults when PHP 8.4.0 + libxml 2.13.0 become generally available
*/
public const DEFAULT_OPTIONS = LIBXML_COMPACT | LIBXML_NONET | LIBXML_NSCLEAN;
/**
* @param string $xml
* @param non-negative-int $options
*
* @return \DOMDocument
*/
public static function fromString(
string $xml,
int $options = self::DEFAULT_OPTIONS,
): DOMDocument {
libxml_set_external_entity_loader(null);
Assert::notWhitespaceOnly($xml);
Assert::notRegex(
$xml,
'/<(\s*)!(\s*)DOCTYPE/',
'Dangerous XML detected, DOCTYPE nodes are not allowed in the XML body',
RuntimeException::class,
);
$internalErrors = libxml_use_internal_errors(true);
libxml_clear_errors();
// If LIBXML_NO_XXE is available and option not set
if (func_num_args() === 1 && defined('LIBXML_NO_XXE')) {
$options |= LIBXML_NO_XXE;
}
$domDocument = self::create();
$loaded = $domDocument->loadXML($xml, $options);
libxml_use_internal_errors($internalErrors);
if (!$loaded) {
$error = libxml_get_last_error();
libxml_clear_errors();
throw new UnparseableXMLException($error);
}
libxml_clear_errors();
foreach ($domDocument->childNodes as $child) {
Assert::false(
$child->nodeType === XML_DOCUMENT_TYPE_NODE,
'Dangerous XML detected, DOCTYPE nodes are not allowed in the XML body',
RuntimeException::class,
);
}
return $domDocument;
}
/**
* @param string $file
* @param non-negative-int $options
*
* @return \DOMDocument
*/
public static function fromFile(
string $file,
?string $schemaFile = null,
int $options = self::DEFAULT_OPTIONS,
): DOMDocument {
error_clear_last();
$xml = @file_get_contents($file);
if ($xml === false) {
$e = error_get_last();
$error = $e['message'] ?? "Check that the file exists and can be read.";
throw new IOException("File '$file' was not loaded; $error");
}
Assert::notWhitespaceOnly($xml, sprintf('File "%s" does not have content', $file), RuntimeException::class);
return (func_num_args() < 2) ? static::fromString($xml) : static::fromString($xml, $options);
}
/**
* @param string $version
* @param string $encoding
* @return \DOMDocument
*/
public static function create(string $version = '1.0', string $encoding = 'UTF-8'): DOMDocument
{
return new DOMDocument($version, $encoding);
}
}

View File

@@ -0,0 +1,89 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML;
use DOMElement;
/**
* interface class to be implemented by all the classes that represent an XML element
*
* @package simplesamlphp/xml-common
*/
interface ElementInterface
{
/**
* Get the XML qualified name (prefix:name) of the element represented by this class.
*
* @return string
*/
public function getQualifiedName(): string;
/**
* Get the value of an attribute from a given element.
*
* @param \DOMElement $xml The element where we should search for the attribute.
* @param string $name The name of the attribute.
* @return string
*
* @throws \SimpleSAML\XML\Exception\MissingAttributeException if the attribute is missing from the element
*/
public static function getAttribute(DOMElement $xml, string $name): string;
/**
* Get the value of an attribute from a given element.
*
* @param \DOMElement $xml The element where we should search for the attribute.
* @param string $name The name of the attribute.
* @param string|null $default The default to return in case the attribute does not exist and it is optional.
* @return string|null
*/
public static function getOptionalAttribute(DOMElement $xml, string $name, ?string $default = null): ?string;
/**
* @param \DOMElement $xml The element where we should search for the attribute.
* @param string $name The name of the attribute.
* @return bool
*
* @throws \SimpleSAML\XML\Exception\MissingAttributeException if the attribute is missing from the element
* @throws \SimpleSAML\Assert\AssertionFailedException if the attribute is not a boolean
*/
public static function getBooleanAttribute(DOMElement $xml, string $name): bool;
/**
* @param \DOMElement $xml The element where we should search for the attribute.
* @param string $name The name of the attribute.
* @param bool|null $default The default to return in case the attribute does not exist and it is optional.
* @return bool|null
*
* @throws \SimpleSAML\Assert\AssertionFailedException if the attribute is not a boolean
*/
public static function getOptionalBooleanAttribute(DOMElement $xml, string $name, ?bool $default = null): ?bool;
/**
* @param \DOMElement $xml The element where we should search for the attribute.
* @param string $name The name of the attribute.
* @return int
*
* @throws \SimpleSAML\XML\Exception\MissingAttributeException if the attribute is missing from the element
* @throws \SimpleSAML\Assert\AssertionFailedException if the attribute is not an integer
*/
public static function getIntegerAttribute(DOMElement $xml, string $name): int;
/**
* @param \DOMElement $xml The element where we should search for the attribute.
* @param string $name The name of the attribute.
* @param int|null $default The default to return in case the attribute does not exist and it is optional.
* @return int|null
*
* @throws \SimpleSAML\Assert\AssertionFailedException if the attribute is not an integer
*/
public static function getOptionalIntegerAttribute(DOMElement $xml, string $name, ?int $default = null): ?int;
}

View File

@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML\Exception;
/**
* Class IOException
*
* This exception is thrown when an I/O operation cannot be handled
*
* @package simplesamlphp/xml-common
*/
class IOException extends RuntimeException
{
/**
* @param string|null $message
*/
public function __construct(?string $message = null)
{
parent::__construct($message ?: 'Generic I/O Exception.');
}
}

View File

@@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML\Exception;
use InvalidArgumentException;
/**
* This exception may be raised when the passed DOMElement is of the wrong type
*
* @package simplesamlphp/xml-common
*/
class InvalidDOMElementException extends InvalidArgumentException
{
}

View File

@@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML\Exception;
/**
* This exception may be raised when the passed DOMElement is missing a mandatory attribute
*
* @package simplesamlphp/xml-common
*/
class MissingAttributeException extends SchemaViolationException
{
}

View File

@@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML\Exception;
/**
* This exception may be raised when the passed DOMElement is missing mandatory child-elements
*
* @package simplesamlphp/xml-common
*/
class MissingElementException extends SchemaViolationException
{
}

View File

@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML\Exception;
use RuntimeException as BuiltinRuntimeException;
/**
* Class RuntimeException
*
* This exception is thrown when an error occurs during processing in the library.
*
* @package simplesamlphp/xml-common
*/
class RuntimeException extends BuiltinRuntimeException
{
}

View File

@@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML\Exception;
use SimpleSAML\Assert\AssertionFailedException;
/**
* This exception may be raised when a violation of the SAML2 schema is detected
*
* @package simplesamlphp/xml-common
*/
class SchemaViolationException extends AssertionFailedException
{
}

View File

@@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML\Exception;
/**
* This exception may be raised when the passed DOMElement contains too much child-elements of a certain type
*
* @package simplesamlphp/xml-common
*/
class TooManyElementsException extends SchemaViolationException
{
}

View File

@@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML\Exception;
use LibXMLError;
use function sprintf;
/**
*/
final class UnparseableXMLException extends RuntimeException
{
/** @var string[] */
private const LEVELMAP = [
LIBXML_ERR_WARNING => 'WARNING',
LIBXML_ERR_ERROR => 'ERROR',
LIBXML_ERR_FATAL => 'FATAL',
];
/**
* Constructor for UnparseableXMLException
*
* @param \LibXMLError $error
*/
public function __construct(LibXMLError $error)
{
$message = sprintf(
'Unable to parse XML - "%s[%d]": "%s" in "%s" at line %d on column %d"',
self::LEVELMAP[$error->level],
$error->code,
$error->message,
$error->file ?: '(string)',
$error->line,
$error->column,
);
parent::__construct($message);
}
}

View File

@@ -0,0 +1,269 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML;
use DOMElement;
use RuntimeException;
use SimpleSAML\Assert\Assert;
use SimpleSAML\XML\Attribute;
use SimpleSAML\XML\Constants as C;
use SimpleSAML\XML\XsNamespace as NS;
use function array_diff;
use function array_map;
use function array_search;
use function defined;
use function implode;
use function in_array;
use function is_array;
use function rtrim;
use function sprintf;
/**
* Trait for elements that can have arbitrary namespaced attributes.
*
* @package simplesamlphp/xml-common
*/
trait ExtendableAttributesTrait
{
/**
* Extra (namespace qualified) attributes.
*
* @var array<int, \SimpleSAML\XML\Attribute>
*/
protected array $namespacedAttributes = [];
/**
* Check if a namespace-qualified attribute exists.
*
* @param string|null $namespaceURI The namespace URI.
* @param string $localName The local name.
* @return bool true if the attribute exists, false if not.
*/
public function hasAttributeNS(?string $namespaceURI, string $localName): bool
{
foreach ($this->getAttributesNS() as $attr) {
if ($attr->getNamespaceURI() === $namespaceURI && $attr->getAttrName() === $localName) {
return true;
}
}
return false;
}
/**
* Get a namespace-qualified attribute.
*
* @param string|null $namespaceURI The namespace URI.
* @param string $localName The local name.
* @return \SimpleSAML\XML\Attribute|null The value of the attribute, or null if the attribute does not exist.
*/
public function getAttributeNS(?string $namespaceURI, string $localName): ?Attribute
{
foreach ($this->getAttributesNS() as $attr) {
if ($attr->getNamespaceURI() === $namespaceURI && $attr->getAttrName() === $localName) {
return $attr;
}
}
return null;
}
/**
* Get the namespaced attributes in this element.
*
* @return array<int, \SimpleSAML\XML\Attribute>
*/
public function getAttributesNS(): array
{
return $this->namespacedAttributes;
}
/**
* Parse an XML document and get the namespaced attributes from the specified namespace(s).
* The namespace defaults to the XS_ANY_ATTR_NAMESPACE constant on the element.
* NOTE: In case the namespace is ##any, this method will also return local non-namespaced attributes!
*
* @param \DOMElement $xml
* @param \SimpleSAML\XML\XsNamespace|array|null $namespace
*
* @return array<int, \SimpleSAML\XML\Attribute> $attributes
*/
protected static function getAttributesNSFromXML(DOMElement $xml, NS|array|null $namespace = null): array
{
$namespace = $namespace ?? self::XS_ANY_ATTR_NAMESPACE;
$exclusionList = self::getAttributeExclusions();
$attributes = [];
// Validate namespace value
if (!is_array($namespace)) {
// Must be one of the predefined values
Assert::oneOf($namespace, NS::cases());
foreach ($xml->attributes as $a) {
if (in_array([$a->namespaceURI, $a->localName], $exclusionList, true)) {
continue;
} elseif ($namespace === NS::OTHER && in_array($a->namespaceURI, [self::NS, null], true)) {
continue;
} elseif ($namespace === NS::TARGET && $a->namespaceURI !== self::NS) {
continue;
} elseif ($namespace === NS::LOCAL && $a->namespaceURI !== null) {
continue;
}
$attributes[] = new Attribute($a->namespaceURI, $a->prefix, $a->localName, $a->nodeValue);
}
} else {
// Array must be non-empty and cannot contain ##any or ##other
Assert::notEmpty($namespace);
Assert::allStringNotEmpty($namespace);
Assert::allNotSame($namespace, NS::ANY);
Assert::allNotSame($namespace, NS::OTHER);
// Replace the ##targetedNamespace with the actual namespace
if (($key = array_search(NS::TARGET, $namespace)) !== false) {
$namespace[$key] = self::NS;
}
// Replace the ##local with null
if (($key = array_search(NS::LOCAL, $namespace)) !== false) {
$namespace[$key] = null;
}
foreach ($xml->attributes as $a) {
if (in_array([$a->namespaceURI, $a->localName], $exclusionList, true)) {
continue;
} elseif (!in_array($a->namespaceURI, $namespace, true)) {
continue;
}
$attributes[] = new Attribute($a->namespaceURI, $a->prefix, $a->localName, $a->nodeValue);
}
}
return $attributes;
}
/**
* @param array<int, \SimpleSAML\XML\Attribute> $attributes
* @throws \SimpleSAML\Assert\AssertionFailedException if $attributes contains anything other than Attribute objects
*/
protected function setAttributesNS(array $attributes): void
{
Assert::maxCount($attributes, C::UNBOUNDED_LIMIT);
Assert::allIsInstanceOf(
$attributes,
Attribute::class,
'Arbitrary XML attributes can only be an instance of Attribute.',
);
$namespace = $this->getAttributeNamespace();
// Validate namespace value
if (!is_array($namespace)) {
// Must be one of the predefined values
Assert::oneOf($namespace, NS::cases());
} else {
// Array must be non-empty and cannot contain ##any or ##other
Assert::notEmpty($namespace);
Assert::allNotSame($namespace, NS::ANY);
Assert::allNotSame($namespace, NS::OTHER);
}
// Get namespaces for all attributes
$actual_namespaces = array_map(
/**
* @param \SimpleSAML\XML\Attribute $elt
* @return string|null
*/
function (Attribute $attr) {
return $attr->getNamespaceURI();
},
$attributes,
);
if ($namespace === NS::LOCAL) {
// If ##local then all namespaces must be null
Assert::allNull($actual_namespaces);
} elseif (is_array($namespace)) {
// Make a local copy of the property that we can edit
$allowed_namespaces = $namespace;
// Replace the ##targetedNamespace with the actual namespace
if (($key = array_search(NS::TARGET, $allowed_namespaces)) !== false) {
$allowed_namespaces[$key] = self::NS;
}
// Replace the ##local with null
if (($key = array_search(NS::LOCAL, $allowed_namespaces)) !== false) {
$allowed_namespaces[$key] = null;
}
$diff = array_diff($actual_namespaces, $allowed_namespaces);
Assert::isEmpty(
$diff,
sprintf(
'Attributes from namespaces [ %s ] are not allowed inside a %s element.',
rtrim(implode(', ', $diff)),
self::NS,
),
);
} else {
if ($namespace === NS::OTHER) {
// All attributes must be namespaced, ergo non-null
Assert::allNotNull($actual_namespaces);
// Must be any namespace other than the parent element
Assert::allNotSame($actual_namespaces, self::NS);
} elseif ($namespace === NS::TARGET) {
// Must be the same namespace as the one of the parent element
Assert::allSame($actual_namespaces, self::NS);
}
}
$exclusionList = self::getAttributeExclusions();
foreach ($attributes as $i => $attr) {
if (in_array([$attr->getNamespaceURI(), $attr->getAttrName()], $exclusionList, true)) {
unset($attributes[$i]);
}
}
$this->namespacedAttributes = $attributes;
}
/**
* @return array|\SimpleSAML\XML\XsNamespace
*/
public function getAttributeNamespace(): array|NS
{
Assert::true(
defined('self::XS_ANY_ATTR_NAMESPACE'),
self::getClassName(self::class)
. '::XS_ANY_ATTR_NAMESPACE constant must be defined and set to the namespace for the xs:anyAttribute.',
RuntimeException::class,
);
return self::XS_ANY_ATTR_NAMESPACE;
}
/**
* Get the exclusions list for getAttributeNSFromXML.
*
* @return array<string, string>
*/
public static function getAttributeExclusions(): array
{
if (defined('self::XS_ANY_ATTR_EXCLUSIONS')) {
return self::XS_ANY_ATTR_EXCLUSIONS;
}
return [];
}
}

View File

@@ -0,0 +1,231 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML;
use DOMElement;
use RuntimeException;
use SimpleSAML\Assert\Assert;
use SimpleSAML\XML\Chunk;
use SimpleSAML\XML\Constants as C;
use SimpleSAML\XML\Registry\ElementRegistry;
use SimpleSAML\XML\XsNamespace as NS;
use function array_diff;
use function array_map;
use function array_search;
use function defined;
use function implode;
use function is_array;
use function rtrim;
use function sprintf;
/**
* Trait grouping common functionality for elements implementing the xs:any element.
*
* @package simplesamlphp/xml-common
*/
trait ExtendableElementTrait
{
/** @var \SimpleSAML\XML\SerializableElementInterface[] */
protected array $elements = [];
/**
* Parse an XML document and get the child elements from the specified namespace(s).
* The namespace defaults to the XS_ANY_ELT_NAMESPACE constant on the element.
* NOTE: In case the namespace is ##any, this method will also return local non-namespaced elements!
*
* @param \DOMElement $xml
* @param \SimpleSAML\XML\XsNamespace|array|null $namespace
*
* @return list<\SimpleSAML\XML\SerializableElementInterface> $elements
*/
protected static function getChildElementsFromXML(DOMElement $xml, NS|array|null $namespace = null): array
{
$namespace = $namespace ?? self::XS_ANY_ELT_NAMESPACE;
$exclusionList = self::getElementExclusions();
$registry = ElementRegistry::getInstance();
$elements = [];
// Validate namespace value
if (!is_array($namespace)) {
// Must be one of the predefined values
Assert::oneOf($namespace, NS::cases());
foreach ($xml->childNodes as $elt) {
if (!($elt instanceof DOMElement)) {
continue;
} elseif (in_array([$elt->namespaceURI, $elt->localName], $exclusionList, true)) {
continue;
} elseif ($namespace === NS::OTHER && in_array($elt->namespaceURI, [self::NS, null], true)) {
continue;
} elseif ($namespace === NS::TARGET && $elt->namespaceURI !== self::NS) {
continue;
} elseif ($namespace === NS::LOCAL && $elt->namespaceURI !== null) {
continue;
}
$handler = $registry->getElementHandler($elt->namespaceURI, $elt->localName);
$elements[] = ($handler === null) ? Chunk::fromXML($elt) : $handler::fromXML($elt);
}
} else {
// Array must be non-empty and cannot contain ##any or ##other
Assert::notEmpty($namespace);
Assert::allStringNotEmpty($namespace);
Assert::allNotSame($namespace, NS::ANY);
Assert::allNotSame($namespace, NS::OTHER);
// Replace the ##targetedNamespace with the actual namespace
if (($key = array_search(NS::TARGET, $namespace)) !== false) {
$namespace[$key] = self::NS;
}
// Replace the ##local with null
if (($key = array_search(NS::LOCAL, $namespace)) !== false) {
$namespace[$key] = null;
}
foreach ($xml->childNodes as $elt) {
if (!($elt instanceof DOMElement)) {
continue;
} elseif (in_array([$elt->namespaceURI, $elt->localName], $exclusionList, true)) {
continue;
} elseif (!in_array($elt->namespaceURI, $namespace, true)) {
continue;
}
$handler = $registry->getElementHandler($elt->namespaceURI, $elt->localName);
$elements[] = ($handler === null) ? Chunk::fromXML($elt) : $handler::fromXML($elt);
}
}
return $elements;
}
/**
* Set an array with all elements present.
*
* @param \SimpleSAML\XML\SerializableElementInterface[] $elements
* @return void
*/
protected function setElements(array $elements): void
{
Assert::maxCount($elements, C::UNBOUNDED_LIMIT);
Assert::allIsInstanceOf($elements, SerializableElementInterface::class);
$namespace = $this->getElementNamespace();
// Validate namespace value
if (!is_array($namespace)) {
// Must be one of the predefined values
Assert::oneOf($namespace, NS::cases());
} else {
// Array must be non-empty and cannot contain ##any or ##other
Assert::notEmpty($namespace);
Assert::allNotSame($namespace, NS::ANY);
Assert::allNotSame($namespace, NS::OTHER);
}
// Get namespaces for all elements
$actual_namespaces = array_map(
/**
* @param \SimpleSAML\XML\SerializableElementInterface $elt
* @return string|null
*/
function (SerializableElementInterface $elt) {
return ($elt instanceof Chunk) ? $elt->getNamespaceURI() : $elt::getNamespaceURI();
},
$elements,
);
if ($namespace === NS::LOCAL) {
// If ##local then all namespaces must be null
Assert::allNull($actual_namespaces);
} elseif (is_array($namespace)) {
// Make a local copy of the property that we can edit
$allowed_namespaces = $namespace;
// Replace the ##targetedNamespace with the actual namespace
if (($key = array_search(NS::TARGET, $allowed_namespaces)) !== false) {
$allowed_namespaces[$key] = self::NS;
}
// Replace the ##local with null
if (($key = array_search(NS::LOCAL, $allowed_namespaces)) !== false) {
$allowed_namespaces[$key] = null;
}
$diff = array_diff($actual_namespaces, $allowed_namespaces);
Assert::isEmpty(
$diff,
sprintf(
'Elements from namespaces [ %s ] are not allowed inside a %s element.',
rtrim(implode(', ', $diff)),
self::NS,
),
);
} elseif ($namespace === NS::OTHER) {
// Must be any namespace other than the parent element, excluding elements with no namespace
Assert::notInArray(null, $actual_namespaces);
Assert::allNotSame($actual_namespaces, self::NS);
} elseif ($namespace === NS::TARGET) {
// Must be the same namespace as the one of the parent element
Assert::allSame($actual_namespaces, self::NS);
} else {
// XS_ANY_NS_ANY
}
$exclusionList = self::getElementExclusions();
foreach ($elements as $i => $elt) {
if (in_array([$elt->getNamespaceURI(), $elt->getLocalName()], $exclusionList, true)) {
unset($elements[$i]);
}
}
$this->elements = $elements;
}
/**
* Get an array with all elements present.
*
* @return \SimpleSAML\XML\SerializableElementInterface[]
*/
public function getElements(): array
{
return $this->elements;
}
/**
* @return array|\SimpleSAML\XML\XsNamespace
*/
public function getElementNamespace(): array|NS
{
Assert::true(
defined('self::XS_ANY_ELT_NAMESPACE'),
self::getClassName(self::class)
. '::XS_ANY_ELT_NAMESPACE constant must be defined and set to the namespace for the xs:any element.',
RuntimeException::class,
);
return self::XS_ANY_ELT_NAMESPACE;
}
/**
* Get the exclusions list for getChildElementsFromXML.
*
* @return array<string, string>
*/
public static function getElementExclusions(): array
{
if (defined('self::XS_ANY_ELT_EXCLUSIONS')) {
return self::XS_ANY_ELT_EXCLUSIONS;
}
return [];
}
}

View File

@@ -0,0 +1,65 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML;
use DOMElement;
use SimpleSAML\XML\Assert\Assert;
use SimpleSAML\XML\Exception\SchemaViolationException;
/**
* Trait grouping common functionality for simple elements with hexbinary textContent
*
* @package simplesamlphp/xml-common
*/
trait HexBinaryElementTrait
{
use StringElementTrait;
/**
* Sanitize the content of the element.
*
* Note: There are no processing rules for xs:hexBinary regarding whitespace. General consensus is to strip them
*
* @param string $content The unsanitized textContent
* @throws \Exception on failure
* @return string
*/
protected function sanitizeContent(string $content): string
{
return str_replace(["\f", "\r", "\n", "\t", "\v", ' '], '', $content);
}
/**
* Validate the content of the element.
*
* @param string $content The value to go in the XML textContent
* @throws \Exception on failure
* @return void
*/
protected function validateContent(string $content): void
{
// Note: content must already be sanitized before validating
Assert::regex(
$this->sanitizeContent($content),
'/([0-9A-F]{2})*/i',
SchemaViolationException::class,
);
}
/** @return string */
abstract public static function getLocalName(): string;
/**
* Create a document structure for this element
*
* @param \DOMElement|null $parent The element we should append to.
* @return \DOMElement
*/
abstract public function instantiateParentElement(?DOMElement $parent = null): DOMElement;
}

View File

@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML;
use SimpleSAML\Assert\Assert;
use SimpleSAML\XML\Exception\SchemaViolationException;
/**
* Trait grouping common functionality for simple elements with just some textContent
*
* @package simplesamlphp/xml-common
*/
trait IntegerElementTrait
{
use StringElementTrait;
/**
* Validate the content of the element.
*
* @param int $content The value to go in the XML textContent
* @throws \Exception on failure
* @return void
*/
protected function validateContent(/** @scrutinizer ignore-unused */ string $content): void
{
/**
* Perform no validation by default.
* Override this method on the implementing class to perform content validation.
*/
Assert::numeric($content, SchemaViolationException::class);
}
}

View File

@@ -0,0 +1,101 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML;
use DOMElement;
use SimpleSAML\Assert\Assert;
use SimpleSAML\XML\Constants as C;
use SimpleSAML\XML\Exception\InvalidDOMElementException;
use SimpleSAML\XML\Exception\MissingAttributeException;
/**
* Trait grouping common functionality for simple localized string elements
*
* @package simplesamlphp/xml-common
*/
trait LocalizedStringElementTrait
{
use StringElementTrait;
/**
* The language this string is on.
*
* @var string
*/
protected string $language;
/**
* Validate the content of the element.
*
* @param string $content The value to go in the XML textContent
* @throws \Exception on failure
* @return void
*/
protected function validateContent(string $content): void
{
Assert::notEmpty($content);
}
/**
* Get the language this string is localized in.
*
* @return string
*/
public function getLanguage(): string
{
return $this->language;
}
/**
* Set the language this string is localized in.
*
* @param string $language
*/
protected function setLanguage(string $language): void
{
Assert::notEmpty($language, 'xml:lang cannot be empty.');
$this->language = $language;
}
/**
* Convert XML into a class instance
*
* @param \DOMElement $xml The XML element we should load
* @return static
*
* @throws \SimpleSAML\XML\Exception\InvalidDOMElementException
* If the qualified name of the supplied element is wrong
*/
public static function fromXML(DOMElement $xml): static
{
Assert::same($xml->localName, static::getLocalName(), InvalidDOMElementException::class);
Assert::same($xml->namespaceURI, static::NS, InvalidDOMElementException::class);
Assert::true(
$xml->hasAttributeNS(C::NS_XML, 'lang'),
'Missing xml:lang from ' . static::getLocalName(),
MissingAttributeException::class,
);
return new static($xml->getAttributeNS(C::NS_XML, 'lang'), $xml->textContent);
}
/**
* @param \DOMElement|null $parent
* @return \DOMElement
*/
final public function toXML(?DOMElement $parent = null): DOMElement
{
$e = $this->instantiateParentElement($parent);
$e->setAttributeNS(C::NS_XML, 'xml:lang', $this->getLanguage());
$e->textContent = $this->getContent();
return $e;
}
}

View File

@@ -0,0 +1,144 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML;
use DOMElement;
use SimpleSAML\XML\Assert\Assert;
use SimpleSAML\XML\Exception\InvalidDOMElementException;
use SimpleSAML\XML\Exception\SchemaViolationException;
use SimpleSAML\XML\StringElementTrait;
use function preg_split;
/**
* Trait grouping common functionality for simple elements with QName textContent
*
* @package simplesamlphp/xml-common
*/
trait QNameElementTrait
{
use StringElementTrait;
/** @var string|null */
protected ?string $contentNamespaceUri;
/**
* Validate the content of the element.
*
* @param string $content The value to go in the XML textContent
* @throws \Exception on failure
* @return void
*/
protected function validateContent(string $content): void
{
Assert::validQName($content, SchemaViolationException::class);
}
/**
* Set the namespaceUri.
*
* @param string|null $namespaceUri
*/
protected function setContentNamespaceUri(?string $namespaceUri): void
{
Assert::nullOrValidURI($namespaceUri, SchemaViolationException::class);
$this->contentNamespaceUri = $namespaceUri;
}
/**
* Get the namespace URI.
*
* @return string|null
*/
public function getContentNamespaceUri(): ?string
{
return $this->contentNamespaceUri;
}
/**
* Splits a QName into an array holding the prefix (or null if no prefix is available) and the localName
*
* @param string $qName The qualified name
* @return array
*/
private static function parseQName(string $qName): array
{
Assert::validQName($qName);
@list($prefix, $localName) = preg_split('/:/', $qName, 2);
if ($localName === null) {
$prefix = null;
$localName = $qName;
}
Assert::nullOrValidNCName($prefix);
Assert::validNCName($localName);
return [$prefix, $localName];
}
/**
* Convert XML into a class instance
*
* @param \DOMElement $xml The XML element we should load
* @return static
*
* @throws \SimpleSAML\XML\Exception\InvalidDOMElementException
* If the qualified name of the supplied element is wrong
*/
public static function fromXML(DOMElement $xml): static
{
Assert::same($xml->localName, static::getLocalName(), InvalidDOMElementException::class);
Assert::same($xml->namespaceURI, static::NS, InvalidDOMElementException::class);
list($prefix, $localName) = self::parseQName($xml->textContent);
$namespace = $xml->lookupNamespaceUri($prefix);
return new static($xml->textContent, $namespace);
}
/**
* Convert this element to XML.
*
* @param \DOMElement|null $parent The element we should append this element to.
* @return \DOMElement
*/
public function toXML(?DOMElement $parent = null): DOMElement
{
$e = $this->instantiateParentElement($parent);
list($prefix, $localName) = self::parseQName($this->getContent());
$namespaceUri = $this->getContentNamespaceUri();
if ($namespaceUri !== null && $prefix !== null) {
if ($e->lookupNamespaceUri($prefix) === null && $e->lookupPrefix($namespaceUri) === null) {
// The namespace is not yet available in the document - insert it
$e->setAttribute('xmlns:' . $prefix, $namespaceUri);
}
}
$e->textContent = ($prefix === null) ? $localName : ($prefix . ':' . $localName);
return $e;
}
/** @return string */
abstract public static function getLocalName(): string;
/**
* Create a document structure for this element
*
* @param \DOMElement|null $parent The element we should append to.
* @return \DOMElement
*/
abstract public function instantiateParentElement(?DOMElement $parent = null): DOMElement;
}

View File

@@ -0,0 +1,97 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML\Registry;
use SimpleSAML\XML\AbstractElement;
use SimpleSAML\XML\Assert\Assert;
use SimpleSAML\XML\Exception\InvalidDOMElementException;
use SimpleSAML\XML\Exception\IOException;
use Symfony\Component\Finder\Finder;
use function array_merge_recursive;
use function dirname;
use function file_exists;
final class ElementRegistry
{
/** @var \SimpleSAML\XML\Registry\ElementRegistry|null $instance */
private static ?ElementRegistry $instance = null;
/** @var array<string, array<string, string>> */
private array $registry = [];
private function __construct()
{
// Initialize the registry with all the elements we know
$classesDir = dirname(__FILE__, 6) . '/vendor/simplesamlphp/composer-xmlprovider-installer/classes';
if (file_exists($classesDir) === true) {
$finder = Finder::create()->files()->name('element.registry.*.php')->in($classesDir);
if ($finder->hasResults()) {
foreach ($finder as $file) {
$this->importFromFile($file->getPathName());
}
}
}
}
public function importFromFile(string $file): void
{
if (file_exists($file) === true) {
$elements = include($file);
$this->registry = array_merge_recursive($this->registry, $elements);
} else {
throw new IOException('File not found.');
}
}
public static function getInstance(): ElementRegistry
{
if (self::$instance === null) {
self::$instance = new static();
}
return self::$instance;
}
/**
* Register a class that can process a certain XML-element.
*
* @param string $class The class name of a class extending AbstractElement.
*/
public function registerElementHandler(string $class): void
{
Assert::subclassOf($class, AbstractElement::class);
$className = AbstractElement::getClassName($class);
$namespace = $class::NS;
$this->registry[$namespace][$className] = $class;
}
/**
* Search for a class that implements an $element in the given $namespace.
*
* Such classes must have been registered previously by calling registerElementHandler(), and they must
* extend \SimpleSAML\XML\AbstractElement.
*
* @param string|null $namespace The namespace URI for the given element.
* @param string $element The local name of the element.
*
* @return string|null The fully-qualified name of a class extending \SimpleSAML\XML\AbstractElement and
* implementing support for the given element, or null if no such class has been registered before.
*/
public function getElementHandler(?string $namespace, string $element): ?string
{
Assert::nullOrValidURI($namespace, InvalidDOMElementException::class);
Assert::validNCName($element, InvalidDOMElementException::class);
return $this->registry[$namespace][$element] ?? null;
}
}

View File

@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML;
use DOMDocument;
/**
* interface class to be implemented by all the classes that can be validated against a schema
*
* @package simplesamlphp/xml-common
*/
interface SchemaValidatableElementInterface extends ElementInterface
{
/**
* Validate the given DOMDocument against the schema set for this element
*
* @param \DOMDocument $document
* @param string|null $schemaFile
* @return \DOMDocument
*
* @throws \SimpleSAML\XML\Exception\IOException
* @throws \SimpleSAML\XML\Exception\SchemaViolationException
*/
public static function schemaValidate(DOMDocument $document, ?string $schemaFile = null): DOMDocument;
}

View File

@@ -0,0 +1,85 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML;
use DOMDocument;
use SimpleSAML\Assert\Assert;
use SimpleSAML\XML\Exception\IOException;
use SimpleSAML\XML\Exception\SchemaViolationException;
use function array_unique;
use function defined;
use function file_exists;
use function implode;
use function libxml_clear_errors;
use function libxml_get_errors;
use function libxml_use_internal_errors;
use function sprintf;
use function trim;
/**
* trait class to be used by all the classes that implement the SchemaValidatableElementInterface
*
* @package simplesamlphp/xml-common
*/
trait SchemaValidatableElementTrait
{
/**
* Validate the given DOMDocument against the schema set for this element
*
* @param \DOMDocument $document
* @param string|null $schemaFile
* @return \DOMDocument
*
* @throws \SimpleSAML\XML\Exception\IOException
* @throws \SimpleSAML\XML\Exception\SchemaViolationException
*/
public static function schemaValidate(DOMDocument $document, ?string $schemaFile = null): DOMDocument
{
$internalErrors = libxml_use_internal_errors(true);
libxml_clear_errors();
if ($schemaFile === null) {
$schemaFile = self::getSchemaFile();
}
// Must suppress the warnings here in order to throw them as an error below.
$result = @$document->schemaValidate($schemaFile);
if ($result === false) {
$msgs = [];
foreach (libxml_get_errors() as $err) {
$msgs[] = trim($err->message) . ' on line ' . $err->line;
}
throw new SchemaViolationException(sprintf(
"XML schema validation errors:\n - %s",
implode("\n - ", array_unique($msgs)),
));
}
libxml_use_internal_errors($internalErrors);
libxml_clear_errors();
return $document;
}
/**
* Get the schema file that can validate this element.
* The path must be relative to the project's base directory.
*
* @return string
*/
public static function getSchemaFile(): string
{
if (defined('static::SCHEMA')) {
$schemaFile = static::SCHEMA;
}
Assert::true(file_exists($schemaFile), sprintf("File not found: %s", $schemaFile), IOException::class);
return $schemaFile;
}
}

View File

@@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML;
use DOMElement;
/**
* interface class to be implemented by all the classes that represent a serializable XML element
*
* @package simplesamlphp/xml-common
*/
interface SerializableElementInterface extends ElementInterface
{
/**
* Output the class as an XML-formatted string
*
* @return string
*/
public function __toString(): string;
/**
* Test if an object, at the state it's in, would produce an empty XML-element
*
* @return bool
*/
public function isEmptyElement(): bool;
/**
* Create a class from XML
*
* @param \DOMElement $xml
* @return static
*/
public static function fromXML(DOMElement $xml): static;
/**
* Create XML from this class
*
* @param \DOMElement|null $parent
* @return \DOMElement
*/
public function toXML(?DOMElement $parent = null): DOMElement;
}

View File

@@ -0,0 +1,90 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML;
use DOMElement;
use SimpleSAML\XML\DOMDocumentFactory;
use function array_pop;
use function get_object_vars;
/**
* Trait grouping common functionality for elements implementing the SerializableElement element.
*
* @package simplesamlphp/xml-common
*/
trait SerializableElementTrait
{
/**
* Whether to format the string output of this element or not.
*
* Defaults to true. Override to disable output formatting.
*
* @var bool
*/
protected bool $formatOutput = true;
/**
* Output the class as an XML-formatted string
*
* @return string
*/
public function __toString(): string
{
$xml = $this->toXML();
$xmlString = $xml->ownerDocument->saveXML();
$doc = DOMDocumentFactory::fromString($xmlString);
$doc->formatOutput = $this->formatOutput;
return $doc->saveXML($doc->firstChild);
}
/**
* Serialize this XML chunk.
*
* This method will be invoked by any calls to serialize().
*
* @return array{0: string} The serialized representation of this XML object.
*/
public function __serialize(): array
{
$xml = $this->toXML();
return [$xml->ownerDocument->saveXML($xml)];
}
/**
* Unserialize an XML object and load it..
*
* This method will be invoked by any calls to unserialize(), allowing us to restore any data that might not
* be serializable in its original form (e.g.: DOM objects).
*
* @param array{0: string} $serialized The XML object that we want to restore.
*/
public function __unserialize(array $serialized): void
{
$xml = static::fromXML(
DOMDocumentFactory::fromString(array_pop($serialized))->documentElement,
);
$vars = get_object_vars($xml);
foreach ($vars as $k => $v) {
$this->$k = $v;
}
}
/**
* Create XML from this class
*
* @param \DOMElement|null $parent
* @return \DOMElement
*/
abstract public function toXML(?DOMElement $parent = null): DOMElement;
}

View File

@@ -0,0 +1,135 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML;
use DOMElement;
use SimpleSAML\Assert\Assert;
use SimpleSAML\XML\Exception\InvalidDOMElementException;
/**
* Trait grouping common functionality for simple elements with just some textContent
*
* @package simplesamlphp/xml-common
*/
trait StringElementTrait
{
/** @var string */
protected string $content;
/**
* Set the content of the element.
*
* @param string $content The value to go in the XML textContent
*/
protected function setContent(string $content): void
{
$this->validateContent($content);
$this->content = $content;
}
/**
* Get the content of the element.
*
* @return string
*/
public function getContent(): string
{
return $this->sanitizeContent($this->getRawContent());
}
/**
* Get the raw content of the element.
*
* @return string
*/
public function getRawContent(): string
{
return $this->content;
}
/**
* Sanitize the content of the element.
*
* @param string $content The value to go in the XML textContent
* @throws \Exception on failure
* @return string
*/
protected function sanitizeContent(string $content): string
{
/**
* Perform no sanitation by default.
* Override this method on the implementing class to perform content sanitation.
*/
return $content;
}
/**
* Validate the content of the element.
*
* @param string $content The value to go in the XML textContent
* @throws \Exception on failure
* @return void
*/
protected function validateContent(/** @scrutinizer ignore-unused */ string $content): void
{
/**
* Perform no validation by default.
* Override this method on the implementing class to perform content validation.
*/
}
/**
* Convert XML into a class instance
*
* @param \DOMElement $xml The XML element we should load
* @return static
*
* @throws \SimpleSAML\XML\Exception\InvalidDOMElementException
* If the qualified name of the supplied element is wrong
*/
public static function fromXML(DOMElement $xml): static
{
Assert::same($xml->localName, static::getLocalName(), InvalidDOMElementException::class);
Assert::same($xml->namespaceURI, static::NS, InvalidDOMElementException::class);
return new static($xml->textContent);
}
/**
* Convert this element to XML.
*
* @param \DOMElement|null $parent The element we should append this element to.
* @return \DOMElement
*/
public function toXML(?DOMElement $parent = null): DOMElement
{
$e = $this->instantiateParentElement($parent);
$e->textContent = $this->getContent();
return $e;
}
/**
* @return string
*/
abstract public static function getLocalName(): string;
/**
* Create a document structure for this element
*
* @param \DOMElement|null $parent The element we should append to.
* @return \DOMElement
*/
abstract public function instantiateParentElement(?DOMElement $parent = null): DOMElement;
}

View File

@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML\TestUtils;
use function class_exists;
/**
* Test for arrayizable XML classes to perform default serialization tests.
*
* @package simplesamlphp\xml-common
*/
trait ArrayizableElementTestTrait
{
/** @var class-string */
protected static string $testedClass;
/** @var array */
protected static array $arrayRepresentation;
/**
* Test arrayization / de-arrayization
*/
public function testArrayization(): void
{
if (!class_exists(self::$testedClass)) {
$this->markTestSkipped(
'Unable to run ' . self::class . '::testArrayization(). Please set ' . self::class
. ':$element to a class-string representing the XML-class being tested',
);
} elseif (self::$arrayRepresentation === null) {
$this->markTestSkipped(
'Unable to run ' . self::class . '::testArrayization(). Please set ' . self::class
. ':$arrayRepresentation to an array representing the XML-class being tested',
);
} else {
$this->assertEquals(
self::$arrayRepresentation,
self::$testedClass::fromArray(self::$arrayRepresentation)->toArray(),
);
}
}
}

View File

@@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML\TestUtils;
use DOMDocument;
use PHPUnit\Framework\Attributes\Depends;
use function class_exists;
/**
* Test for AbstractElement classes to perform schema validation tests.
*
* @package simplesamlphp\xml-common
*/
trait SchemaValidationTestTrait
{
/** @var string|null */
protected static ?string $schemaFile = null;
/** @var class-string */
protected static string $testedClass;
/** @var \DOMDocument */
protected static DOMDocument $xmlRepresentation;
/**
* Test schema validation.
*/
#[Depends('testSerialization')]
public function testSchemaValidation(): void
{
if (!class_exists(self::$testedClass)) {
$this->markTestSkipped(
'Unable to run ' . self::class . '::testSchemaValidation(). Please set ' . self::class
. ':$testedClass to a class-string representing the XML-class being tested',
);
} elseif (empty(self::$xmlRepresentation)) {
$this->markTestSkipped(
'Unable to run ' . self::class . '::testSchemaValidation(). Please set ' . self::class
. ':$xmlRepresentation to a DOMDocument representing the XML-class being tested',
);
} else {
// Validate before serialization
self::$testedClass::schemaValidate(self::$xmlRepresentation, self::$schemaFile);
// Perform serialization
$class = self::$testedClass::fromXML(self::$xmlRepresentation->documentElement);
$serializedClass = $class->toXML();
// Validate after serialization
self::$testedClass::schemaValidate($serializedClass->ownerDocument, self::$schemaFile);
// If we got this far and no exceptions were thrown, consider this test passed!
$this->addToAssertionCount(1);
}
}
abstract public function testSerialization(): void;
}

View File

@@ -0,0 +1,82 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML\TestUtils;
use DOMDocument;
use PHPUnit\Framework\Attributes\Depends;
use function class_exists;
/**
* Test for Serializable XML classes to perform default serialization tests.
*
* @package simplesamlphp\xml-common
*/
trait SerializableElementTestTrait
{
/** @var class-string */
protected static string $testedClass;
/** @var \DOMDocument */
protected static DOMDocument $xmlRepresentation;
/**
* Test creating XML from a class.
*/
abstract public function testMarshalling(): void;
/**
* Test creating a class from XML.
*/
public function testUnmarshalling(): void
{
if (!class_exists(self::$testedClass)) {
$this->markTestSkipped(
'Unable to run ' . self::class . '::testUnmarshalling(). Please set ' . self::class
. ':$testedClass to a class-string representing the XML-class being tested',
);
} elseif (empty(self::$xmlRepresentation)) {
$this->markTestSkipped(
'Unable to run ' . self::class . '::testUnmarshalling(). Please set ' . self::class
. ':$xmlRepresentation to a DOMDocument representing the XML-class being tested',
);
} else {
$elt = self::$testedClass::fromXML(self::$xmlRepresentation->documentElement);
$this->assertEquals(
self::$xmlRepresentation->saveXML(self::$xmlRepresentation->documentElement),
strval($elt),
);
}
}
/**
* Test serialization / unserialization.
*/
#[Depends('testMarshalling')]
#[Depends('testUnmarshalling')]
public function testSerialization(): void
{
if (!class_exists(self::$testedClass)) {
$this->markTestSkipped(
'Unable to run ' . self::class . '::testSerialization(). Please set ' . self::class
. ':$testedClass to a class-string representing the XML-class being tested',
);
} elseif (empty(self::$xmlRepresentation)) {
$this->markTestSkipped(
'Unable to run ' . self::class . '::testSerialization(). Please set ' . self::class
. ':$xmlRepresentation to a DOMDocument representing the XML-class being tested',
);
} else {
$this->assertEquals(
self::$xmlRepresentation->saveXML(self::$xmlRepresentation->documentElement),
strval(unserialize(serialize(self::$testedClass::fromXML(self::$xmlRepresentation->documentElement)))),
);
}
}
}

View File

@@ -0,0 +1,63 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML;
use DOMElement;
use SimpleSAML\Assert\Assert;
use SimpleSAML\XML\Exception\InvalidDOMElementException;
use SimpleSAML\XML\Exception\SchemaViolationException;
/**
* Trait grouping common functionality for simple URI string elements
*
* @package simplesamlphp/xml-common
*/
trait URIElementTrait
{
use StringElementTrait;
/**
* Validate the content of the element.
*
* @param string $content The value to go in the XML textContent
* @throws \Exception on failure
* @return void
*/
protected function validateContent(string $content): void
{
Assert::validURI($content, SchemaViolationException::class);
}
/**
* Convert XML into a class instance
*
* @param \DOMElement $xml The XML element we should load
* @return static
*
* @throws \SimpleSAML\XML\Exception\InvalidDOMElementException
* If the qualified name of the supplied element is wrong
*/
public static function fromXML(DOMElement $xml): static
{
Assert::same($xml->localName, static::getLocalName(), InvalidDOMElementException::class);
Assert::same($xml->namespaceURI, static::NS, InvalidDOMElementException::class);
return new static($xml->textContent);
}
/**
* @param \DOMElement|null $parent
* @return \DOMElement
*/
final public function toXML(?DOMElement $parent = null): DOMElement
{
$e = $this->instantiateParentElement($parent);
$e->textContent = $this->getContent();
return $e;
}
}

View File

@@ -0,0 +1,166 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML;
use DateTimeImmutable;
use DateTimeInterface;
use DOMElement;
use SimpleSAML\XML\Assert\Assert;
use function trim;
/**
* Helper functions for the XML library.
*
* @package simplesamlphp/xml-common
*/
class Utils
{
/**
* @deprecated Create elements that extend AbstractElement and use it's interface to retrieve attributes instead.
*
* Extract localized strings from a set of nodes.
*
* @param \DOMElement $parent The element that contains the localized strings.
* @param string $namespaceURI The namespace URI the localized strings should have.
* @param string $localName The localName of the localized strings.
* @return array<string, string> Localized strings.
*/
public static function extractLocalizedStrings(DOMElement $parent, string $namespaceURI, string $localName): array
{
$ret = [];
foreach ($parent->childNodes as $node) {
if ($node->namespaceURI !== $namespaceURI || $node->localName !== $localName) {
continue;
} elseif (!($node instanceof DOMElement)) {
continue;
}
if ($node->hasAttribute('xml:lang')) {
$language = $node->getAttribute('xml:lang');
} else {
$language = 'en';
}
$ret[$language] = trim($node->textContent);
}
return $ret;
}
/**
* @deprecated Create elements that extend AbstractElement and use <element>::getChildrenOfClass() instead.
*
* Extract strings from a set of nodes.
*
* @param \DOMElement $parent The element that contains the localized strings.
* @param string $namespaceURI The namespace URI the string elements should have.
* @param string $localName The localName of the string elements.
* @return string[] The string values of the various nodes.
*/
public static function extractStrings(DOMElement $parent, string $namespaceURI, string $localName): array
{
$ret = [];
foreach ($parent->childNodes as $node) {
if ($node->namespaceURI !== $namespaceURI || $node->localName !== $localName) {
continue;
}
$ret[] = trim($node->textContent);
}
return $ret;
}
/**
* @deprecated Create elements that extend AbstractElement and use <element>::toXML() instead.
*
* Append string element.
*
* @param \DOMElement $parent The parent element we should append the new nodes to.
* @param string $namespace The namespace of the created element.
* @param string $name The name of the created element.
* @param string $value The value of the element.
* @return \DOMElement The generated element.
*/
public static function addString(
DOMElement $parent,
string $namespace,
string $name,
string $value,
): DOMElement {
$doc = $parent->ownerDocument;
Assert::notNull($doc);
$n = $doc->createElementNS($namespace, $name);
$n->appendChild($doc->createTextNode($value));
$parent->appendChild($n);
return $n;
}
/**
* @deprecated Create elements that extend AbstractElement and use <element>::toXML() instead.
*
* Append string elements.
*
* @param \DOMElement $parent The parent element we should append the new nodes to.
* @param string $namespace The namespace of the created elements
* @param string $name The name of the created elements
* @param bool $localized Whether the strings are localized, and should include the xml:lang attribute.
* @param string[] $values The values we should create the elements from.
*/
public static function addStrings(
DOMElement $parent,
string $namespace,
string $name,
bool $localized,
array $values,
): void {
$doc = $parent->ownerDocument;
Assert::notNull($doc);
foreach ($values as $index => $value) {
$n = $doc->createElementNS($namespace, $name);
$n->appendChild($doc->createTextNode($value));
if ($localized) {
$n->setAttribute('xml:lang', $index);
}
$parent->appendChild($n);
}
}
/**
* @deprecated Use DateTime objects instead
*
* This function converts a SAML2 timestamp on the form
* yyyy-mm-ddThh:mm:ss(\.s+)?Z to a UNIX timestamp. The sub-second
* part is ignored.
*
* Note that we always require a 'Z' timezone for the dateTime to be valid.
* This is not in the SAML spec but that's considered to be a bug in the
* spec. See https://github.com/simplesamlphp/saml2/pull/36 for some
* background.
*
* @param string $time The time we should convert.
* @throws \Exception
* @return int Converted to a unix timestamp.
*/
public static function xsDateTimeToTimestamp(string $time): int
{
Assert::validDateTime($time);
$dateTime1 = DateTimeImmutable::createFromFormat(DateTimeInterface::ISO8601, $time);
$dateTime2 = DateTimeImmutable::createFromFormat(DateTimeInterface::RFC3339_EXTENDED, $time);
$dateTime = $dateTime1 ?: $dateTime2;
Assert::isInstanceOf($dateTime, DateTimeImmutable::class);
Assert::same($dateTime->getTimeZone()->getName(), 'Z');
return $dateTime->getTimestamp();
}
}

View File

@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML\Utils;
use function bin2hex;
use function random_bytes;
/**
* @package simplesamlphp/xml-common
*/
class Random
{
/**
* The fixed length of random identifiers.
*/
public const ID_LENGTH = 43;
/**
* This function will generate a unique ID that is valid for use
* in an xs:ID attribute
*/
public function generateID(): string
{
return '_' . bin2hex(random_bytes((self::ID_LENGTH - 1) / 2));
}
}

View File

@@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML\Utils;
use DOMDocument;
use DOMNode;
use DOMXPath;
use SimpleSAML\Assert\Assert;
/**
* XPath helper functions for the XML library.
*
* @package simplesamlphp/xml-common
*/
class XPath
{
/**
* Get an instance of DOMXPath associated with a DOMNode
*
* @param \DOMNode $node The associated node
* @return \DOMXPath
*/
public static function getXPath(DOMNode $node): DOMXPath
{
static $xpCache = null;
if ($node instanceof DOMDocument) {
$doc = $node;
} else {
$doc = $node->ownerDocument;
Assert::notNull($doc);
}
if ($xpCache === null || !$xpCache->document->isSameNode($doc)) {
$xpCache = new DOMXPath($doc);
}
return $xpCache;
}
/**
* Do an XPath query on an XML node.
*
* @param \DOMNode $node The XML node.
* @param string $query The query.
* @param \DOMXPath $xpCache The DOMXPath object
* @return array<int<0, max>, \DOMNameSpaceNode|\DOMNode|null> Array with matching DOM nodes.
*/
public static function xpQuery(DOMNode $node, string $query, DOMXPath $xpCache): array
{
$ret = [];
$results = $xpCache->query($query, $node);
for ($i = 0; $i < $results->length; $i++) {
$ret[$i] = $results->item($i);
}
return $ret;
}
}

View File

@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML;
/**
* The namespace-attribute values for xs:any elements
*
* @package simplesamlphp/xml-common
*/
enum XsNamespace: string
{
case ANY = '##any';
case LOCAL = '##local';
case OTHER = '##other';
case TARGET = '##targetNamespace';
}

View File

@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\XML;
/**
* The processContents-attribute values for xs:any elements
*
* @package simplesamlphp/xml-common
*/
enum XsProcess: string
{
case LAX = 'lax';
case SKIP = 'skip';
case STRICT = 'strict';
}

View File

@@ -0,0 +1,55 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\Test\XML\Assert;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use SimpleSAML\Assert\AssertionFailedException;
use SimpleSAML\XML\Assert\Assert;
/**
* Class \SimpleSAML\Test\XML\Assert\DateTimeTest
*
* @package simplesamlphp/xml-common
*/
#[CoversClass(Assert::class)]
final class DateTimeTest extends TestCase
{
/**
* @param boolean $shouldPass
* @param string $dateTime
*/
#[DataProvider('provideDateTime')]
public function testValidDateTime(bool $shouldPass, string $dateTime): void
{
try {
Assert::validDateTime($dateTime);
$this->assertTrue($shouldPass);
} catch (AssertionFailedException $e) {
$this->assertFalse($shouldPass);
}
}
/**
* @return array<int, array{0: bool, 1: string}>
*/
public static function provideDateTime(): array
{
return [
[true, '2001-10-26T21:32:52'],
[true, '2001-10-26T21:32:52+02:00'],
[true, '2001-10-26T19:32:52Z'],
[true, '2001-10-26T19:32:52+00:00'],
[true, '-2001-10-26T21:32:52'],
[true, '2001-10-26T21:32:52.12679'],
[false, '2001-10-26'],
[false, '2001-10-26T21:32'],
[false, '2001-10-26T25:32:52+02:00'],
[false, '01-10-26T21:32'],
];
}
}

View File

@@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\Test\XML\Assert;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use SimpleSAML\Assert\AssertionFailedException;
use SimpleSAML\XML\Assert\Assert;
/**
* Class \SimpleSAML\Test\XML\Assert\DurationTest
*
* @package simplesamlphp/xml-common
*/
#[CoversClass(Assert::class)]
final class DurationTest extends TestCase
{
/**
* @param boolean $shouldPass
* @param string $duration
*/
#[DataProvider('provideDuration')]
public function testValidDuration(bool $shouldPass, string $duration): void
{
try {
Assert::validDuration($duration);
$this->assertTrue($shouldPass);
} catch (AssertionFailedException $e) {
$this->assertFalse($shouldPass);
}
}
/**
* @return array<int, array{0: bool, 1: string}>
*/
public static function provideDuration(): array
{
return [
[true, 'P2Y6M5DT12H35M30S'],
[true, 'P1DT2H'],
[true, 'P1W'],
[true, 'P20M'],
[true, 'PT20M'],
[true, 'P0Y20M0D'],
[true, 'P0Y'],
[true, '-P60D'],
[true, 'PT1M30.5S'],
[true, 'P15.5Y'],
[true, 'P15,5Y'],
[false, 'P-20M'],
[false, 'P20MT'],
[false, 'P1YM5D'],
[false, 'P1D2H'],
[false, '1Y2M'],
[false, 'P2M1Y'],
[false, 'P'],
[false, 'PT15.S'],
// Trailing newlines are forbidden
[false, "P20M\n"],
];
}
}

View File

@@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\Test\XML\Assert;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use SimpleSAML\Assert\AssertionFailedException;
use SimpleSAML\XML\Assert\Assert;
/**
* Class \SimpleSAML\Test\Assert\HexBinaryTest
*
* @package simplesamlphp/xml-common
*/
#[CoversClass(Assert::class)]
final class HexBinaryTest extends TestCase
{
/**
* @param boolean $shouldPass
* @param string $name
*/
#[DataProvider('provideHexBinary')]
public function testHexBinary(bool $shouldPass, string $name): void
{
try {
Assert::validHexBinary($name);
$this->assertTrue($shouldPass);
} catch (AssertionFailedException $e) {
$this->assertFalse($shouldPass);
}
}
/**
* @return array<string, array{0: bool, 1: string}>
*/
public static function provideHexBinary(): array
{
return [
'empty' => [false, ''],
'base64' => [false, 'U2ltcGxlU0FNTHBocA=='],
'valid' => [true, '3f3c6d78206c657673726f693d6e3122302e20226e656f636964676e223d54552d4622383e3f'],
'invalid' => [false, '3f3r'],
'bogus' => [false, '&*$(#&^@!(^%$'],
'length not dividable by 4' => [false, '3f3'],
];
}
}

View File

@@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\Test\XML\Assert;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use SimpleSAML\Assert\AssertionFailedException;
use SimpleSAML\XML\Assert\Assert;
/**
* Class \SimpleSAML\Test\XML\Assert\NCNameTest
*
* @package simplesamlphp/xml-common
*/
#[CoversClass(Assert::class)]
final class NCNameTest extends TestCase
{
/**
* @param boolean $shouldPass
* @param string $name
*/
#[DataProvider('provideNCName')]
public function testValidNCName(bool $shouldPass, string $name): void
{
try {
Assert::validNCName($name);
$this->assertTrue($shouldPass);
} catch (AssertionFailedException $e) {
$this->assertFalse($shouldPass);
}
}
/**
* @return array<int, array{0: bool, 1: string}>
*/
public static function provideNCName(): array
{
return [
[true, 'Test'],
[true, '_Test'],
// Prefixed v4 UUID
[true, '_5425e58e-e799-4884-92cc-ca64ecede32f'],
// An empty value is not valid, unless xsi:nil is used
[false, ''],
[false, 'Te*st'],
[false, '1Test'],
[false, 'Te:st'],
// Trailing newlines are forbidden
[false, "Test\n"],
];
}
}

View File

@@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\Test\XML\Assert;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use SimpleSAML\Assert\AssertionFailedException;
use SimpleSAML\XML\Assert\Assert;
/**
* Class \SimpleSAML\Test\XML\Assert\NMTokenTest
*
* @package simplesamlphp/xml-common
*/
#[CoversClass(Assert::class)]
final class NMTokenTest extends TestCase
{
/**
* @param boolean $shouldPass
* @param string $nmtoken
*/
#[DataProvider('provideNMToken')]
public function testValidToken(bool $shouldPass, string $nmtoken): void
{
try {
Assert::validNMToken($nmtoken);
$this->assertTrue($shouldPass);
} catch (AssertionFailedException $e) {
$this->assertFalse($shouldPass);
}
}
/**
* @return array<int, array{0: bool, 1: string}>
*/
public static function provideNMToken(): array
{
return [
[true, 'Snoopy'],
[true, 'CMS'],
[true, 'fööbár'],
[true, '1950-10-04'],
[true, '0836217462'],
// Spaces are forbidden
[false, 'foo bar'],
// Commas are forbidden
[false, 'foo,bar'],
// Trailing newlines are forbidden
[false, "foobar\n"],
];
}
}

View File

@@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\Test\XML\Assert;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use SimpleSAML\Assert\AssertionFailedException;
use SimpleSAML\XML\Assert\Assert;
/**
* Class \SimpleSAML\Test\XML\Assert\NMTokensTest
*
* @package simplesamlphp/xml-common
*/
#[CoversClass(Assert::class)]
final class NMTokensTest extends TestCase
{
/**
* @param boolean $shouldPass
* @param string $nmtokens
*/
#[DataProvider('provideNMTokens')]
public function testValidTokens(bool $shouldPass, string $nmtokens): void
{
try {
Assert::validNMTokens($nmtokens);
$this->assertTrue($shouldPass);
} catch (AssertionFailedException $e) {
$this->assertFalse($shouldPass);
}
}
/**
* @return array<int, array{0: bool, 1: string}>
*/
public static function provideNMTokens(): array
{
return [
[true, 'Snoopy'],
[true, 'CMS'],
[true, 'fööbár'],
[true, '1950-10-04'],
[true, '0836217462 0836217463'],
[true, 'foo bar'],
// Quotes are forbidden
[false, 'foo "bar" baz'],
// Commas are forbidden
[false, 'foo,bar'],
// Trailing newlines are forbidden
[false, "foobar\n"],
];
}
}

View File

@@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\Test\XML\Assert;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use SimpleSAML\Assert\AssertionFailedException;
use SimpleSAML\XML\Assert\Assert;
/**
* Class \SimpleSAML\Test\XML\Assert\QNameTest
*
* @package simplesamlphp/xml-common
*/
#[CoversClass(Assert::class)]
final class QNameTest extends TestCase
{
/**
* @param boolean $shouldPass
* @param string $name
*/
#[DataProvider('provideQName')]
public function testValidQName(bool $shouldPass, string $name): void
{
try {
Assert::validQName($name);
$this->assertTrue($shouldPass);
} catch (AssertionFailedException $e) {
$this->assertFalse($shouldPass);
}
}
/**
* @return array<int, array{0: bool, 1: string}>
*/
public static function provideQName(): array
{
return [
[true, 'some:Test'],
[true, 'some:_Test'],
[true, '_some:_Test'],
[true, 'Test'],
// Cannot start with a colon
[false, ':test'],
// Cannot contain multiple colons
[false, 'test:test:test'],
// Cannot start with a number
[false, '1Test'],
// Cannot contain a wildcard character
[false, 'Te*st'],
// Prefixed newlines are forbidden
[false, "\nsome:Test"],
// Trailing newlines are forbidden
[false, "some:Test\n"],
];
}
}

View File

@@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\Test\XML;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\TestCase;
use SimpleSAML\XML\Registry\ElementRegistry;
/**
* @package simplesamlphp\xml-common
*/
#[CoversClass(ElementRegistry::class)]
#[Group('registry')]
final class ElementRegistryTest extends TestCase
{
/** @var \SimpleSAML\XML\Registry\ElementRegistry */
protected static ElementRegistry $registry;
/**
*/
public static function setUpBeforeClass(): void
{
self::$registry = ElementRegistry::getInstance();
self::$registry->registerElementHandler('\SimpleSAML\Test\XML\Element');
}
/**
*/
public function testFetchingHandlerWorks(): void
{
$handler = self::$registry->getElementHandler('urn:x-simplesamlphp:namespace', 'Element');
$this->assertEquals($handler, '\SimpleSAML\Test\XML\Element');
}
/**
*/
public function testAddingHandlerWorks(): void
{
self::$registry->registerElementHandler('\SimpleSAML\Test\XML\ExtendableElement');
$handler = self::$registry->getElementHandler('urn:x-simplesamlphp:namespace', 'ExtendableElement');
$this->assertEquals($handler, '\SimpleSAML\Test\XML\ExtendableElement');
}
/**
*/
public function testUnknownHandlerReturnsNull(): void
{
$handler = self::$registry->getElementHandler('urn:x-simplesamlphp:namespace', 'UnknownElement');
$this->assertNull($handler);
}
}

View File

@@ -0,0 +1,65 @@
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE schema
PUBLIC "-//W3C//DTD XMLSchema 200102//EN" "http://www.w3.org/2001/XMLSchema.dtd"
[
<!ATTLIST schema
xmlns:ds CDATA #FIXED "urn:x-simplesamlphp:namespace">
<!ENTITY ssp 'urn:x-simplesamlphp:namespace'>
<!ENTITY % p ''>
<!ENTITY % s ''>
]>
<!-- Schema for SimpleSAMLphp dummy classes -->
<schema xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:ssp="urn:x-simplesamlphp:namespace"
targetNamespace="urn:x-simplesamlphp:namespace"
version="0.1" elementFormDefault="qualified">
<!-- Start ExtendableElement -->
<element name="ExtendableElement" type="ssp:ExtendableElementType"/>
<complexType name="ExtendableElementType">
<sequence>
<element ref="ssp:Chunk"/>
<any namespace="##any" processContents="lax"/>
<!-- (1,1) elements from (1,1) external namespace -->
</sequence>
</complexType>
<!-- End ExtendableElement -->
<!-- Start Chunk -->
<element name="Chunk" type="string"/>
<!-- End Chunk -->
<!-- Start BooleanElement -->
<element name="BooleanElement" type="boolean"/>
<!-- End BooleanElement -->
<!-- Start StringElement -->
<element name="StringElement" type="string"/>
<!-- End StringElement -->
<!-- Start URIElement -->
<element name="URIElement" type="anyURI"/>
<!-- End URIElement -->
<!-- Start ExtendableAttributesElement -->
<element name="ExtendableAttributesElement" type="ssp:ExtendableAttributesElementType"/>
<complexType name="ExtendableAttributesElementType">
<anyAttribute namespace="##any" processContents="lax"/>
</complexType>
<!-- End ExtendableAttributesElement -->
</schema>