Обновление клиента (apps, 3rdparty, install)

This commit is contained in:
root
2026-03-16 08:42:57 +00:00
parent b8905de237
commit f390426546
3354 changed files with 505213 additions and 3 deletions
+661
View File
@@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If 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 convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<http://www.gnu.org/licenses/>.
@@ -0,0 +1,94 @@
<?php declare(strict_types=1);
/**
* @copyright Copyright (c) 2017 Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace SearchDAV\Backend;
use Sabre\DAV\INode;
use SearchDAV\Query\Query;
interface ISearchBackend {
/**
* Get the path of the search arbiter of this backend
*
* The search arbiter is the URI that the client will send its SEARCH requests to
* Note that this is not required to be the same as the search scopes which determine what to search in
*
* The returned value should be a path relative the root of the dav server.
*
* For example, if you want to support SEARCH requests on `https://example.com/dav.php/search`
* with the sabre/dav server listening on `/dav.php` you should return `search` as arbiter path.
*
* @return string
*/
public function getArbiterPath(): string;
/**
* Whether the search backend supports search requests on this scope
*
* The scope defines the resource that it being searched, such as a folder or address book.
*
* Note that a search arbiter has no inherit limitations on which scopes it can support and scopes
* that reside on a different dav server entirely might be considered valid by an implementation.
*
* One example use case for this would be a service that provides additional indexing on a 3rd party service.
*
* @param string $href an absolute uri of the search scope
* @param string|integer $depth 0, 1 or 'infinite'
* @param string|null $path the path of the search scope relative to the dav server, or null if the scope is outside the dav server
* @return bool
*/
public function isValidScope(string $href, $depth, ?string $path): bool;
/**
* List the available properties that can be used in search
*
* This is used to tell the search client what properties can be queried, used to filter and used to sort.
*
* Since sabre's PropFind handling mechanism is used to return the properties to the client, it's required that all
* properties which are listed as selectable have a PropFind handler set.
*
* @param string $href an absolute uri of the search scope
* @param string|null $path the path of the search scope relative to the dav server, or null if the scope is outside the dav server
* @return SearchPropertyDefinition[]
*/
public function getPropertyDefinitionsForScope(string $href, ?string $path): array;
/**
* Preform the search request
*
* The search results consist of the uri for the found resource and an INode describing the resource
* To return the properties requested by the query sabre's existing PropFind method is used, thus the search implementation
* is not required to collect these properties and is free to ignore the `select` part of the query
*
* @param Query $query
* @return SearchResult[]
*/
public function search(Query $query): array;
/**
* Called by the search plugin once the nodes to be returned have been found.
* This can be used to more efficiently load the requested properties for the results.
*
* @param INode[] $nodes
* @param string[] $requestProperties
*/
public function preloadPropertyFor(array $nodes, array $requestProperties): void;
}
@@ -0,0 +1,66 @@
<?php declare(strict_types=1);
/**
* @copyright Copyright (c) 2017 Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace SearchDAV\Backend;
class SearchPropertyDefinition {
const XS = '{http://www.w3.org/2001/XMLSchema}';
const DATATYPE_STRING = self::XS . 'string';
const DATATYPE_INTEGER = self::XS . 'integer';
const DATATYPE_NONNEGATIVE_INTEGER = self::XS . 'nonNegativeInteger';
const DATATYPE_NON_NEGATIVE_INTEGER = self::XS . 'nonNegativeInteger';
const DATATYPE_DECIMAL = self::XS . 'decimal';
const DATATYPE_DATETIME = self::XS . 'dateTime';
const DATATYPE_BOOLEAN = self::XS . 'boolean';
/** @var boolean */
public $searchable;
/** @var boolean */
public $selectable;
/** @var boolean */
public $sortable;
/** @var boolean */
public $caseSensitive;
/** @var string */
public $dataType;
/** @var string */
public $name;
/**
* SearchProperty constructor.
*
* @param string $name the name and namespace of the property in clark notation
* @param bool $searchable whether this property can be used as part of a search query
* @param bool $selectable whether this property can be returned as part of a search result
* @param bool $sortable whether this property can be used to sort the search result
* @param string $dataType the datatype of the property, one of the SearchProperty::DATATYPE_ constants or any XSD datatype in clark notation
* @param bool $caseSensitive whether comparisons on the property are case-sensitive, only applies to string properties
*/
public function __construct(string $name, bool $selectable, bool $searchable, bool $sortable, string $dataType = self::DATATYPE_STRING, bool $caseSensitive = true) {
$this->searchable = $searchable;
$this->selectable = $selectable;
$this->sortable = $sortable;
$this->dataType = $dataType;
$this->name = $name;
$this->caseSensitive = $caseSensitive;
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php declare(strict_types=1);
/**
* @copyright Copyright (c) 2017 Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace SearchDAV\Backend;
use Sabre\DAV\INode;
class SearchResult {
/** @var INode */
public $node;
/** @var string */
public $href;
/**
* SearchResult constructor.
*
* @param INode $node
* @param string $href
*/
public function __construct(INode $node, string $href) {
$this->node = $node;
$this->href = $href;
}
}
+107
View File
@@ -0,0 +1,107 @@
<?php declare(strict_types=1);
/**
* @copyright Copyright (c) 2017 Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace SearchDAV\DAV;
use Sabre\DAV\Exception\BadRequest;
use Sabre\DAV\Xml\Response\MultiStatus;
use Sabre\HTTP\RequestInterface;
use Sabre\HTTP\ResponseInterface;
use SearchDAV\Backend\ISearchBackend;
use SearchDAV\Backend\SearchPropertyDefinition;
use SearchDAV\XML\BasicSearch;
use SearchDAV\XML\BasicSearchSchema;
use SearchDAV\XML\PropDesc;
use SearchDAV\XML\QueryDiscoverResponse;
use SearchDAV\XML\Scope;
class DiscoverHandler {
/** @var ISearchBackend */
private $searchBackend;
/** @var PathHelper */
private $pathHelper;
/** @var QueryParser */
private $queryParser;
/**
* @param ISearchBackend $searchBackend
* @param PathHelper $pathHelper
* @param QueryParser $queryParser
*/
public function __construct(ISearchBackend $searchBackend, PathHelper $pathHelper, QueryParser $queryParser) {
$this->searchBackend = $searchBackend;
$this->pathHelper = $pathHelper;
$this->queryParser = $queryParser;
}
public function handelDiscoverRequest($xml, RequestInterface $request, ResponseInterface $response): bool {
if (!isset($xml['{DAV:}basicsearch'])) {
$response->setStatus(400);
$response->setBody('Unexpected xml content for query-schema-discovery, expected basicsearch');
return false;
}
/** @var BasicSearch $query */
$query = $xml['{DAV:}basicsearch'];
$scopes = $query->from;
$results = array_map(function (Scope $scope) {
$scope->path = $this->pathHelper->getPathFromUri($scope->href);
if ($this->searchBackend->isValidScope($scope->href, $scope->depth, $scope->path)) {
$searchProperties = $this->searchBackend->getPropertyDefinitionsForScope($scope->href, $scope->path);
$searchSchema = $this->getBasicSearchForProperties($searchProperties);
return new QueryDiscoverResponse($scope->href, $searchSchema, 200);
} else {
return new QueryDiscoverResponse($scope->href, null, 404); // TODO something other than 404? 403 maybe
}
}, $scopes);
$multiStatus = new MultiStatus($results);
$response->setStatus(207);
$response->setHeader('Content-Type', 'application/xml; charset="utf-8"');
$response->setBody($this->queryParser->write('{DAV:}multistatus', $multiStatus, $request->getUrl()));
return false;
}
private function hashDefinition(SearchPropertyDefinition $definition): string {
return $definition->dataType
. (($definition->searchable) ? '1' : '0')
. (($definition->sortable) ? '1' : '0')
. (($definition->selectable) ? '1' : '0');
}
/**
* @param SearchPropertyDefinition[] $propertyDefinitions
* @return BasicSearchSchema
*/
private function getBasicSearchForProperties(array $propertyDefinitions): BasicSearchSchema {
/** @var PropDesc[] $groups */
$groups = [];
foreach ($propertyDefinitions as $propertyDefinition) {
$key = $this->hashDefinition($propertyDefinition);
if (!isset($groups[$key])) {
$groups[$key] = new PropDesc($propertyDefinition);
}
$groups[$key]->properties[] = $propertyDefinition->name;
}
return new BasicSearchSchema(array_values($groups));
}
}
+50
View File
@@ -0,0 +1,50 @@
<?php declare(strict_types=1);
/**
* @copyright Copyright (c) 2017 Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace SearchDAV\DAV;
use Sabre\DAV\Exception\Forbidden;
use Sabre\DAV\Server;
class PathHelper {
/** @var Server */
private $server;
/**
* PathHelper constructor.
*
* @param Server $server
*/
public function __construct(Server $server) {
$this->server = $server;
}
public function getPathFromUri(string $uri): ?string {
if (strpos($uri, '://') === false) {
return $uri;
}
try {
return ($uri === '' && $this->server->getBaseUri() === '/') ? '' : $this->server->calculateUri($uri);
} catch (Forbidden $e) {
return null;
}
}
}
+83
View File
@@ -0,0 +1,83 @@
<?php declare(strict_types=1);
/**
* @copyright Copyright (c) 2017 Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace SearchDAV\DAV;
use Sabre\Xml\Element;
use Sabre\Xml\Reader;
use Sabre\Xml\Service;
use SearchDAV\XML\BasicSearch;
use SearchDAV\XML\Limit;
use SearchDAV\XML\Literal;
use SearchDAV\XML\Operator;
use SearchDAV\XML\Order;
use SearchDAV\XML\Scope;
use function Sabre\Xml\Deserializer\keyValue;
use function Sabre\Xml\Deserializer\repeatingElements;
class QueryParser extends Service {
public $namespaceMap = [
'DAV:' => 'd',
'http://sabredav.org/ns' => 's',
'http://www.w3.org/2001/XMLSchema' => 'xs',
SearchPlugin::SEARCHDAV_NS => 'sd'
];
public function __construct() {
$this->elementMap = [
'{DAV:}literal' => Literal::class,
'{DAV:}searchrequest' => Element\KeyValue::class,
'{DAV:}query-schema-discovery' => Element\KeyValue::class,
'{DAV:}basicsearch' => BasicSearch::class,
'{DAV:}select' => function (Reader $reader) {
return keyValue($reader, '{DAV:}scope')['{DAV:}prop'];
},
'{DAV:}from' => function (Reader $reader) {
return repeatingElements($reader, '{DAV:}scope');
},
'{DAV:}orderby' => function (Reader $reader) {
return repeatingElements($reader, '{DAV:}order');
},
'{DAV:}scope' => Scope::class,
'{DAV:}where' => function (Reader $reader) {
$operators = array_map(function ($element) {
return $element['value'];
}, $reader->parseGetElements());
return (isset($operators[0])) ? $operators[0] : null;
},
'{DAV:}prop' => Element\Elements::class,
'{DAV:}order' => Order::class,
'{DAV:}eq' => Operator::class,
'{DAV:}gt' => Operator::class,
'{DAV:}gte' => Operator::class,
'{DAV:}lt' => Operator::class,
'{DAV:}lte' => Operator::class,
'{DAV:}and' => Operator::class,
'{DAV:}or' => Operator::class,
'{DAV:}like' => Operator::class,
'{DAV:}contains' => Operator::class,
'{DAV:}not' => Operator::class,
'{DAV:}is-collection' => Operator::class,
'{DAV:}is-defined' => Operator::class,
'{DAV:}limit' => Limit::class,
];
}
}
+200
View File
@@ -0,0 +1,200 @@
<?php declare(strict_types=1);
/**
* @copyright Copyright (c) 2017 Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace SearchDAV\DAV;
use Sabre\DAV\Exception\BadRequest;
use Sabre\DAV\INode;
use Sabre\DAV\PropFind;
use Sabre\DAV\Server;
use Sabre\HTTP\ResponseInterface;
use SearchDAV\Backend\ISearchBackend;
use SearchDAV\Backend\SearchPropertyDefinition;
use SearchDAV\Backend\SearchResult;
use SearchDAV\Query\Operator;
use SearchDAV\Query\Order;
use SearchDAV\Query\Query;
use SearchDAV\XML\BasicSearch;
class SearchHandler {
/** @var ISearchBackend */
private $searchBackend;
/** @var PathHelper */
private $pathHelper;
/** @var Server */
private $server;
/**
* @param ISearchBackend $searchBackend
* @param PathHelper $pathHelper
* @param Server $server
*/
public function __construct(ISearchBackend $searchBackend, PathHelper $pathHelper, Server $server) {
$this->searchBackend = $searchBackend;
$this->pathHelper = $pathHelper;
$this->server = $server;
}
public function handleSearchRequest($xml, ResponseInterface $response): bool {
if (!isset($xml['{DAV:}basicsearch'])) {
$response->setStatus(400);
$response->setBody('Unexpected xml content for search request, expected basicsearch');
return false;
}
/** @var BasicSearch $query */
$query = $xml['{DAV:}basicsearch'];
if (!$query->select) {
$response->setStatus(400);
$response->setBody('Parse error: Missing {DAV:}select from {DAV:}basicsearch');
return false;
}
$response->setStatus(207);
$response->setHeader('Content-Type', 'application/xml; charset="utf-8"');
$allProps = [];
foreach ($query->from as $scope) {
$scope->path = $this->pathHelper->getPathFromUri($scope->href);
$props = $this->searchBackend->getPropertyDefinitionsForScope($scope->href, $scope->path);
foreach ($props as $prop) {
$allProps[$prop->name] = $prop;
}
}
try {
$results = $this->searchBackend->search($this->getQueryForXML($query, $allProps));
} catch (BadRequest $e) {
$response->setStatus(400);
$response->setBody($e->getMessage());
return false;
}
$data = $this->server->generateMultiStatus(iterator_to_array($this->getPropertiesIteratorResults(
$results,
$query->select
)), false);
$response->setBody($data);
return false;
}
/**
* @param BasicSearch $xml
* @param SearchPropertyDefinition[] $allProps
* @return Query
* @throws BadRequest
*/
private function getQueryForXML(BasicSearch $xml, array $allProps): Query {
$orderBy = array_map(function (\SearchDAV\XML\Order $order) use ($allProps) {
if (!isset($allProps[$order->property])) {
throw new BadRequest('requested order by property is not a valid property for this scope');
}
$prop = $allProps[$order->property];
if (!$prop->sortable) {
throw new BadRequest('requested order by property is not sortable');
}
return new Order($prop, $order->order);
}, $xml->orderBy);
$select = array_map(function ($propName) use ($allProps) {
if (!isset($allProps[$propName])) {
return null;
}
$prop = $allProps[$propName];
if (!$prop->selectable) {
throw new BadRequest('requested property is not selectable');
}
return $prop;
}, $xml->select);
$select = array_filter($select);
$where = $xml->where ? $this->transformOperator($xml->where, $allProps) : null;
return new Query($select, $xml->from, $where, $orderBy, $xml->limit);
}
/**
* @param \SearchDAV\XML\Operator $operator
* @param SearchPropertyDefinition[] $allProps
* @return Operator
* @throws BadRequest
*/
private function transformOperator(\SearchDAV\XML\Operator $operator, array $allProps): Operator {
$arguments = array_map(function ($argument) use ($allProps) {
if (is_string($argument)) {
if (!isset($allProps[$argument])) {
throw new BadRequest('requested search property is not a valid property for this scope');
}
$prop = $allProps[$argument];
if (!$prop->searchable) {
throw new BadRequest('requested search property is not searchable');
}
return $prop;
} else {
if ($argument instanceof \SearchDAV\XML\Operator) {
return $this->transformOperator($argument, $allProps);
} else {
return $argument;
}
}
}, $operator->arguments);
return new Operator($operator->type, $arguments);
}
/**
* Returns a list of properties for a given path
*
* The path that should be supplied should have the baseUrl stripped out
* The list of properties should be supplied in Clark notation. If the list is empty
* 'allprops' is assumed.
*
* If a depth of 1 is requested child elements will also be returned.
*
* @param SearchResult[] $results
* @param string[] $propertyNames
* @param int $depth
* @return \Iterator<array>
*/
private function getPropertiesIteratorResults(array $results, array $propertyNames = [], int $depth = 0): \Iterator {
$propFindType = $propertyNames ? PropFind::NORMAL : PropFind::ALLPROPS;
$this->searchBackend->preloadPropertyFor(array_map(function (SearchResult $result): INode {
return $result->node;
}, $results), $propertyNames);
foreach ($results as $result) {
$node = $result->node;
$propFind = new PropFind($result->href, $propertyNames, $depth, $propFindType);
$r = $this->server->getPropertiesByNode($propFind, $node);
if ($r) {
$result = $propFind->getResultForMultiStatus();
$result['href'] = $propFind->getPath();
// WebDAV recommends adding a slash to the path, if the path is
// a collection.
// Furthermore, iCal also demands this to be the case for
// principals. This is non-standard, but we support it.
$resourceType = $this->server->getResourceTypeForNode($node);
if (in_array('{DAV:}collection', $resourceType) || in_array('{DAV:}principal', $resourceType)) {
$result['href'] .= '/';
}
yield $result;
}
}
}
}
+128
View File
@@ -0,0 +1,128 @@
<?php declare(strict_types=1);
/**
* @copyright Copyright (c) 2017 Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace SearchDAV\DAV;
use Sabre\DAV\INode;
use Sabre\DAV\PropFind;
use Sabre\DAV\Server;
use Sabre\DAV\ServerPlugin;
use Sabre\HTTP\RequestInterface;
use Sabre\HTTP\ResponseInterface;
use Sabre\Xml\ParseException;
use SearchDAV\Backend\ISearchBackend;
use SearchDAV\XML\SupportedQueryGrammar;
class SearchPlugin extends ServerPlugin {
const SEARCHDAV_NS = 'https://github.com/icewind1991/SearchDAV/ns';
/** @var ISearchBackend */
private $searchBackend;
/** @var QueryParser */
private $queryParser;
/** @var PathHelper */
private $pathHelper;
/** @var SearchHandler */
private $search;
/** @var DiscoverHandler */
private $discover;
public function __construct(ISearchBackend $searchBackend) {
$this->searchBackend = $searchBackend;
$this->queryParser = new QueryParser();
}
public function initialize(Server $server): void {
$this->pathHelper = new PathHelper($server);
$this->search = new SearchHandler($this->searchBackend, $this->pathHelper, $server);
$this->discover = new DiscoverHandler($this->searchBackend, $this->pathHelper, $this->queryParser);
$server->on('method:SEARCH', [$this, 'searchHandler']);
$server->on('afterMethod:OPTIONS', [$this, 'optionHandler']);
$server->on('propFind', [$this, 'propFindHandler']);
}
public function propFindHandler(PropFind $propFind, INode $node): void {
if ($propFind->getPath() === $this->searchBackend->getArbiterPath()) {
$propFind->handle('{DAV:}supported-query-grammar-set', new SupportedQueryGrammar());
}
}
/**
* SEARCH is allowed for users files
*
* @param string $path
* @return string[]
*/
public function getHTTPMethods($path): array {
$path = $this->pathHelper->getPathFromUri($path);
if ($this->searchBackend->getArbiterPath() === $path) {
return ['SEARCH'];
} else {
return [];
}
}
public function optionHandler(RequestInterface $request, ResponseInterface $response): void {
if ($request->getPath() === $this->searchBackend->getArbiterPath()) {
$response->addHeader('DASL', '<DAV:basicsearch>');
}
}
public function searchHandler(RequestInterface $request, ResponseInterface $response): bool {
$contentType = $request->getHeader('Content-Type') ?? '';
// Currently, we only support xml search queries
if ((strpos($contentType, 'text/xml') === false) && (strpos($contentType, 'application/xml') === false)) {
return true;
}
if ($request->getPath() !== $this->searchBackend->getArbiterPath()) {
return true;
}
try {
$xml = $this->queryParser->parse(
$request->getBodyAsString(),
$request->getUrl(),
$documentType
);
} catch (ParseException $e) {
$response->setStatus(400);
$response->setBody('Parse error: ' . $e->getMessage());
return false;
}
switch ($documentType) {
case '{DAV:}searchrequest':
return $this->search->handleSearchRequest($xml, $response);
case '{DAV:}query-schema-discovery':
return $this->discover->handelDiscoverRequest($xml, $request, $response);
default:
$response->setStatus(400);
$response->setBody('Unexpected document type: ' . $documentType . ' for this Content-Type, expected {DAV:}searchrequest or {DAV:}query-schema-discovery');
return false;
}
}
}
+39
View File
@@ -0,0 +1,39 @@
<?php declare(strict_types=1);
/**
* @copyright Copyright (c) 2018 Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace SearchDAV\Query;
class Limit {
/**
* @var integer
*
* The maximum number of results to be returned
*
* If set to 0 then no limit should be imposed
*/
public $maxResults = 0;
/**
* @var integer
*
* The index of the first result to be returned (offset)
*/
public $firstResult = 0;
}
+40
View File
@@ -0,0 +1,40 @@
<?php declare(strict_types=1);
/**
* @copyright Copyright (c) 2018 Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace SearchDAV\Query;
class Literal {
/**
* @var string|boolean|\DateTime|integer
*
* The value of the literal
*/
public $value;
/**
* Literal constructor.
*
* @param bool|\DateTime|int|string $value
*/
public function __construct($value = '') {
$this->value = $value;
}
}
+68
View File
@@ -0,0 +1,68 @@
<?php declare(strict_types=1);
/**
* @copyright Copyright (c) 2018 Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace SearchDAV\Query;
class Operator {
const OPERATION_AND = '{DAV:}and';
const OPERATION_OR = '{DAV:}or';
const OPERATION_NOT = '{DAV:}not';
const OPERATION_EQUAL = '{DAV:}eq';
const OPERATION_LESS_THAN = '{DAV:}lt';
const OPERATION_LESS_OR_EQUAL_THAN = '{DAV:}lte';
const OPERATION_GREATER_THAN = '{DAV:}gt';
const OPERATION_GREATER_OR_EQUAL_THAN = '{DAV:}gte';
const OPERATION_IS_COLLECTION = '{DAV:}is-collection';
const OPERATION_IS_DEFINED = '{DAV:}is-defined';
const OPERATION_IS_LIKE = '{DAV:}like';
const OPERATION_CONTAINS = '{DAV:}contains';
/**
* @var string
*
* The type of operation, one of the Operator::OPERATION_* constants
*/
public $type;
/**
* @var (Literal|\SearchDAV\Backend\SearchPropertyDefinition|Operator)[]
*
* The list of arguments for the operation
*
* - SearchPropDefinition: property for comparison
* - Literal: literal value for comparison
* - Operator: nested operation for and/or/not operations
*
* Which type and what number of argument an Operator takes depends on the operator type.
*/
public $arguments;
/**
* Operator constructor.
*
* @param string $type
* @param (Literal|\SearchDAV\Backend\SearchPropertyDefinition|Operator)[] $arguments
*/
public function __construct(string $type = '', array $arguments = []) {
$this->type = $type;
$this->arguments = $arguments;
}
}
+52
View File
@@ -0,0 +1,52 @@
<?php declare(strict_types=1);
/**
* @copyright Copyright (c) 2018 Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace SearchDAV\Query;
use SearchDAV\Backend\SearchPropertyDefinition;
class Order {
const ASC = 'ascending';
const DESC = 'descending';
/**
* @var SearchPropertyDefinition
*
* The property that should be sorted on.
*/
public $property;
/**
* @var string 'ascending' or 'descending'
*
* The sort direction
*/
public $order;
/**
* Order constructor.
* @param SearchPropertyDefinition $property
* @param string $order
*/
public function __construct(SearchPropertyDefinition $property, string $order) {
$this->property = $property;
$this->order = $order;
}
}
+78
View File
@@ -0,0 +1,78 @@
<?php declare(strict_types=1);
/**
* @copyright Copyright (c) 2018 Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace SearchDAV\Query;
use SearchDAV\Backend\SearchPropertyDefinition;
class Query {
/**
* @var SearchPropertyDefinition[]
*
* The list of properties to be selected
*/
public $select;
/**
* @var Scope[]
*
* The collections to perform the search in
*/
public $from;
/**
* @var ?Operator
*
* The search operator, either a comparison ('gt', 'eq', ...) or a boolean operator ('and', 'or', 'not')
*/
public $where;
/**
* @var Order[]
*
* The list of order operations that should be used to order the results.
*
* Each order operations consists of a property to sort on and a sort direction.
* If more than one order operations are specified, the comparisons for ordering should
* be applied in the order that the order operations are defined in with the earlier comparisons being
* more significant.
*/
public $orderBy;
/**
* @var Limit
*
* The limit and offset for the search query
*/
public $limit;
/**
* Query constructor.
* @param SearchPropertyDefinition[] $select
* @param Scope[] $from
* @param Operator|null $where
* @param Order[] $orderBy
* @param Limit $limit
*/
public function __construct(array $select, array $from, ?Operator $where, array $orderBy, Limit $limit) {
$this->select = $select;
$this->from = $from;
$this->where = $where;
$this->orderBy = $orderBy;
$this->limit = $limit;
}
}
+59
View File
@@ -0,0 +1,59 @@
<?php declare(strict_types=1);
/**
* @copyright Copyright (c) 2018 Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace SearchDAV\Query;
class Scope {
/**
* @var string
*
* The scope of the search, either as absolute uri or as a path relative to the
* search arbiter.
*/
public $href;
/**
* @var string|int 0, 1 or 'infinite'
*
* How deep the search query should be with 0 being only the scope itself,
* 1 being all direct child entries of the scope and infinite being all entries
* in the scope collection at any depth.
*/
public $depth;
/**
* @var string|null
*
* the path of the search scope relative to the dav server, or null if the scope is outside the dav server
*/
public $path;
/**
* @param string $href
* @param int|string $depth
* @param string|null $path
*/
public function __construct(string $href = '', $depth = 1, ?string $path = null) {
$this->href = $href;
$this->depth = $depth;
$this->path = $path;
}
}
+98
View File
@@ -0,0 +1,98 @@
<?php declare(strict_types=1);
/**
* @copyright Copyright (c) 2017 Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace SearchDAV\XML;
use Sabre\Xml\ParseException;
use Sabre\Xml\Reader;
use Sabre\Xml\XmlDeserializable;
use function Sabre\Xml\Deserializer\keyValue;
/**
* The object representation of a search query made by the client
*/
class BasicSearch implements XmlDeserializable {
/**
* @var string[]
*
* The list of properties to be selected, specified in clark notation
*/
public $select;
/**
* @var Scope[]
*
* The collections to perform the search in
*/
public $from;
/**
* @var ?Operator
*
* The search operator, either a comparison ('gt', 'eq', ...) or a boolean operator ('and', 'or', 'not')
*/
public $where;
/**
* @var Order[]
*
* The list of order operations that should be used to order the results.
*
* Each order operations consists of a property to sort on and a sort direction.
* If more then one order operations are specified, the comparisons for ordering should
* be applied in the order that the order operations are defined in with the earlier comparisons being
* more significant.
*/
public $orderBy;
/**
* @var Limit
*
* The limit and offset for the search query
*/
public $limit;
public function __construct(array $select, array $from, ?Operator $where, array $orderBy, Limit $limit) {
$this->select = $select;
$this->from = $from;
$this->where = $where;
$this->orderBy = $orderBy;
$this->limit = $limit;
}
/**
* @param Reader $reader
* @return BasicSearch
* @throws ParseException
*/
public static function xmlDeserialize(Reader $reader): BasicSearch {
$elements = keyValue($reader);
if (!isset($elements['{DAV:}from'])) {
throw new ParseException('Missing {DAV:}from when parsing {DAV:}basicsearch');
}
return new BasicSearch(
$elements['{DAV:}select'] ?? [],
$elements['{DAV:}from'],
$elements['{DAV:}where'] ?? null,
$elements['{DAV:}orderby'] ?? [],
$elements['{DAV:}limit'] ?? new Limit()
);
}
}
@@ -0,0 +1,49 @@
<?php declare(strict_types=1);
/**
* @copyright Copyright (c) 2017 Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace SearchDAV\XML;
use Sabre\Xml\Writer;
use Sabre\Xml\XmlSerializable;
class BasicSearchSchema implements XmlSerializable {
/** @var PropDesc[] */
public $properties;
/**
* BasicSearchSchema constructor.
*
* @param PropDesc[] $properties
*/
public function __construct(array $properties) {
$this->properties = $properties;
}
public function xmlSerialize(Writer $writer): void {
$childs = array_map(function (PropDesc $propDesc) {
return [
'name' => '{DAV:}propdesc',
'value' => $propDesc
];
}, $this->properties);
$writer->writeElement('{DAV:}properties', $childs);
}
}
+45
View File
@@ -0,0 +1,45 @@
<?php declare(strict_types=1);
/**
* @copyright Copyright (c) 2017 Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace SearchDAV\XML;
use Sabre\Xml\Reader;
use Sabre\Xml\XmlDeserializable;
use SearchDAV\DAV\SearchPlugin;
use function Sabre\Xml\Deserializer\keyValue;
/**
* The limit and offset of a search query
*/
class Limit extends \SearchDAV\Query\Limit implements XmlDeserializable {
public static function xmlDeserialize(Reader $reader): Limit {
$limit = new self();
$elements = keyValue($reader);
$namespace = SearchPlugin::SEARCHDAV_NS;
$limit->maxResults = isset($elements['{DAV:}nresults']) ? $elements['{DAV:}nresults'] : 0;
$firstResult = '{' . $namespace . '}firstresult';
$limit->firstResult = isset($elements[$firstResult]) ? $elements[$firstResult] : 0;
return $limit;
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php declare(strict_types=1);
/**
* @copyright Copyright (c) 2017 Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace SearchDAV\XML;
use Sabre\Xml\Reader;
use Sabre\Xml\XmlDeserializable;
class Literal extends \SearchDAV\Query\Literal implements XmlDeserializable {
public static function xmlDeserialize(Reader $reader): Literal {
$literal = new self();
if ($reader->isEmptyElement) {
$literal->value = '';
} else {
$literal->value = $reader->readText();
}
$reader->read();
return $literal;
}
}
+94
View File
@@ -0,0 +1,94 @@
<?php declare(strict_types=1);
/**
* @copyright Copyright (c) 2017 Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace SearchDAV\XML;
use Sabre\Xml\Reader;
use Sabre\Xml\XmlDeserializable;
use SearchDAV\Query\Operator as QueryOperator;
class Operator implements XmlDeserializable {
/**
* @var string
*
* The type of operation, one of the Operator::OPERATION_* constants
*/
public $type;
/**
* @var (Literal|string|Operator)[]
*
* The list of arguments for the operation
*
* - string: property name for comparison
* - Literal: literal value for comparison
* - Operation: nested operation for and/or/not operations
*
* Which type and what number of argument an Operator takes depends on the operator type.
*/
public $arguments;
/**
* Operator constructor.
*
* @param string $type
* @param (Literal|string|Operator)[] $arguments
*/
public function __construct(string $type = '', array $arguments = []) {
$this->type = $type;
$this->arguments = $arguments;
}
public static function xmlDeserialize(Reader $reader): Operator {
$operator = new self();
$operator->type = $reader->getClark() ?? '';
if ($reader->isEmptyElement) {
$reader->next();
return $operator;
}
if ($operator->type === QueryOperator::OPERATION_CONTAINS) {
$operator->arguments[] = $reader->readString();
$reader->next();
return $operator;
}
$reader->read();
do {
if ($reader->nodeType === Reader::ELEMENT) {
$argument = $reader->parseCurrentElement();
if ($argument['name'] === '{DAV:}prop') {
$operator->arguments[] = $argument['value'][0] ?? '';
} else {
$operator->arguments[] = $argument['value'];
}
} else {
if (!$reader->read()) {
break;
}
}
} while ($reader->nodeType !== Reader::END_ELEMENT);
$reader->read();
return $operator;
}
}
+63
View File
@@ -0,0 +1,63 @@
<?php declare(strict_types=1);
/**
* @copyright Copyright (c) 2017 Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace SearchDAV\XML;
use Sabre\Xml\Reader;
use Sabre\Xml\XmlDeserializable;
use function Sabre\Xml\Deserializer\keyValue;
class Order implements XmlDeserializable {
/**
* @var string
*
* The property that should be sorted on.
*/
public $property;
/**
* @var string 'ascending' or 'descending'
*
* The sort direction
*/
public $order;
/**
* Order constructor.
*
* @param string $property
* @param string $order
*/
public function __construct(string $property = '', string $order = \SearchDAV\Query\Order::ASC) {
$this->property = $property;
$this->order = $order;
}
public static function xmlDeserialize(Reader $reader): Order {
$order = new self();
$childs = keyValue($reader);
$order->order = array_key_exists('{DAV:}descending', $childs) ? \SearchDAV\Query\Order::DESC : \SearchDAV\Query\Order::ASC;
$order->property = $childs['{DAV:}prop'][0];
return $order;
}
}
+78
View File
@@ -0,0 +1,78 @@
<?php declare(strict_types=1);
/**
* @copyright Copyright (c) 2017 Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace SearchDAV\XML;
use Sabre\Xml\Writer;
use Sabre\Xml\XmlSerializable;
use SearchDAV\Backend\SearchPropertyDefinition;
class PropDesc implements XmlSerializable {
/**
* @var string[]
*/
public $properties = [];
/**
* @var string
*/
public $dataType;
/**
* @var boolean
*/
public $searchable;
/**
* @var boolean
*/
public $selectable;
/**
* @var boolean
*/
public $sortable;
public function __construct(SearchPropertyDefinition $propertyDefinition) {
$this->dataType = $propertyDefinition->dataType;
$this->sortable = $propertyDefinition->sortable;
$this->selectable = $propertyDefinition->selectable;
$this->searchable = $propertyDefinition->searchable;
}
public function xmlSerialize(Writer $writer): void {
$data = [
'{DAV:}dataType' => [$this->dataType => null]
];
if ($this->searchable) {
$data['{DAV:}searchable'] = null;
}
if ($this->sortable) {
$data['{DAV:}sortable'] = null;
}
if ($this->selectable) {
$data['{DAV:}selectable'] = null;
}
$writer->write(array_map(function ($propName) {
return [
'name' => '{DAV:}prop',
'value' => $propName
];
}, $this->properties));
$writer->write($data);
}
}
@@ -0,0 +1,61 @@
<?php declare(strict_types=1);
/**
* @copyright Copyright (c) 2017 Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace SearchDAV\XML;
use Sabre\DAV\Xml\Element\Response;
use Sabre\Xml\Writer;
use function Sabre\HTTP\encodePath;
class QueryDiscoverResponse extends Response {
/**
* @var BasicSearchSchema|null
*/
protected $schema;
/**
* QueryDiscoverResponse constructor.
*
* @param string $href
* @param BasicSearchSchema|null $schema
* @param null|int|string $httpStatus
*/
public function __construct($href, ?BasicSearchSchema $schema = null, $httpStatus = null) {
if ($httpStatus !== null) {
$httpStatus = (string)$httpStatus;
}
parent::__construct($href, [], $httpStatus);
$this->schema = $schema;
}
public function xmlSerialize(Writer $writer): void {
if ($status = $this->getHTTPStatus()) {
$writer->writeElement('{DAV:}status', 'HTTP/1.1 ' . $status . ' ' . \Sabre\HTTP\Response::$statusCodes[$status]);
}
$writer->writeElement('{DAV:}href', encodePath($this->getHref()));
if ($this->schema) {
$writer->writeElement('{DAV:}query-schema', [
'{DAV:}basicsearchschema' => $this->schema
]);
}
}
}
+38
View File
@@ -0,0 +1,38 @@
<?php declare(strict_types=1);
/**
* @copyright Copyright (c) 2017 Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace SearchDAV\XML;
use Sabre\Xml\Reader;
use Sabre\Xml\XmlDeserializable;
use function Sabre\Xml\Deserializer\keyValue;
class Scope extends \SearchDAV\Query\Scope implements XmlDeserializable {
public static function xmlDeserialize(Reader $reader): Scope {
$scope = new self();
$values = keyValue($reader);
$scope->href = $values['{DAV:}href'];
$scope->depth = $values['{DAV:}depth'];
return $scope;
}
}
@@ -0,0 +1,38 @@
<?php declare(strict_types=1);
/**
* @copyright Copyright (c) 2017 Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace SearchDAV\XML;
use Sabre\Xml\Writer;
use Sabre\Xml\XmlSerializable;
class SupportedQueryGrammar implements XmlSerializable {
const GRAMMAR_BASIC_SEARCH = '{DAV:}basicsearch';
public function xmlSerialize(Writer $writer): void {
$writer->startElement('{DAV:}supported-query-grammar');
$writer->startElement('{DAV:}grammar');
$writer->startElement(self::GRAMMAR_BASIC_SEARCH);
$writer->endElement();
$writer->endElement();
$writer->endElement();
}
}
+19
View File
@@ -0,0 +1,19 @@
Copyright (c) 2014 Robin Appelman <robin@icewind.nl>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+235
View File
@@ -0,0 +1,235 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.
The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.
An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based on the Program.
To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If 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 convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.
You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <http://www.gnu.org/licenses/>.
+121
View File
@@ -0,0 +1,121 @@
Creative Commons Legal Code
CC0 1.0 Universal
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
HEREUNDER.
Statement of Purpose
The laws of most jurisdictions throughout the world automatically confer
exclusive Copyright and Related Rights (defined below) upon the creator
and subsequent owner(s) (each and all, an "owner") of an original work of
authorship and/or a database (each, a "Work").
Certain owners wish to permanently relinquish those rights to a Work for
the purpose of contributing to a commons of creative, cultural and
scientific works ("Commons") that the public can reliably and without fear
of later claims of infringement build upon, modify, incorporate in other
works, reuse and redistribute as freely as possible in any form whatsoever
and for any purposes, including without limitation commercial purposes.
These owners may contribute to the Commons to promote the ideal of a free
culture and the further production of creative, cultural and scientific
works, or to gain reputation or greater distribution for their Work in
part through the use and efforts of others.
For these and/or other purposes and motivations, and without any
expectation of additional consideration or compensation, the person
associating CC0 with a Work (the "Affirmer"), to the extent that he or she
is an owner of Copyright and Related Rights in the Work, voluntarily
elects to apply CC0 to the Work and publicly distribute the Work under its
terms, with knowledge of his or her Copyright and Related Rights in the
Work and the meaning and intended legal effect of CC0 on those rights.
1. Copyright and Related Rights. A Work made available under CC0 may be
protected by copyright and related or neighboring rights ("Copyright and
Related Rights"). Copyright and Related Rights include, but are not
limited to, the following:
i. the right to reproduce, adapt, distribute, perform, display,
communicate, and translate a Work;
ii. moral rights retained by the original author(s) and/or performer(s);
iii. publicity and privacy rights pertaining to a person's image or
likeness depicted in a Work;
iv. rights protecting against unfair competition in regards to a Work,
subject to the limitations in paragraph 4(a), below;
v. rights protecting the extraction, dissemination, use and reuse of data
in a Work;
vi. database rights (such as those arising under Directive 96/9/EC of the
European Parliament and of the Council of 11 March 1996 on the legal
protection of databases, and under any national implementation
thereof, including any amended or successor version of such
directive); and
vii. other similar, equivalent or corresponding rights throughout the
world based on applicable law or treaty, and any national
implementations thereof.
2. Waiver. To the greatest extent permitted by, but not in contravention
of, applicable law, Affirmer hereby overtly, fully, permanently,
irrevocably and unconditionally waives, abandons, and surrenders all of
Affirmer's Copyright and Related Rights and associated claims and causes
of action, whether now known or unknown (including existing as well as
future claims and causes of action), in the Work (i) in all territories
worldwide, (ii) for the maximum duration provided by applicable law or
treaty (including future time extensions), (iii) in any current or future
medium and for any number of copies, and (iv) for any purpose whatsoever,
including without limitation commercial, advertising or promotional
purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
member of the public at large and to the detriment of Affirmer's heirs and
successors, fully intending that such Waiver shall not be subject to
revocation, rescission, cancellation, termination, or any other legal or
equitable action to disrupt the quiet enjoyment of the Work by the public
as contemplated by Affirmer's express Statement of Purpose.
3. Public License Fallback. Should any part of the Waiver for any reason
be judged legally invalid or ineffective under applicable law, then the
Waiver shall be preserved to the maximum extent permitted taking into
account Affirmer's express Statement of Purpose. In addition, to the
extent the Waiver is so judged Affirmer hereby grants to each affected
person a royalty-free, non transferable, non sublicensable, non exclusive,
irrevocable and unconditional license to exercise Affirmer's Copyright and
Related Rights in the Work (i) in all territories worldwide, (ii) for the
maximum duration provided by applicable law or treaty (including future
time extensions), (iii) in any current or future medium and for any number
of copies, and (iv) for any purpose whatsoever, including without
limitation commercial, advertising or promotional purposes (the
"License"). The License shall be deemed effective as of the date CC0 was
applied by Affirmer to the Work. Should any part of the License for any
reason be judged legally invalid or ineffective under applicable law, such
partial invalidity or ineffectiveness shall not invalidate the remainder
of the License, and in such case Affirmer hereby affirms that he or she
will not (i) exercise any of his or her remaining Copyright and Related
Rights in the Work or (ii) assert any associated claims and causes of
action with respect to the Work, in either case contrary to Affirmer's
express Statement of Purpose.
4. Limitations and Disclaimers.
a. No trademark or patent rights held by Affirmer are waived, abandoned,
surrendered, licensed or otherwise affected by this document.
b. Affirmer offers the Work as-is and makes no representations or
warranties of any kind concerning the Work, express, implied,
statutory or otherwise, including without limitation warranties of
title, merchantability, fitness for a particular purpose, non
infringement, or the absence of latent or other defects, accuracy, or
the present or absence of errors, whether or not discoverable, all to
the greatest extent permissible under applicable law.
c. Affirmer disclaims responsibility for clearing rights of other persons
that may apply to the Work or any use thereof, including without
limitation any person's Copyright and Related Rights in the Work.
Further, Affirmer disclaims responsibility for obtaining any necessary
consents, permissions or other rights required for any use of the
Work.
d. Affirmer understands and acknowledges that Creative Commons is not a
party to this document and has no duty or obligation with respect to
this CC0 or use of the Work.
+9
View File
@@ -0,0 +1,9 @@
MIT License
Copyright (c) <year> <copyright holders>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+69
View File
@@ -0,0 +1,69 @@
<?php declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2020 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace Icewind\SMB;
class ACL {
const TYPE_ALLOW = 0;
const TYPE_DENY = 1;
const MASK_READ = 0x0001;
const MASK_WRITE = 0x0002;
const MASK_EXECUTE = 0x00020;
const MASK_DELETE = 0x10000;
const FLAG_OBJECT_INHERIT = 0x1;
const FLAG_CONTAINER_INHERIT = 0x2;
/** @var int */
private $type;
/** @var int */
private $flags;
/** @var int */
private $mask;
public function __construct(int $type, int $flags, int $mask) {
$this->type = $type;
$this->flags = $flags;
$this->mask = $mask;
}
/**
* Check if the acl allows a specific permissions
*
* Note that this does not take inherited acls into account
*
* @param int $mask one of the ACL::MASK_* constants
* @return bool
*/
public function allows(int $mask): bool {
return $this->type === self::TYPE_ALLOW && ($this->mask & $mask) === $mask;
}
/**
* Check if the acl allows a specific permissions
*
* Note that this does not take inherited acls into account
*
* @param int $mask one of the ACL::MASK_* constants
* @return bool
*/
public function denies(int $mask): bool {
return $this->type === self::TYPE_DENY && ($this->mask & $mask) === $mask;
}
public function getType(): int {
return $this->type;
}
public function getFlags(): int {
return $this->flags;
}
public function getMask(): int {
return $this->mask;
}
}
+61
View File
@@ -0,0 +1,61 @@
<?php
/**
* SPDX-FileCopyrightText: 2018 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace Icewind\SMB;
abstract class AbstractServer implements IServer {
const LOCALE = 'en_US.UTF-8';
/** @var string */
protected $host;
/** @var IAuth */
protected $auth;
/** @var ISystem */
protected $system;
/** @var ITimeZoneProvider */
protected $timezoneProvider;
/** @var IOptions */
protected $options;
/**
* @param string $host
* @param IAuth $auth
* @param ISystem $system
* @param ITimeZoneProvider $timeZoneProvider
* @param IOptions $options
*/
public function __construct(string $host, IAuth $auth, ISystem $system, ITimeZoneProvider $timeZoneProvider, IOptions $options) {
$this->host = $host;
$this->auth = $auth;
$this->system = $system;
$this->timezoneProvider = $timeZoneProvider;
$this->options = $options;
}
public function getAuth(): IAuth {
return $this->auth;
}
public function getHost(): string {
return $this->host;
}
public function getTimeZone(): string {
return $this->timezoneProvider->get($this->host);
}
public function getSystem(): ISystem {
return $this->system;
}
public function getOptions(): IOptions {
return $this->options;
}
}
+37
View File
@@ -0,0 +1,37 @@
<?php
/**
* SPDX-FileCopyrightText: 2015 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB;
use Icewind\SMB\Exception\InvalidPathException;
abstract class AbstractShare implements IShare {
/** @var string[] */
private $forbiddenCharacters;
public function __construct() {
$this->forbiddenCharacters = ['?', '<', '>', ':', '*', '|', '"', chr(0), "\n", "\r"];
}
/**
* @param string $path
* @throws InvalidPathException
*/
protected function verifyPath(string $path): void {
foreach ($this->forbiddenCharacters as $char) {
if (strpos($path, $char) !== false) {
throw new InvalidPathException('Invalid path, "' . $char . '" is not allowed');
}
}
}
/**
* @param string[] $charList
*/
public function setForbiddenChars(array $charList): void {
$this->forbiddenCharacters = $charList;
}
}
+33
View File
@@ -0,0 +1,33 @@
<?php
/**
* SPDX-FileCopyrightText: 2018 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace Icewind\SMB;
use Icewind\SMB\Exception\Exception;
class AnonymousAuth implements IAuth {
public function getUsername(): ?string {
return null;
}
public function getWorkgroup(): ?string {
return 'dummy';
}
public function getPassword(): ?string {
return null;
}
public function getExtraCommandLineArguments(): string {
return '-N';
}
public function setExtraSmbClientOptions($smbClientState): void {
if (smbclient_option_set($smbClientState, SMBCLIENT_OPT_AUTO_ANONYMOUS_LOGIN, true) === false) {
throw new Exception("Failed to set smbclient options for anonymous auth");
}
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
/**
* SPDX-FileCopyrightText: 2018 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace Icewind\SMB;
class BasicAuth implements IAuth {
/** @var string */
private $username;
/** @var string|null */
private $workgroup;
/** @var string */
private $password;
public function __construct(string $username, ?string $workgroup, string $password) {
$this->username = $username;
$this->workgroup = $workgroup;
$this->password = $password;
}
public function getUsername(): ?string {
return $this->username;
}
public function getWorkgroup(): ?string {
return $this->workgroup;
}
public function getPassword(): ?string {
return $this->password;
}
public function getExtraCommandLineArguments(): string {
return ($this->workgroup) ? '-W ' . escapeshellarg($this->workgroup) : '';
}
public function setExtraSmbClientOptions($smbClientState): void {
// noop
}
}
+27
View File
@@ -0,0 +1,27 @@
<?php
/**
* SPDX-FileCopyrightText: 2016 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB;
class Change {
/** @var int */
private $code;
/** @var string */
private $path;
public function __construct(int $code, string $path) {
$this->code = $code;
$this->path = $path;
}
public function getCode(): int {
return $this->code;
}
public function getPath(): string {
return $this->path;
}
}
@@ -0,0 +1,10 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Exception;
class AccessDeniedException extends ConnectException {
}
@@ -0,0 +1,10 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Exception;
class AlreadyExistsException extends InvalidRequestException {
}
@@ -0,0 +1,10 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Exception;
class AuthenticationException extends ConnectException {
}
+10
View File
@@ -0,0 +1,10 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Exception;
class ConnectException extends Exception {
}
@@ -0,0 +1,10 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Exception;
class ConnectionAbortedException extends ConnectException {
}
@@ -0,0 +1,10 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Exception;
class ConnectionException extends ConnectException {
}
@@ -0,0 +1,10 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Exception;
class ConnectionRefusedException extends ConnectException {
}
@@ -0,0 +1,10 @@
<?php
/**
* SPDX-FileCopyrightText: 2020 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Exception;
class ConnectionResetException extends ConnectException {
}
@@ -0,0 +1,10 @@
<?php
/**
* SPDX-FileCopyrightText: 2016 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Exception;
class DependencyException extends Exception {
}
+51
View File
@@ -0,0 +1,51 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Exception;
use Throwable;
/**
* @psalm-consistent-constructor
*/
class Exception extends \Exception {
public function __construct(string $message = "", int $code = 0, ?Throwable $previous = null) {
parent::__construct($message, $code, $previous);
}
/**
* @param string|null $path
* @param string|int|null $error
* @return Exception
*/
public static function unknown(?string $path, $error): Exception {
$message = 'Unknown error (' . (string)$error . ')';
if ($path) {
$message .= ' for ' . $path;
}
return new Exception($message, is_int($error) ? $error : 0);
}
/**
* @param array<int|string, class-string<Exception>> $exceptionMap
* @param string|int|null $error
* @param string|null $path
* @return Exception
*/
public static function fromMap(array $exceptionMap, $error, ?string $path): Exception {
if (isset($exceptionMap[$error])) {
$exceptionClass = $exceptionMap[$error];
if (is_numeric($error)) {
return new $exceptionClass($path, $error);
} else {
return new $exceptionClass($path);
}
} else {
return Exception::unknown($path, $error);
}
}
}
@@ -0,0 +1,10 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Exception;
class FileInUseException extends InvalidRequestException {
}
@@ -0,0 +1,10 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Exception;
class ForbiddenException extends InvalidRequestException {
}
@@ -0,0 +1,10 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Exception;
class HostDownException extends ConnectException {
}
@@ -0,0 +1,10 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Exception;
class InvalidArgumentException extends InvalidRequestException {
}
@@ -0,0 +1,10 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Exception;
class InvalidHostException extends ConnectException {
}
@@ -0,0 +1,10 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Exception;
class InvalidParameterException extends InvalidRequestException {
}
@@ -0,0 +1,10 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Exception;
class InvalidPathException extends InvalidRequestException {
}
@@ -0,0 +1,29 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Exception;
class InvalidRequestException extends Exception {
/**
* @var string
*/
protected $path;
public function __construct(string $path = "", int $code = 0, ?\Throwable $previous = null) {
$class = get_class($this);
$parts = explode('\\', $class);
$baseName = array_pop($parts);
parent::__construct('Invalid request for ' . $path . ' (' . $baseName . ')', $code, $previous);
$this->path = $path;
}
/**
* @return string
*/
public function getPath() {
return $this->path;
}
}
@@ -0,0 +1,10 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Exception;
class InvalidResourceException extends Exception {
}
+13
View File
@@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2022 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace Icewind\SMB\Exception;
class InvalidTicket extends Exception {
}
@@ -0,0 +1,10 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Exception;
class InvalidTypeException extends InvalidRequestException {
}
@@ -0,0 +1,10 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Exception;
class NoLoginServerException extends ConnectException {
}
@@ -0,0 +1,10 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Exception;
class NoRouteToHostException extends ConnectException {
}
@@ -0,0 +1,10 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Exception;
class NotEmptyException extends InvalidRequestException {
}
@@ -0,0 +1,10 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Exception;
class NotFoundException extends InvalidRequestException {
}
@@ -0,0 +1,10 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Exception;
class OutOfSpaceException extends InvalidRequestException {
}
@@ -0,0 +1,15 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Exception;
use Throwable;
class RevisionMismatchException extends Exception {
public function __construct(string $message = 'Protocol version mismatch', int $code = 0, Throwable $previous = null) {
parent::__construct($message, $code, $previous);
}
}
@@ -0,0 +1,10 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Exception;
class TimedOutException extends ConnectException {
}
+29
View File
@@ -0,0 +1,29 @@
<?php
/**
* SPDX-FileCopyrightText: 2018 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace Icewind\SMB;
interface IAuth {
public function getUsername(): ?string;
public function getWorkgroup(): ?string;
public function getPassword(): ?string;
/**
* Any extra command line option for smbclient that are required
*
* @return string
*/
public function getExtraCommandLineArguments(): string;
/**
* Set any extra options for libsmbclient that are required
*
* @param resource $smbClientState
*/
public function setExtraSmbClientOptions($smbClientState): void;
}
+45
View File
@@ -0,0 +1,45 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB;
interface IFileInfo {
/*
* Mappings of the DOS mode bits, as returned by smbc_getxattr() when the
* attribute name "system.dos_attr.mode" (or "system.dos_attr.*" or
* "system.*") is specified.
*/
const MODE_READONLY = 0x01;
const MODE_HIDDEN = 0x02;
const MODE_SYSTEM = 0x04;
const MODE_VOLUME_ID = 0x08;
const MODE_DIRECTORY = 0x10;
const MODE_ARCHIVE = 0x20;
const MODE_NORMAL = 0x80;
public function getPath(): string;
public function getName(): string;
public function getSize(): int;
public function getMTime(): int;
public function isDirectory(): bool;
public function isReadOnly(): bool;
public function isHidden(): bool;
public function isSystem(): bool;
public function isArchived(): bool;
/**
* @return ACL[]
*/
public function getAcls(): array;
}
+43
View File
@@ -0,0 +1,43 @@
<?php
/**
* SPDX-FileCopyrightText: 2016 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB;
interface INotifyHandler {
// https://msdn.microsoft.com/en-us/library/dn392331.aspx
const NOTIFY_ADDED = 1;
const NOTIFY_REMOVED = 2;
const NOTIFY_MODIFIED = 3;
const NOTIFY_RENAMED_OLD = 4;
const NOTIFY_RENAMED_NEW = 5;
const NOTIFY_ADDED_STREAM = 6;
const NOTIFY_REMOVED_STREAM = 7;
const NOTIFY_MODIFIED_STREAM = 8;
const NOTIFY_REMOVED_BY_DELETE = 9;
/**
* Get all changes detected since the start of the notify process or the last call to getChanges
*
* @return Change[]
*/
public function getChanges(): array;
/**
* Listen actively to all incoming changes
*
* Note that this is a blocking process and will cause the process to block forever if not explicitly terminated
*
* @param callable(Change):?bool $callback
*/
public function listen(callable $callback): void;
/**
* Stop listening for changes
*
* Note that any pending changes will be discarded
*/
public function stop(): void;
}
+26
View File
@@ -0,0 +1,26 @@
<?php
/**
* SPDX-FileCopyrightText: 2018 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace Icewind\SMB;
interface IOptions {
const PROTOCOL_NT1 = 'NT1';
const PROTOCOL_SMB2 = 'SMB2';
const PROTOCOL_SMB2_02 = 'SMB2_02';
const PROTOCOL_SMB2_22 = 'SMB2_22';
const PROTOCOL_SMB2_24 = 'SMB2_24';
const PROTOCOL_SMB3 = 'SMB3';
const PROTOCOL_SMB3_00 = 'SMB3_00';
const PROTOCOL_SMB3_02 = 'SMB3_02';
const PROTOCOL_SMB3_10 = 'SMB3_10';
const PROTOCOL_SMB3_11 = 'SMB3_11';
public function getTimeout(): int;
public function getMinProtocol(): ?string;
public function getMaxProtocol(): ?string;
}
+31
View File
@@ -0,0 +1,31 @@
<?php
/**
* SPDX-FileCopyrightText: 2018 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace Icewind\SMB;
interface IServer {
public function getAuth(): IAuth;
public function getHost(): string;
/**
* @return \Icewind\SMB\IShare[]
*
* @throws \Icewind\SMB\Exception\AuthenticationException
* @throws \Icewind\SMB\Exception\InvalidHostException
*/
public function listShares(): array;
public function getShare(string $name): IShare;
public function getTimeZone(): string;
public function getSystem(): ISystem;
public function getOptions(): IOptions;
public static function available(ISystem $system): bool;
}
+164
View File
@@ -0,0 +1,164 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB;
use Icewind\SMB\Exception\AlreadyExistsException;
use Icewind\SMB\Exception\InvalidRequestException;
use Icewind\SMB\Exception\InvalidTypeException;
use Icewind\SMB\Exception\NotFoundException;
interface IShare {
/**
* Get the name of the share
*
* @return string
*/
public function getName(): string;
/**
* Download a remote file
*
* @param string $source remote file
* @param string $target local file
* @return bool
*
* @throws NotFoundException
* @throws InvalidTypeException
*/
public function get(string $source, string $target): bool;
/**
* Upload a local file
*
* @param string $source local file
* @param string $target remote file
* @return bool
*
* @throws NotFoundException
* @throws InvalidTypeException
*/
public function put(string $source, string $target): bool;
/**
* Open a readable stream to a remote file
*
* @param string $source
* @return resource a read only stream with the contents of the remote file
*
* @throws NotFoundException
* @throws InvalidTypeException
*/
public function read(string $source);
/**
* Open a writable stream to a remote file
* Note: This method will truncate the file to 0bytes
*
* @param string $target
* @return resource a write only stream to upload a remote file
*
* @throws NotFoundException
* @throws InvalidTypeException
*/
public function write(string $target);
/**
* Open a writable stream to a remote file and set the cursor to the end of the file
*
* @param string $target
* @return resource a write only stream to upload a remote file
*
* @throws NotFoundException
* @throws InvalidTypeException
* @throws InvalidRequestException
*/
public function append(string $target);
/**
* Rename a remote file
*
* @param string $from
* @param string $to
* @return bool
*
* @throws NotFoundException
* @throws AlreadyExistsException
*/
public function rename(string $from, string $to): bool;
/**
* Delete a file on the share
*
* @param string $path
* @return bool
*
* @throws NotFoundException
* @throws InvalidTypeException
*/
public function del(string $path): bool;
/**
* List the content of a remote folder
*
* @param string $path
* @return IFileInfo[]
*
* @throws NotFoundException
* @throws InvalidTypeException
*/
public function dir(string $path): array;
/**
* @param string $path
* @return IFileInfo
*
* @throws NotFoundException
*/
public function stat(string $path): IFileInfo;
/**
* Create a folder on the share
*
* @param string $path
* @return bool
*
* @throws NotFoundException
* @throws AlreadyExistsException
*/
public function mkdir(string $path): bool;
/**
* Remove a folder on the share
*
* @param string $path
* @return bool
*
* @throws NotFoundException
* @throws InvalidTypeException
*/
public function rmdir(string $path): bool;
/**
* @param string $path
* @param int $mode a combination of FileInfo::MODE_READONLY, FileInfo::MODE_ARCHIVE, FileInfo::MODE_SYSTEM and FileInfo::MODE_HIDDEN, FileInfo::NORMAL
* @return mixed
*/
public function setMode(string $path, int $mode);
/**
* @param string $path
* @return INotifyHandler
*/
public function notify(string $path);
/**
* Get the IServer instance for this share
*
* @return IServer
*/
public function getServer(): IServer;
}
+63
View File
@@ -0,0 +1,63 @@
<?php
/**
* SPDX-FileCopyrightText: 2018 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace Icewind\SMB;
/**
* The `ISystem` interface provides a way to access system dependent information
* such as the availability and location of certain binaries.
*/
interface ISystem {
/**
* Get the path to a file descriptor of the current process
*
* @param int $num the file descriptor id
* @return string
*/
public function getFD(int $num): string;
/**
* Get the full path to the `smbclient` binary of null if the binary is not available
*
* @return string|null
*/
public function getSmbclientPath(): ?string;
/**
* Get the full path to the `net` binary of null if the binary is not available
*
* @return string|null
*/
public function getNetPath(): ?string;
/**
* Get the full path to the `smbcacls` binary of null if the binary is not available
*
* @return string|null
*/
public function getSmbcAclsPath(): ?string;
/**
* Get the full path to the `stdbuf` binary of null if the binary is not available
*
* @return string|null
*/
public function getStdBufPath(): ?string;
/**
* Get the full path to the `date` binary of null if the binary is not available
*
* @return string|null
*/
public function getDatePath(): ?string;
/**
* Whether or not the smbclient php extension is enabled
*
* @return bool
*/
public function libSmbclientAvailable(): bool;
}
+17
View File
@@ -0,0 +1,17 @@
<?php
/**
* SPDX-FileCopyrightText: 2018 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace Icewind\SMB;
interface ITimeZoneProvider {
/**
* Get the timezone of the smb server
*
* @param string $host
* @return string
*/
public function get(string $host): string;
}
+47
View File
@@ -0,0 +1,47 @@
<?php
/**
* SPDX-FileCopyrightText: 2018 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace Icewind\SMB;
use Icewind\SMB\Exception\DependencyException;
use Icewind\SMB\Exception\Exception;
use Icewind\SMB\Exception\InvalidTicket;
/**
* Use existing kerberos ticket to authenticate and reuse the apache ticket cache (mod_auth_kerb)
*
* @deprecated Use `KerberosAuth` with `$auth->setTicket(KerberosTicket::fromEnv())` instead
*/
class KerberosApacheAuth extends KerberosAuth implements IAuth {
public function getTicket(): KerberosTicket {
if ($this->ticket === null) {
$ticket = KerberosTicket::fromEnv();
if ($ticket === null) {
throw new InvalidTicket("No ticket found in environment");
}
$this->ticket = $ticket;
}
return $this->ticket;
}
/**
* Copy the ticket to a temporary location and use that ticket for authentication
*
* @return void
*/
public function copyTicket(): void {
$this->ticket = KerberosTicket::load($this->getTicket()->save());
}
/**
* Check if a valid kerberos ticket is present
*
* @return bool
*/
public function checkTicket(): bool {
return $this->getTicket()->isValid();
}
}
+64
View File
@@ -0,0 +1,64 @@
<?php
/**
* SPDX-FileCopyrightText: 2018 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace Icewind\SMB;
use Icewind\SMB\Exception\Exception;
/**
* Use existing kerberos ticket to authenticate
*/
class KerberosAuth implements IAuth {
/** @var ?KerberosTicket */
protected $ticket = null;
public function getTicket(): ?KerberosTicket {
return $this->ticket;
}
public function setTicket(?KerberosTicket $ticket): void {
$this->ticket = $ticket;
}
public function getUsername(): ?string {
return 'dummy';
}
public function getWorkgroup(): ?string {
return 'dummy';
}
public function getPassword(): ?string {
return null;
}
private function setEnv():void {
$ticket = $this->getTicket();
if ($ticket) {
$ticket->validate();
// note that even if the ticket name is the value we got from `getenv("KRB5CCNAME")` we still need to set the env variable ourselves
// this is because `getenv` also reads the variables passed from the SAPI (apache-php) and we need to set the variable in the OS's env
putenv("KRB5CCNAME=" . $ticket->getCacheName());
}
}
public function getExtraCommandLineArguments(): string {
$this->setEnv();
return '-k';
}
public function setExtraSmbClientOptions($smbClientState): void {
$this->setEnv();
$success = (bool)smbclient_option_set($smbClientState, SMBCLIENT_OPT_USE_KERBEROS, true);
$success = $success && smbclient_option_set($smbClientState, SMBCLIENT_OPT_FALLBACK_AFTER_KERBEROS, false);
if (!$success) {
throw new Exception("Failed to set smbclient options for kerberos auth");
}
}
}
+85
View File
@@ -0,0 +1,85 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2022 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace Icewind\SMB;
use Icewind\SMB\Exception\InvalidTicket;
use KRB5CCache;
class KerberosTicket {
/** @var KRB5CCache */
private $krb5;
/** @var string */
private $cacheName;
public function __construct(KRB5CCache $krb5, string $cacheName) {
$this->krb5 = $krb5;
$this->cacheName = $cacheName;
}
public function getCacheName(): string {
return $this->cacheName;
}
public function getName(): string{
return $this->krb5->getName();
}
public function isValid(): bool {
return count($this->krb5->getEntries()) > 0;
}
public function validate(): void {
if (!$this->isValid()) {
throw new InvalidTicket("No kerberos ticket found.");
}
}
/**
* Load the ticket from the cache specified by the KRB5CCNAME variable.
*
* @return KerberosTicket|null
*/
public static function fromEnv(): ?KerberosTicket {
$ticketName = getenv("KRB5CCNAME");
if (!$ticketName) {
return null;
}
$krb5 = new KRB5CCache();
$krb5->open($ticketName);
return new KerberosTicket($krb5, $ticketName);
}
public static function load(string $ticket): KerberosTicket {
$tmpFilename = tempnam(sys_get_temp_dir(), "krb5cc_php_");
file_put_contents($tmpFilename, $ticket);
register_shutdown_function(function () use ($tmpFilename) {
if (file_exists($tmpFilename)) {
unlink($tmpFilename);
}
});
$ticketName = "FILE:" . $tmpFilename;
$krb5 = new KRB5CCache();
$krb5->open($ticketName);
return new KerberosTicket($krb5, $ticketName);
}
public function save(): string {
if (substr($this->cacheName, 0, 5) === 'FILE:') {
$ticket = file_get_contents(substr($this->cacheName, 5));
} else {
$tmpFilename = tempnam(sys_get_temp_dir(), "krb5cc_php_");
$tmpCacheFile = "FILE:" . $tmpFilename;
$this->krb5->save($tmpCacheFile);
$ticket = file_get_contents($tmpFilename);
unlink($tmpFilename);
}
return $ticket;
}
}
+142
View File
@@ -0,0 +1,142 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Native;
use Icewind\SMB\ACL;
use Icewind\SMB\Exception\Exception;
use Icewind\SMB\Exception\NotFoundException;
use Icewind\SMB\IFileInfo;
class NativeFileInfo implements IFileInfo {
/** @var string */
protected $path;
/** @var string */
protected $name;
/** @var NativeShare */
protected $share;
/** @var array{"mode": int, "size": int, "mtime": int}|null */
protected $statCache = null;
public function __construct(NativeShare $share, string $path, string $name) {
$this->share = $share;
$this->path = $path;
$this->name = $name;
}
public function getPath(): string {
return $this->path;
}
public function getName(): string {
return $this->name;
}
/**
* @return array{"mode": int, "size": int, "mtime": int}
*/
protected function stat(): array {
if (is_null($this->statCache)) {
$this->statCache = $this->share->rawStat($this->path);
}
return $this->statCache;
}
public function getSize(): int {
$stat = $this->stat();
return $stat['size'];
}
public function getMTime(): int {
$stat = $this->stat();
return $stat['mtime'];
}
/**
* On "mode":
*
* different smbclient versions seem to return different mode values for 'system.dos_attr.mode'
*
* older versions return the dos permissions mask as defined in `IFileInfo::MODE_*` while
* newer versions return the equivalent unix permission mask.
*
* Since the unix mask doesn't contain the proper hidden/archive/system flags we have to assume them
* as false (except for `hidden` where we use the unix dotfile convention)
*/
protected function getMode(): int {
$mode = $this->stat()['mode'];
// Let us ignore the ATTR_NOT_CONTENT_INDEXED for now
$mode &= ~0x00002000;
return $mode;
}
public function isDirectory(): bool {
$mode = $this->getMode();
if ($mode > 0x1000) {
return ($mode & 0x4000 && !($mode & 0x8000)); // 0x4000: unix directory flag shares bits with 0xC000: socket
} else {
return (bool)($mode & IFileInfo::MODE_DIRECTORY);
}
}
public function isReadOnly(): bool {
$mode = $this->getMode();
if ($mode > 0x1000) {
return !(bool)($mode & 0x80); // 0x80: owner write permissions
} else {
return (bool)($mode & IFileInfo::MODE_READONLY);
}
}
public function isHidden(): bool {
$mode = $this->getMode();
if ($mode > 0x1000) {
return strlen($this->name) > 0 && $this->name[0] === '.';
} else {
return (bool)($mode & IFileInfo::MODE_HIDDEN);
}
}
public function isSystem(): bool {
$mode = $this->getMode();
if ($mode > 0x1000) {
return false;
} else {
return (bool)($mode & IFileInfo::MODE_SYSTEM);
}
}
public function isArchived(): bool {
$mode = $this->getMode();
if ($mode > 0x1000) {
return false;
} else {
return (bool)($mode & IFileInfo::MODE_ARCHIVE);
}
}
/**
* @return ACL[]
*/
public function getAcls(): array {
$acls = [];
$attribute = $this->share->getAttribute($this->path, 'system.nt_sec_desc.acl.*+');
foreach (explode(',', $attribute) as $acl) {
list($user, $permissions) = explode(':', $acl, 2);
$user = trim($user, '\\');
list($type, $flags, $mask) = explode('/', $permissions);
$mask = hexdec($mask);
$acls[$user] = new ACL((int)$type, (int)$flags, (int)$mask);
}
return $acls;
}
}
+92
View File
@@ -0,0 +1,92 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Native;
use Icewind\SMB\StringBuffer;
/**
* Stream optimized for read only usage
*/
class NativeReadStream extends NativeStream {
const CHUNK_SIZE = 1048576; // 1MB chunks
/** @var StringBuffer */
private $readBuffer;
public function __construct() {
$this->readBuffer = new StringBuffer();
}
/** @var int */
private $pos = 0;
public function stream_open($path, $mode, $options, &$opened_path) {
return parent::stream_open($path, $mode, $options, $opened_path);
}
/**
* Wrap a stream from libsmbclient-php into a regular php stream
*
* @param NativeState $state
* @param resource $smbStream
* @param string $mode
* @param string $url
* @return resource
*/
public static function wrap(NativeState $state, $smbStream, string $mode, string $url) {
return parent::wrapClass($state, $smbStream, $mode, $url, NativeReadStream::class);
}
public function stream_read($count) {
// php reads 8192 bytes at once
// however due to network latency etc, it's faster to read in larger chunks
// and buffer the result
if (!parent::stream_eof() && $this->readBuffer->remaining() < $count) {
$chunk = parent::stream_read(self::CHUNK_SIZE);
if ($chunk === false) {
return false;
}
$this->readBuffer->push($chunk);
}
$result = $this->readBuffer->read($count);
$read = strlen($result);
$this->pos += $read;
return $result;
}
public function stream_seek($offset, $whence = SEEK_SET) {
$result = parent::stream_seek($offset, $whence);
if ($result) {
$this->readBuffer->clear();
$pos = parent::stream_tell();
if ($pos === false) {
return false;
}
$this->pos = $pos;
}
return $result;
}
public function stream_eof() {
return $this->readBuffer->remaining() <= 0 && parent::stream_eof();
}
public function stream_tell() {
return $this->pos;
}
public function stream_write($data) {
return false;
}
public function stream_truncate($size) {
return false;
}
}
+64
View File
@@ -0,0 +1,64 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Native;
use Icewind\SMB\AbstractServer;
use Icewind\SMB\Exception\AuthenticationException;
use Icewind\SMB\Exception\InvalidHostException;
use Icewind\SMB\IAuth;
use Icewind\SMB\IOptions;
use Icewind\SMB\IShare;
use Icewind\SMB\ISystem;
use Icewind\SMB\ITimeZoneProvider;
class NativeServer extends AbstractServer {
/**
* @var NativeState
*/
protected $state;
public function __construct(string $host, IAuth $auth, ISystem $system, ITimeZoneProvider $timeZoneProvider, IOptions $options) {
parent::__construct($host, $auth, $system, $timeZoneProvider, $options);
$this->state = new NativeState();
}
protected function connect(): void {
$this->state->init($this->getAuth(), $this->getOptions());
}
/**
* @return IShare[]
* @throws AuthenticationException
* @throws InvalidHostException
*/
public function listShares(): array {
$this->connect();
$shares = [];
$dh = $this->state->opendir('smb://' . $this->getHost());
while ($share = $this->state->readdir($dh, '')) {
if ($share['type'] === 'file share') {
$shares[] = $this->getShare($share['name']);
}
}
$this->state->closedir($dh, '');
return $shares;
}
public function getShare(string $name): IShare {
return new NativeShare($this, $name);
}
/**
* Check if the smbclient php extension is available
*
* @param ISystem $system
* @return bool
*/
public static function available(ISystem $system): bool {
return $system->libSmbclientAvailable();
}
}
+369
View File
@@ -0,0 +1,369 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Native;
use Icewind\SMB\AbstractShare;
use Icewind\SMB\Exception\AlreadyExistsException;
use Icewind\SMB\Exception\AuthenticationException;
use Icewind\SMB\Exception\ConnectionException;
use Icewind\SMB\Exception\DependencyException;
use Icewind\SMB\Exception\InvalidHostException;
use Icewind\SMB\Exception\InvalidPathException;
use Icewind\SMB\Exception\InvalidResourceException;
use Icewind\SMB\Exception\InvalidTypeException;
use Icewind\SMB\Exception\NotFoundException;
use Icewind\SMB\IFileInfo;
use Icewind\SMB\INotifyHandler;
use Icewind\SMB\IServer;
use Icewind\SMB\Wrapped\Server;
use Icewind\SMB\Wrapped\Share;
class NativeShare extends AbstractShare {
/**
* @var IServer $server
*/
private $server;
/**
* @var string $name
*/
private $name;
/** @var NativeState|null $state */
private $state = null;
public function __construct(IServer $server, string $name) {
parent::__construct();
$this->server = $server;
$this->name = $name;
}
/**
* @throws ConnectionException
* @throws AuthenticationException
* @throws InvalidHostException
*/
protected function getState(): NativeState {
if ($this->state) {
return $this->state;
}
$this->state = new NativeState();
$this->state->init($this->server->getAuth(), $this->server->getOptions());
return $this->state;
}
/**
* Get the name of the share
*
* @return string
*/
public function getName(): string {
return $this->name;
}
private function buildUrl(string $path): string {
$this->verifyPath($path);
$url = sprintf('smb://%s/%s', $this->server->getHost(), $this->name);
if ($path) {
$path = trim($path, '/');
$url .= '/';
$url .= implode('/', array_map('rawurlencode', explode('/', $path)));
}
return $url;
}
/**
* List the content of a remote folder
*
* @param string $path
* @return IFileInfo[]
*
* @throws NotFoundException
* @throws InvalidTypeException
*/
public function dir(string $path): array {
$files = [];
$dh = $this->getState()->opendir($this->buildUrl($path));
while ($file = $this->getState()->readdir($dh, $path)) {
$name = $file['name'];
if ($name !== '.' and $name !== '..') {
$fullPath = $path . '/' . $name;
$files [] = new NativeFileInfo($this, $fullPath, $name);
}
}
$this->getState()->closedir($dh, $path);
return $files;
}
/**
* @param string $path
* @return IFileInfo
*/
public function stat(string $path): IFileInfo {
$info = new NativeFileInfo($this, $path, self::mb_basename($path));
// trigger attribute loading
$info->getSize();
return $info;
}
/**
* @return array{"mode": int, "size": int, "mtime": int}
*/
public function rawStat(string $path): array {
return $this->getState()->stat($this->buildUrl($path));
}
/**
* Multibyte unicode safe version of basename()
*
* @param string $path
* @link http://php.net/manual/en/function.basename.php#121405
* @return string
*/
protected static function mb_basename(string $path): string {
if (preg_match('@^.*[\\\\/]([^\\\\/]+)$@s', $path, $matches)) {
return $matches[1];
} elseif (preg_match('@^([^\\\\/]+)$@s', $path, $matches)) {
return $matches[1];
}
return '';
}
/**
* Create a folder on the share
*
* @param string $path
* @return bool
*
* @throws NotFoundException
* @throws AlreadyExistsException
*/
public function mkdir(string $path): bool {
return $this->getState()->mkdir($this->buildUrl($path));
}
/**
* Remove a folder on the share
*
* @param string $path
* @return bool
*
* @throws NotFoundException
* @throws InvalidTypeException
*/
public function rmdir(string $path): bool {
return $this->getState()->rmdir($this->buildUrl($path));
}
/**
* Delete a file on the share
*
* @param string $path
* @return bool
*
* @throws NotFoundException
* @throws InvalidTypeException
*/
public function del(string $path): bool {
return $this->getState()->unlink($this->buildUrl($path));
}
/**
* Rename a remote file
*
* @param string $from
* @param string $to
* @return bool
*
* @throws NotFoundException
* @throws AlreadyExistsException
*/
public function rename(string $from, string $to): bool {
return $this->getState()->rename($this->buildUrl($from), $this->buildUrl($to));
}
/**
* Upload a local file
*
* @param string $source local file
* @param string $target remove file
* @return bool
*
* @throws NotFoundException
* @throws InvalidTypeException
*/
public function put(string $source, string $target): bool {
$sourceHandle = fopen($source, 'rb');
$targetUrl = $this->buildUrl($target);
$targetHandle = $this->getState()->create($targetUrl);
while ($data = fread($sourceHandle, NativeReadStream::CHUNK_SIZE)) {
$this->getState()->write($targetHandle, $data, $targetUrl);
}
$this->getState()->close($targetHandle, $targetUrl);
return true;
}
/**
* Download a remote file
*
* @param string $source remove file
* @param string $target local file
* @return bool
*
* @throws AuthenticationException
* @throws ConnectionException
* @throws InvalidHostException
* @throws InvalidPathException
* @throws InvalidResourceException
*/
public function get(string $source, string $target): bool {
if (!$target) {
throw new InvalidPathException('Invalid target path: Filename cannot be empty');
}
$sourceHandle = $this->getState()->open($this->buildUrl($source), 'r');
$targetHandle = @fopen($target, 'wb');
if (!$targetHandle) {
$error = error_get_last();
if (is_array($error)) {
$reason = $error['message'];
} else {
$reason = 'Unknown error';
}
$this->getState()->close($sourceHandle, $this->buildUrl($source));
throw new InvalidResourceException('Failed opening local file "' . $target . '" for writing: ' . $reason);
}
while ($data = $this->getState()->read($sourceHandle, NativeReadStream::CHUNK_SIZE, $source)) {
fwrite($targetHandle, $data);
}
$this->getState()->close($sourceHandle, $this->buildUrl($source));
return true;
}
/**
* Open a readable stream to a remote file
*
* @param string $source
* @return resource a read only stream with the contents of the remote file
*
* @throws NotFoundException
* @throws InvalidTypeException
*/
public function read(string $source) {
$url = $this->buildUrl($source);
$handle = $this->getState()->open($url, 'r');
return NativeReadStream::wrap($this->getState(), $handle, 'r', $url);
}
/**
* Open a writeable stream to a remote file
* Note: This method will truncate the file to 0bytes first
*
* @param string $target
* @return resource a writeable stream
*
* @throws NotFoundException
* @throws InvalidTypeException
*/
public function write(string $target) {
$url = $this->buildUrl($target);
$handle = $this->getState()->create($url);
return NativeWriteStream::wrap($this->getState(), $handle, 'w', $url);
}
/**
* Open a writeable stream and set the cursor to the end of the stream
*
* @param string $target
* @return resource a writeable stream
*
* @throws NotFoundException
* @throws InvalidTypeException
*/
public function append(string $target) {
$url = $this->buildUrl($target);
$handle = $this->getState()->open($url, "a+");
return NativeWriteStream::wrap($this->getState(), $handle, "a", $url);
}
/**
* Get extended attributes for the path
*
* @param string $path
* @param string $attribute attribute to get the info
* @return string the attribute value
*/
public function getAttribute(string $path, string $attribute): string {
return $this->getState()->getxattr($this->buildUrl($path), $attribute);
}
/**
* Set extended attributes for the given path
*
* @param string $path
* @param string $attribute attribute to get the info
* @param string|int $value
* @return mixed the attribute value
*/
public function setAttribute(string $path, string $attribute, $value) {
if (is_int($value)) {
if ($attribute === 'system.dos_attr.mode') {
$value = '0x' . dechex($value);
} else {
throw new \InvalidArgumentException("Invalid value for attribute");
}
}
return $this->getState()->setxattr($this->buildUrl($path), $attribute, $value);
}
/**
* Set DOS comaptible node mode
*
* @param string $path
* @param int $mode a combination of FileInfo::MODE_READONLY, FileInfo::MODE_ARCHIVE, FileInfo::MODE_SYSTEM and FileInfo::MODE_HIDDEN, FileInfo::NORMAL
* @return mixed
*/
public function setMode(string $path, int $mode) {
return $this->setAttribute($path, 'system.dos_attr.mode', $mode);
}
/**
* Start smb notify listener
* Note: This is a blocking call
*
* @param string $path
* @return INotifyHandler
*/
public function notify(string $path): INotifyHandler {
// php-smbclient does not support notify (https://github.com/eduardok/libsmbclient-php/issues/29)
// so we use the smbclient based backend for this
if (!Server::available($this->server->getSystem())) {
throw new DependencyException('smbclient not found in path for notify command');
}
$share = new Share($this->server, $this->getName(), $this->server->getSystem());
return $share->notify($path);
}
public function getServer(): IServer {
return $this->server;
}
public function __destruct() {
unset($this->state);
}
}
+433
View File
@@ -0,0 +1,433 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Native;
use Icewind\SMB\Exception\AlreadyExistsException;
use Icewind\SMB\Exception\ConnectionException;
use Icewind\SMB\Exception\ConnectionRefusedException;
use Icewind\SMB\Exception\ConnectionResetException;
use Icewind\SMB\Exception\Exception;
use Icewind\SMB\Exception\FileInUseException;
use Icewind\SMB\Exception\ForbiddenException;
use Icewind\SMB\Exception\HostDownException;
use Icewind\SMB\Exception\InvalidArgumentException;
use Icewind\SMB\Exception\InvalidTypeException;
use Icewind\SMB\Exception\ConnectionAbortedException;
use Icewind\SMB\Exception\NoRouteToHostException;
use Icewind\SMB\Exception\NotEmptyException;
use Icewind\SMB\Exception\NotFoundException;
use Icewind\SMB\Exception\OutOfSpaceException;
use Icewind\SMB\Exception\TimedOutException;
use Icewind\SMB\IAuth;
use Icewind\SMB\IOptions;
/**
* Low level wrapper for libsmbclient-php with error handling
*/
class NativeState {
/** @var resource|null */
protected $state = null;
/** @var bool */
protected $connected = false;
/**
* sync the garbage collection cycle
* __deconstruct() of KerberosAuth should not called too soon
*
* @var IAuth|null $auth
*/
protected $auth = null;
// see error.h
const EXCEPTION_MAP = [
1 => ForbiddenException::class,
2 => NotFoundException::class,
13 => ForbiddenException::class,
16 => FileInUseException::class,
17 => AlreadyExistsException::class,
20 => InvalidTypeException::class,
21 => InvalidTypeException::class,
22 => InvalidArgumentException::class,
28 => OutOfSpaceException::class,
39 => NotEmptyException::class,
103 => ConnectionAbortedException::class,
104 => ConnectionResetException::class,
110 => TimedOutException::class,
111 => ConnectionRefusedException::class,
112 => HostDownException::class,
113 => NoRouteToHostException::class
];
protected function handleError(?string $path): void {
if (!$this->state) {
return;
}
$error = smbclient_state_errno($this->state);
if ($error === 0) {
return;
}
throw Exception::fromMap(self::EXCEPTION_MAP, $error, $path);
}
/**
* @param mixed $result
* @param string|null $uri
* @throws Exception
*/
protected function testResult($result, ?string $uri): void {
if ($result === false or $result === null) {
// smb://host/share/path
if (is_string($uri) && count(explode('/', $uri, 5)) > 4) {
list(, , , , $path) = explode('/', $uri, 5);
$path = '/' . $path;
} else {
$path = $uri;
}
$this->handleError($path);
}
}
/**
* @param IAuth $auth
* @param IOptions $options
* @return bool
*/
public function init(IAuth $auth, IOptions $options) {
if ($this->connected) {
return true;
}
/** @var resource $state */
$state = smbclient_state_new();
$this->state = $state;
/** @psalm-suppress UnusedFunctionCall */
smbclient_option_set($this->state, SMBCLIENT_OPT_AUTO_ANONYMOUS_LOGIN, false);
/** @psalm-suppress UnusedFunctionCall */
smbclient_option_set($this->state, SMBCLIENT_OPT_TIMEOUT, $options->getTimeout() * 1000);
if (function_exists('smbclient_client_protocols')) {
smbclient_client_protocols($this->state, $options->getMinProtocol(), $options->getMaxProtocol());
}
$auth->setExtraSmbClientOptions($this->state);
// sync the garbage collection cycle
// __deconstruct() of KerberosAuth should not caled too soon
$this->auth = $auth;
$result = @smbclient_state_init($this->state, $auth->getWorkgroup(), $auth->getUsername(), $auth->getPassword());
$this->testResult($result, '');
$this->connected = true;
return $result;
}
/**
* @param string $uri
* @return resource
*/
public function opendir(string $uri) {
if (!$this->state) {
throw new ConnectionException("Not connected");
}
/** @var resource $result */
$result = @smbclient_opendir($this->state, $uri);
$this->testResult($result, $uri);
return $result;
}
/**
* @param resource $dir
* @param string $path
* @return array{"type": string, "comment": string, "name": string}|false
*/
public function readdir($dir, string $path) {
if (!$this->state) {
throw new ConnectionException("Not connected");
}
/** @var array{"type": string, "comment": string, "name": string}|false $result */
$result = @smbclient_readdir($this->state, $dir);
$this->testResult($result, $path);
return $result;
}
/**
* @param resource $dir
* @param string $path
* @return bool
*/
public function closedir($dir, string $path): bool {
if (!$this->state) {
throw new ConnectionException("Not connected");
}
$result = @smbclient_closedir($this->state, $dir);
$this->testResult($result, $path);
return $result;
}
/**
* @param string $old
* @param string $new
* @return bool
*/
public function rename(string $old, string $new): bool {
if (!$this->state) {
throw new ConnectionException("Not connected");
}
$result = @smbclient_rename($this->state, $old, $this->state, $new);
$this->testResult($result, $new);
return $result;
}
/**
* @param string $uri
* @return bool
*/
public function unlink(string $uri): bool {
if (!$this->state) {
throw new ConnectionException("Not connected");
}
$result = @smbclient_unlink($this->state, $uri);
$this->testResult($result, $uri);
return $result;
}
/**
* @param string $uri
* @param int $mask
* @return bool
*/
public function mkdir(string $uri, int $mask = 0777): bool {
if (!$this->state) {
throw new ConnectionException("Not connected");
}
$result = @smbclient_mkdir($this->state, $uri, $mask);
$this->testResult($result, $uri);
return $result;
}
/**
* @param string $uri
* @return bool
*/
public function rmdir(string $uri): bool {
if (!$this->state) {
throw new ConnectionException("Not connected");
}
$result = @smbclient_rmdir($this->state, $uri);
$this->testResult($result, $uri);
return $result;
}
/**
* @param string $uri
* @return array{"mtime": int, "size": int, "mode": int}
*/
public function stat(string $uri): array {
if (!$this->state) {
throw new ConnectionException("Not connected");
}
/** @var array{"mtime": int, "size": int, "mode": int} $result */
$result = @smbclient_stat($this->state, $uri);
$this->testResult($result, $uri);
return $result;
}
/**
* @param resource $file
* @param string $path
* @return array{"mtime": int, "size": int, "mode": int}
*/
public function fstat($file, string $path): array {
if (!$this->state) {
throw new ConnectionException("Not connected");
}
/** @var array{"mtime": int, "size": int, "mode": int} $result */
$result = @smbclient_fstat($this->state, $file);
$this->testResult($result, $path);
return $result;
}
/**
* @param string $uri
* @param string $mode
* @param int $mask
* @return resource
*/
public function open(string $uri, string $mode, int $mask = 0666) {
if (!$this->state) {
throw new ConnectionException("Not connected");
}
/** @var resource $result */
$result = @smbclient_open($this->state, $uri, $mode, $mask);
$this->testResult($result, $uri);
return $result;
}
/**
* @param string $uri
* @param int $mask
* @return resource
*/
public function create(string $uri, int $mask = 0666) {
if (!$this->state) {
throw new ConnectionException("Not connected");
}
/** @var resource $result */
$result = @smbclient_creat($this->state, $uri, $mask);
$this->testResult($result, $uri);
return $result;
}
/**
* @param resource $file
* @param int $bytes
* @param string $path
* @return string
*/
public function read($file, int $bytes, string $path): string {
if (!$this->state) {
throw new ConnectionException("Not connected");
}
/** @var string $result */
$result = @smbclient_read($this->state, $file, $bytes);
$this->testResult($result, $path);
return $result;
}
/**
* @param resource $file
* @param string $data
* @param string $path
* @param int|null $length
* @return int
*/
public function write($file, string $data, string $path, ?int $length = null): int {
if (!$this->state) {
throw new ConnectionException("Not connected");
}
if ($length) {
$result = @smbclient_write($this->state, $file, $data, $length);
} else {
$result = @smbclient_write($this->state, $file, $data);
}
$this->testResult($result, $path);
if ($result === false) {
return 0;
}
return $result;
}
/**
* @param resource $file
* @param int $offset
* @param int $whence SEEK_SET | SEEK_CUR | SEEK_END
* @param string|null $path
*
* @return false|int new file offset as measured from the start of the file on success.
*/
public function lseek($file, int $offset, int $whence = SEEK_SET, string $path = null) {
if (!$this->state) {
throw new ConnectionException("Not connected");
}
// psalm doesn't think int|false == int|false for some reason, so we do a needless annotation to help it out
/**
* @psalm-suppress UnnecessaryVarAnnotation
* @var int|false $result
*/
$result = @smbclient_lseek($this->state, $file, $offset, $whence);
$this->testResult($result, $path);
return $result;
}
/**
* @param resource $file
* @param int $size
* @param string $path
* @return bool
*/
public function ftruncate($file, int $size, string $path): bool {
if (!$this->state) {
throw new ConnectionException("Not connected");
}
$result = @smbclient_ftruncate($this->state, $file, $size);
$this->testResult($result, $path);
return $result;
}
/**
* @param resource $file
* @param string $path
* @return bool
*/
public function close($file, string $path): bool {
if (!$this->state) {
return false;
}
$result = @smbclient_close($this->state, $file);
$this->testResult($result, $path);
return $result;
}
/**
* @param string $uri
* @param string $key
* @return string
*/
public function getxattr(string $uri, string $key) {
if (!$this->state) {
throw new ConnectionException("Not connected");
}
/** @var string $result */
$result = @smbclient_getxattr($this->state, $uri, $key);
$this->testResult($result, $uri);
return $result;
}
/**
* @param string $uri
* @param string $key
* @param string $value
* @param int $flags
* @return bool
*/
public function setxattr(string $uri, string $key, string $value, int $flags = 0) {
if (!$this->state) {
throw new ConnectionException("Not connected");
}
/** @var bool $result */
$result = @smbclient_setxattr($this->state, $uri, $key, $value, $flags);
$this->testResult($result, $uri);
return $result;
}
public function __destruct() {
if ($this->connected && $this->state) {
if (smbclient_state_free($this->state) === false) {
throw new Exception("Failed to free smb state");
}
}
}
}
+158
View File
@@ -0,0 +1,158 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Native;
use Icewind\SMB\Exception\Exception;
use Icewind\SMB\Exception\InvalidRequestException;
use Icewind\Streams\File;
use InvalidArgumentException;
abstract class NativeStream implements File {
/**
* @var resource
* @psalm-suppress PropertyNotSetInConstructor
*/
public $context;
/**
* @var NativeState
* @psalm-suppress PropertyNotSetInConstructor
*/
protected $state;
/**
* @var resource
* @psalm-suppress PropertyNotSetInConstructor
*/
protected $handle;
/**
* @var bool
*/
protected $eof = false;
/**
* @var string
*/
protected $url = '';
/**
* Wrap a stream from libsmbclient-php into a regular php stream
*
* @param NativeState $state
* @param resource $smbStream
* @param string $mode
* @param string $url
* @param class-string<NativeStream> $class
* @return resource
*/
protected static function wrapClass(NativeState $state, $smbStream, string $mode, string $url, string $class) {
if (stream_wrapper_register('nativesmb', $class) === false) {
throw new Exception("Failed to register stream wrapper");
}
$context = stream_context_create([
'nativesmb' => [
'state' => $state,
'handle' => $smbStream,
'url' => $url
]
]);
$fh = fopen('nativesmb://', $mode, false, $context);
if (stream_wrapper_unregister('nativesmb') === false) {
throw new Exception("Failed to unregister stream wrapper");
}
return $fh;
}
public function stream_close() {
try {
return $this->state->close($this->handle, $this->url);
} catch (\Exception $e) {
return false;
}
}
public function stream_eof() {
return $this->eof;
}
public function stream_flush() {
return false;
}
public function stream_open($path, $mode, $options, &$opened_path) {
$context = stream_context_get_options($this->context);
if (!isset($context['nativesmb']) || !is_array($context['nativesmb'])) {
throw new InvalidArgumentException("context not set");
}
$state = $context['nativesmb']['state'];
if (!$state instanceof NativeState) {
throw new InvalidArgumentException("invalid context set");
}
$this->state = $state;
$handle = $context['nativesmb']['handle'];
if (!is_resource($handle)) {
throw new InvalidArgumentException("invalid context set");
}
$this->handle = $handle;
$url = $context['nativesmb']['url'];
if (!is_string($url)) {
throw new InvalidArgumentException("invalid context set");
}
$this->url = $url;
return true;
}
public function stream_read($count) {
$result = $this->state->read($this->handle, $count, $this->url);
if (strlen($result) < $count) {
$this->eof = true;
}
return $result;
}
public function stream_seek($offset, $whence = SEEK_SET) {
$this->eof = false;
try {
return $this->state->lseek($this->handle, $offset, $whence, $this->url) !== false;
} catch (InvalidRequestException $e) {
return false;
}
}
/**
* @return array{"mtime": int, "size": int, "mode": int}|false
*/
public function stream_stat() {
try {
return $this->state->fstat($this->handle, $this->url);
} catch (Exception $e) {
return false;
}
}
public function stream_tell() {
return $this->state->lseek($this->handle, 0, SEEK_CUR, $this->url);
}
public function stream_write($data) {
return $this->state->write($this->handle, $data, $this->url);
}
public function stream_truncate($size) {
return $this->state->ftruncate($this->handle, $size, $this->url);
}
public function stream_set_option($option, $arg1, $arg2) {
return false;
}
public function stream_lock($operation) {
return false;
}
}
+95
View File
@@ -0,0 +1,95 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Native;
use Icewind\SMB\StringBuffer;
/**
* Stream optimized for write only usage
*/
class NativeWriteStream extends NativeStream {
const CHUNK_SIZE = 1048576; // 1MB chunks
/** @var StringBuffer */
private $writeBuffer;
/** @var int */
private $pos = 0;
public function __construct() {
$this->writeBuffer = new StringBuffer();
}
public function stream_open($path, $mode, $options, &$opened_path): bool {
return parent::stream_open($path, $mode, $options, $opened_path);
}
/**
* Wrap a stream from libsmbclient-php into a regular php stream
*
* @param NativeState $state
* @param resource $smbStream
* @param string $mode
* @param string $url
* @return resource
*/
public static function wrap(NativeState $state, $smbStream, string $mode, string $url) {
return parent::wrapClass($state, $smbStream, $mode, $url, NativeWriteStream::class);
}
public function stream_seek($offset, $whence = SEEK_SET) {
$this->flushWrite();
$result = parent::stream_seek($offset, $whence);
if ($result) {
$pos = parent::stream_tell();
if ($pos === false) {
return false;
}
$this->pos = $pos;
}
return $result;
}
private function flushWrite(): void {
parent::stream_write($this->writeBuffer->flush());
}
public function stream_write($data) {
$written = $this->writeBuffer->push($data);
$this->pos += $written;
if ($this->writeBuffer->remaining() >= self::CHUNK_SIZE) {
$this->flushWrite();
}
return $written;
}
public function stream_close() {
try {
$this->flushWrite();
$flushResult = true;
} catch (\Exception $e) {
$flushResult = false;
}
return parent::stream_close() && $flushResult;
}
public function stream_tell() {
return $this->pos;
}
public function stream_read($count) {
return false;
}
public function stream_truncate($size) {
$this->flushWrite();
$this->pos = $size;
return parent::stream_truncate($size);
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
/**
* SPDX-FileCopyrightText: 2018 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace Icewind\SMB;
class Options implements IOptions {
/** @var int */
private $timeout = 20;
/** @var string|null */
private $minProtocol;
/** @var string|null */
private $maxProtocol;
public function getTimeout(): int {
return $this->timeout;
}
public function setTimeout(int $timeout): void {
$this->timeout = $timeout;
}
public function getMinProtocol(): ?string {
return $this->minProtocol;
}
public function setMinProtocol(?string $minProtocol): void {
$this->minProtocol = $minProtocol;
}
public function getMaxProtocol(): ?string {
return $this->maxProtocol;
}
public function setMaxProtocol(?string $maxProtocol): void {
$this->maxProtocol = $maxProtocol;
}
}
+70
View File
@@ -0,0 +1,70 @@
<?php
/**
* SPDX-FileCopyrightText: 2018 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace Icewind\SMB;
use Icewind\SMB\Exception\DependencyException;
use Icewind\SMB\Native\NativeServer;
use Icewind\SMB\Wrapped\Server;
class ServerFactory {
const BACKENDS = [
NativeServer::class,
Server::class
];
/** @var ISystem */
private $system;
/** @var IOptions */
private $options;
/** @var ITimeZoneProvider */
private $timeZoneProvider;
/**
* ServerFactory constructor.
*
* @param IOptions|null $options
* @param ISystem|null $system
* @param ITimeZoneProvider|null $timeZoneProvider
*/
public function __construct(
?IOptions $options = null,
?ISystem $system = null,
?ITimeZoneProvider $timeZoneProvider = null
) {
if (is_null($options)) {
$options = new Options();
}
if (is_null($system)) {
$system = new System();
}
if (is_null($timeZoneProvider)) {
$timeZoneProvider = new TimeZoneProvider($system);
}
$this->options = $options;
$this->system = $system;
$this->timeZoneProvider = $timeZoneProvider;
}
/**
* @param string $host
* @param IAuth $credentials
* @return IServer
* @throws DependencyException
*/
public function createServer(string $host, IAuth $credentials): IServer {
foreach (self::BACKENDS as $backend) {
if (call_user_func("$backend::available", $this->system)) {
return new $backend($host, $credentials, $this->system, $this->timeZoneProvider, $this->options);
}
}
throw new DependencyException('No valid backend available, ensure smbclient is in the path or php-smbclient is installed');
}
}
+48
View File
@@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2021 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace Icewind\SMB;
class StringBuffer {
/** @var string */
private $buffer = "";
/** @var int */
private $pos = 0;
public function clear(): void {
$this->buffer = "";
$this->pos = 0;
}
public function push(string $data): int {
$this->buffer = $this->flush() . $data;
return strlen($data);
}
public function remaining(): int {
return strlen($this->buffer) - $this->pos;
}
public function read(int $count): string {
$chunk = substr($this->buffer, $this->pos, $count);
$this->pos += strlen($chunk);
return $chunk;
}
public function flush(): string {
if ($this->pos === 0) {
$remaining = $this->buffer;
} else {
$remaining = substr($this->buffer, $this->pos);
}
$this->clear();
return $remaining;
}
}
+75
View File
@@ -0,0 +1,75 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB;
use Icewind\SMB\Exception\Exception;
class System implements ISystem {
/** @var (string|null)[] */
private $paths = [];
/**
* Get the path to a file descriptor of the current process
*
* @param int $num the file descriptor id
* @return string
* @throws Exception
*/
public function getFD(int $num): string {
$folders = [
'/proc/self/fd',
'/dev/fd'
];
foreach ($folders as $folder) {
if (file_exists($folder)) {
return $folder . '/' . $num;
}
}
throw new Exception('Cant find file descriptor path');
}
public function getSmbclientPath(): ?string {
return $this->getBinaryPath('smbclient');
}
public function getNetPath(): ?string {
return $this->getBinaryPath('net');
}
public function getSmbcAclsPath(): ?string {
return $this->getBinaryPath('smbcacls');
}
public function getStdBufPath(): ?string {
return $this->getBinaryPath('stdbuf');
}
public function getDatePath(): ?string {
return $this->getBinaryPath('date');
}
public function libSmbclientAvailable(): bool {
return function_exists('smbclient_state_new');
}
protected function getBinaryPath(string $binary): ?string {
if (!isset($this->paths[$binary])) {
$result = null;
$output = [];
exec("which $binary 2>&1", $output, $result);
if ($result === 0 && isset($output[0])) {
$this->paths[$binary] = (string)$output[0];
} elseif (is_executable("/usr/bin/$binary")) {
$this->paths[$binary] = "/usr/bin/$binary";
} else {
$this->paths[$binary] = null;
}
}
return $this->paths[$binary];
}
}
+52
View File
@@ -0,0 +1,52 @@
<?php
/**
* SPDX-FileCopyrightText: 2015 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB;
class TimeZoneProvider implements ITimeZoneProvider {
/**
* @var string[]
*/
private $timeZones = [];
/**
* @var ISystem
*/
private $system;
/**
* @param ISystem $system
*/
public function __construct(ISystem $system) {
$this->system = $system;
}
public function get(string $host): string {
if (!isset($this->timeZones[$host])) {
$timeZone = null;
$net = $this->system->getNetPath();
// for local domain names we can assume same timezone
if ($net && $host && strpos($host, '.') !== false) {
$command = sprintf(
'%s time zone -S %s',
$net,
escapeshellarg($host)
);
$timeZone = exec($command);
}
if (!$timeZone) {
$date = $this->system->getDatePath();
if ($date) {
$timeZone = exec($date . " +%z");
} else {
$timeZone = date_default_timezone_get();
}
}
$this->timeZones[$host] = $timeZone;
}
return $this->timeZones[$host];
}
}
+115
View File
@@ -0,0 +1,115 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Wrapped;
use Icewind\SMB\Exception\AccessDeniedException;
use Icewind\SMB\Exception\AuthenticationException;
use Icewind\SMB\Exception\ConnectException;
use Icewind\SMB\Exception\ConnectionException;
use Icewind\SMB\Exception\ConnectionRefusedException;
use Icewind\SMB\Exception\InvalidHostException;
use Icewind\SMB\Exception\NoLoginServerException;
class Connection extends RawConnection {
const DELIMITER = 'smb:';
const DELIMITER_LENGTH = 4;
/** @var Parser */
private $parser;
/**
* @param string $command
* @param Parser $parser
* @param array<string, string> $env
*/
public function __construct(string $command, Parser $parser, array $env = []) {
parent::__construct($command, $env);
$this->parser = $parser;
}
/**
* send input to smbclient
*
* @param string $input
*/
public function write(string $input) {
return parent::write($input . PHP_EOL);
}
/**
* @throws ConnectException
*/
public function clearTillPrompt(): void {
$this->write('');
do {
$promptLine = $this->readTillPrompt();
if ($promptLine === false) {
break;
}
$this->parser->checkConnectionError($promptLine);
} while (!$this->isPrompt($promptLine));
if ($this->write('') === false) {
throw new ConnectionRefusedException();
}
$this->readTillPrompt();
}
/**
* get all unprocessed output from smbclient until the next prompt
*
* @return string[]
* @throws AuthenticationException
* @throws ConnectException
* @throws ConnectionException
* @throws InvalidHostException
* @throws NoLoginServerException
* @throws AccessDeniedException
*/
public function read(): array {
if (!$this->isValid()) {
throw new ConnectionException('Connection not valid');
}
$output = $this->readTillPrompt();
if ($output === false) {
$this->unknownError(false);
}
$output = explode("\n", $output);
// last line contains the prompt
array_pop($output);
return $output;
}
private function isPrompt(string $line): bool {
return substr($line, 0, self::DELIMITER_LENGTH) === self::DELIMITER;
}
/**
* @param string|bool $promptLine (optional) prompt line that might contain some info about the error
* @throws ConnectException
* @return no-return
*/
private function unknownError($promptLine = '') {
if ($promptLine) { //maybe we have some error we missed on the previous line
throw new ConnectException('Unknown error (' . $promptLine . ')');
} else {
$error = $this->readError(); // maybe something on stderr
if ($error) {
throw new ConnectException('Unknown error (stderr: ' . $error . ')');
} else {
throw new ConnectException('Unknown error');
}
}
}
public function close(bool $terminate = true): void {
if (get_resource_type($this->getInputStream()) === 'stream') {
// ignore any errors while trying to send the close command, the process might already be dead
@$this->write('close' . PHP_EOL);
}
$this->close_process($terminate);
}
}
+30
View File
@@ -0,0 +1,30 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Wrapped;
class ErrorCodes {
/**
* connection errors
*/
const LogonFailure = 'NT_STATUS_LOGON_FAILURE';
const BadHostName = 'NT_STATUS_BAD_NETWORK_NAME';
const Unsuccessful = 'NT_STATUS_UNSUCCESSFUL';
const ConnectionRefused = 'NT_STATUS_CONNECTION_REFUSED';
const NoLogonServers = 'NT_STATUS_NO_LOGON_SERVERS';
const PathNotFound = 'NT_STATUS_OBJECT_PATH_NOT_FOUND';
const NoSuchFile = 'NT_STATUS_NO_SUCH_FILE';
const ObjectNotFound = 'NT_STATUS_OBJECT_NAME_NOT_FOUND';
const NameCollision = 'NT_STATUS_OBJECT_NAME_COLLISION';
const AccessDenied = 'NT_STATUS_ACCESS_DENIED';
const DirectoryNotEmpty = 'NT_STATUS_DIRECTORY_NOT_EMPTY';
const FileIsADirectory = 'NT_STATUS_FILE_IS_A_DIRECTORY';
const NotADirectory = 'NT_STATUS_NOT_A_DIRECTORY';
const SharingViolation = 'NT_STATUS_SHARING_VIOLATION';
const InvalidParameter = 'NT_STATUS_INVALID_PARAMETER';
const RevisionMismatch = 'NT_STATUS_REVISION_MISMATCH';
}
+88
View File
@@ -0,0 +1,88 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Wrapped;
use Icewind\SMB\ACL;
use Icewind\SMB\IFileInfo;
class FileInfo implements IFileInfo {
/** @var string */
protected $path;
/** @var string */
protected $name;
/** @var int */
protected $size;
/** @var int */
protected $time;
/** @var int */
protected $mode;
/** @var callable(): ACL[] */
protected $aclCallback;
/**
* @param string $path
* @param string $name
* @param int $size
* @param int $time
* @param int $mode
* @param callable(): ACL[] $aclCallback
*/
public function __construct(string $path, string $name, int $size, int $time, int $mode, callable $aclCallback) {
$this->path = $path;
$this->name = $name;
$this->size = $size;
$this->time = $time;
$this->mode = $mode;
$this->aclCallback = $aclCallback;
}
/**
* @return string
*/
public function getPath(): string {
return $this->path;
}
public function getName(): string {
return $this->name;
}
public function getSize(): int {
return $this->size;
}
public function getMTime(): int {
return $this->time;
}
public function isDirectory(): bool {
return (bool)($this->mode & IFileInfo::MODE_DIRECTORY);
}
public function isReadOnly(): bool {
return (bool)($this->mode & IFileInfo::MODE_READONLY);
}
public function isHidden(): bool {
return (bool)($this->mode & IFileInfo::MODE_HIDDEN);
}
public function isSystem(): bool {
return (bool)($this->mode & IFileInfo::MODE_SYSTEM);
}
public function isArchived(): bool {
return (bool)($this->mode & IFileInfo::MODE_ARCHIVE);
}
/**
* @return ACL[]
*/
public function getAcls(): array {
return ($this->aclCallback)();
}
}
+111
View File
@@ -0,0 +1,111 @@
<?php
/**
* SPDX-FileCopyrightText: 2016 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Wrapped;
use Icewind\SMB\Change;
use Icewind\SMB\Exception\Exception;
use Icewind\SMB\Exception\RevisionMismatchException;
use Icewind\SMB\INotifyHandler;
class NotifyHandler implements INotifyHandler {
/** @var Connection */
private $connection;
/** @var string */
private $path;
/** @var bool */
private $listening = true;
// see error.h
const EXCEPTION_MAP = [
ErrorCodes::RevisionMismatch => RevisionMismatchException::class,
];
/**
* @param Connection $connection
* @param string $path
*/
public function __construct(Connection $connection, string $path) {
$this->connection = $connection;
$this->path = $path;
}
/**
* Get all changes detected since the start of the notify process or the last call to getChanges
*
* @return Change[]
*/
public function getChanges(): array {
if (!$this->listening) {
return [];
}
stream_set_blocking($this->connection->getOutputStream(), false);
$lines = [];
while (($line = $this->connection->readLine())) {
$this->checkForError($line);
$lines[] = $line;
}
stream_set_blocking($this->connection->getOutputStream(), true);
return array_values(array_filter(array_map([$this, 'parseChangeLine'], $lines)));
}
/**
* Listen actively to all incoming changes
*
* Note that this is a blocking process and will cause the process to block forever if not explicitly terminated
*
* @param callable(Change):?bool $callback
*/
public function listen(callable $callback): void {
if ($this->listening) {
while (true) {
$line = $this->connection->readLine();
if ($line === false) {
break;
}
$this->checkForError($line);
$change = $this->parseChangeLine($line);
if ($change) {
$result = $callback($change);
if ($result === false) {
break;
}
}
};
}
}
private function parseChangeLine(string $line): ?Change {
$code = (int)substr($line, 0, 4);
if ($code === 0) {
return null;
}
$subPath = str_replace('\\', '/', substr($line, 5));
if ($this->path === '') {
return new Change($code, $subPath);
} else {
return new Change($code, $this->path . '/' . $subPath);
}
}
private function checkForError(string $line): void {
if (substr($line, 0, 16) === 'notify returned ') {
$error = substr($line, 16);
throw Exception::fromMap(array_merge(self::EXCEPTION_MAP, Parser::EXCEPTION_MAP), $error, 'Notify is not supported with the used smb version');
}
}
public function stop(): void {
$this->listening = false;
$this->connection->close();
}
public function __destruct() {
$this->stop();
}
}
+276
View File
@@ -0,0 +1,276 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Wrapped;
use Icewind\SMB\ACL;
use Icewind\SMB\Exception\AccessDeniedException;
use Icewind\SMB\Exception\AlreadyExistsException;
use Icewind\SMB\Exception\AuthenticationException;
use Icewind\SMB\Exception\Exception;
use Icewind\SMB\Exception\FileInUseException;
use Icewind\SMB\Exception\InvalidHostException;
use Icewind\SMB\Exception\InvalidParameterException;
use Icewind\SMB\Exception\InvalidResourceException;
use Icewind\SMB\Exception\InvalidTypeException;
use Icewind\SMB\Exception\NoLoginServerException;
use Icewind\SMB\Exception\NotEmptyException;
use Icewind\SMB\Exception\NotFoundException;
class Parser {
const MSG_NOT_FOUND = 'Error opening local file ';
/**
* @var string
*/
protected $timeZone;
// see error.h
const EXCEPTION_MAP = [
ErrorCodes::LogonFailure => AuthenticationException::class,
ErrorCodes::PathNotFound => NotFoundException::class,
ErrorCodes::ObjectNotFound => NotFoundException::class,
ErrorCodes::NoSuchFile => NotFoundException::class,
ErrorCodes::NameCollision => AlreadyExistsException::class,
ErrorCodes::AccessDenied => AccessDeniedException::class,
ErrorCodes::DirectoryNotEmpty => NotEmptyException::class,
ErrorCodes::FileIsADirectory => InvalidTypeException::class,
ErrorCodes::NotADirectory => InvalidTypeException::class,
ErrorCodes::SharingViolation => FileInUseException::class,
ErrorCodes::InvalidParameter => InvalidParameterException::class
];
const MODE_STRINGS = [
'R' => FileInfo::MODE_READONLY,
'H' => FileInfo::MODE_HIDDEN,
'S' => FileInfo::MODE_SYSTEM,
'D' => FileInfo::MODE_DIRECTORY,
'A' => FileInfo::MODE_ARCHIVE,
'N' => FileInfo::MODE_NORMAL
];
/**
* @param string $timeZone
*/
public function __construct(string $timeZone) {
$this->timeZone = $timeZone;
}
private function getErrorCode(string $line): ?string {
$parts = explode(' ', $line);
foreach ($parts as $part) {
if (substr($part, 0, 9) === 'NT_STATUS') {
return $part;
}
}
return null;
}
/**
* @param string[] $output
* @param string $path
* @return no-return
* @throws Exception
* @throws InvalidResourceException
* @throws NotFoundException
*/
public function checkForError(array $output, string $path): void {
if (strpos($output[0], 'does not exist')) {
throw new NotFoundException($path);
}
$error = $this->getErrorCode($output[0]);
if (substr($output[0], 0, strlen(self::MSG_NOT_FOUND)) === self::MSG_NOT_FOUND) {
$localPath = substr($output[0], strlen(self::MSG_NOT_FOUND));
throw new InvalidResourceException('Failed opening local file "' . $localPath . '" for writing');
}
throw Exception::fromMap(self::EXCEPTION_MAP, $error, $path);
}
/**
* check if the first line holds a connection failure
*
* @param string $line
* @throws AuthenticationException
* @throws InvalidHostException
* @throws NoLoginServerException
* @throws AccessDeniedException
*/
public function checkConnectionError(string $line): void {
$line = rtrim($line, ')');
if (substr($line, -23) === ErrorCodes::LogonFailure) {
throw new AuthenticationException('Invalid login');
}
if (substr($line, -26) === ErrorCodes::BadHostName) {
throw new InvalidHostException('Invalid hostname');
}
if (substr($line, -22) === ErrorCodes::Unsuccessful) {
throw new InvalidHostException('Connection unsuccessful');
}
if (substr($line, -28) === ErrorCodes::ConnectionRefused) {
throw new InvalidHostException('Connection refused');
}
if (substr($line, -26) === ErrorCodes::NoLogonServers) {
throw new NoLoginServerException('No login server');
}
if (substr($line, -23) === ErrorCodes::AccessDenied) {
throw new AccessDeniedException('Access denied');
}
}
public function parseMode(string $mode): int {
$result = 0;
foreach (self::MODE_STRINGS as $char => $val) {
if (strpos($mode, $char) !== false) {
$result |= $val;
}
}
return $result;
}
/**
* @param string[] $output
* @return array{"mtime": int, "mode": int, "size": int}
* @throws Exception
*/
public function parseStat(array $output): array {
$data = [];
foreach ($output as $line) {
// A line = explode statement may not fill all array elements
// properly. May happen when accessing non Windows Fileservers
$words = explode(':', $line, 2);
$name = isset($words[0]) ? $words[0] : '';
$value = isset($words[1]) ? $words[1] : '';
$value = trim($value);
if (!isset($data[$name])) {
$data[$name] = $value;
}
}
$attributeStart = strpos($data['attributes'], '(');
if ($attributeStart === false) {
throw new Exception("Malformed state response from server");
}
return [
'mtime' => strtotime($data['write_time']),
'mode' => hexdec(substr($data['attributes'], $attributeStart + 1, -1)),
'size' => isset($data['stream']) ? (int)(explode(' ', $data['stream'])[1]) : 0
];
}
/**
* @param string[] $output
* @param string $basePath
* @param callable(string):ACL[] $aclCallback
* @return FileInfo[]
*/
public function parseDir(array $output, string $basePath, callable $aclCallback): array {
//last line is used space
array_pop($output);
$regex = '/^\s*(.*?)\s\s\s\s+(?:([NDHARSCndharsc]*)\s+)?([0-9]+)\s+(.*)$/';
//2 spaces, filename, optional type, size, date
$content = [];
foreach ($output as $line) {
if (preg_match($regex, $line, $matches)) {
list(, $name, $mode, $size, $time) = $matches;
if ($name !== '.' and $name !== '..') {
$mode = $this->parseMode(strtoupper($mode));
$time = strtotime($time . ' ' . $this->timeZone);
$path = $basePath . '/' . $name;
$content[] = new FileInfo($path, $name, (int)$size, $time, $mode, function () use ($aclCallback, $path): array {
return $aclCallback($path);
});
}
}
}
return $content;
}
/**
* @param string[] $output
* @return array<string, string>
*/
public function parseListShares(array $output): array {
$shareNames = [];
foreach ($output as $line) {
if (strpos($line, '|')) {
list($type, $name, $description) = explode('|', $line);
if (strtolower($type) === 'disk') {
$shareNames[$name] = $description;
}
} elseif (strpos($line, 'Disk')) {
// new output format
list($name, $description) = explode('Disk', $line);
$shareNames[trim($name)] = trim($description);
}
}
return $shareNames;
}
/**
* @param string[] $rawAcls
* @return ACL[]
*/
public function parseACLs(array $rawAcls): array {
$acls = [];
foreach ($rawAcls as $acl) {
if (strpos($acl, ':') === false) {
continue;
}
[$type, $acl] = explode(':', $acl, 2);
if ($type !== 'ACL') {
continue;
}
[$user, $permissions] = explode(':', $acl, 2);
[$type, $flags, $mask] = explode('/', $permissions);
$type = $type === 'ALLOWED' ? ACL::TYPE_ALLOW : ACL::TYPE_DENY;
$flagsInt = 0;
foreach (explode('|', $flags) as $flagString) {
if ($flagString === 'OI') {
$flagsInt += ACL::FLAG_OBJECT_INHERIT;
} elseif ($flagString === 'CI') {
$flagsInt += ACL::FLAG_CONTAINER_INHERIT;
}
}
if (substr($mask, 0, 2) === '0x') {
$maskInt = hexdec($mask);
} else {
$maskInt = 0;
foreach (explode('|', $mask) as $maskString) {
if ($maskString === 'R') {
$maskInt += ACL::MASK_READ;
} elseif ($maskString === 'W') {
$maskInt += ACL::MASK_WRITE;
} elseif ($maskString === 'X') {
$maskInt += ACL::MASK_EXECUTE;
} elseif ($maskString === 'D') {
$maskInt += ACL::MASK_DELETE;
} elseif ($maskString === 'READ') {
$maskInt += ACL::MASK_READ + ACL::MASK_EXECUTE;
} elseif ($maskString === 'CHANGE') {
$maskInt += ACL::MASK_READ + ACL::MASK_EXECUTE + ACL::MASK_WRITE + ACL::MASK_DELETE;
} elseif ($maskString === 'FULL') {
$maskInt += ACL::MASK_READ + ACL::MASK_EXECUTE + ACL::MASK_WRITE + ACL::MASK_DELETE;
}
}
}
if (isset($acls[$user])) {
$existing = $acls[$user];
$maskInt += $existing->getMask();
}
$acls[$user] = new ACL($type, $flagsInt, $maskInt);
}
ksort($acls);
return $acls;
}
}
+250
View File
@@ -0,0 +1,250 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Wrapped;
use Icewind\SMB\Exception\ConnectException;
use Icewind\SMB\Exception\ConnectionException;
class RawConnection {
/**
* @var string
*/
private $command;
/**
* @var string[]
*/
private $env;
/**
* @var resource[] $pipes
*
* $pipes[0] holds STDIN for smbclient
* $pipes[1] holds STDOUT for smbclient
* $pipes[3] holds the authfile for smbclient
* $pipes[4] holds the stream for writing files
* $pipes[5] holds the stream for reading files
*/
private $pipes = [];
/**
* @var resource|null $process
*/
private $process;
/**
* @var resource|null $authStream
*/
private $authStream = null;
/**
* @param string $command
* @param array<string, string> $env
*/
public function __construct(string $command, array $env = []) {
$this->command = $command;
$this->env = $env;
}
/**
* @throws ConnectException
* @psalm-assert resource $this->process
*/
public function connect(): void {
if (is_null($this->getAuthStream())) {
throw new ConnectException('Authentication not set before connecting');
}
$descriptorSpec = [
0 => ['pipe', 'r'], // child reads from stdin
1 => ['pipe', 'w'], // child writes to stdout
2 => ['pipe', 'w'], // child writes to stderr
3 => $this->getAuthStream(), // child reads from fd#3
4 => ['pipe', 'r'], // child reads from fd#4
5 => ['pipe', 'w'] // child writes to fd#5
];
setlocale(LC_ALL, Server::LOCALE);
$env = array_merge($this->env, [
'CLI_FORCE_INTERACTIVE' => 'y', // Make sure the prompt is displayed
'CLI_NO_READLINE' => 1, // Not all distros build smbclient with readline, disable it to get consistent behaviour
'LC_ALL' => Server::LOCALE,
'LANG' => Server::LOCALE,
'COLUMNS' => 8192, // prevent smbclient from line-wrapping it's output
'TZ' => 'UTC',
]);
$this->process = proc_open($this->command, $descriptorSpec, $this->pipes, '/', $env);
if (!$this->isValid()) {
throw new ConnectionException();
}
}
/**
* check if the connection is still active
*
* @return bool
* @psalm-assert-if-true resource $this->process
*/
public function isValid(): bool {
if (is_resource($this->process)) {
$status = proc_get_status($this->process);
return $status['running'];
} else {
return false;
}
}
/**
* send input to the process
*
* @param string $input
* @return int|bool
*/
public function write(string $input) {
$result = @fwrite($this->getInputStream(), $input);
fflush($this->getInputStream());
return $result;
}
/**
* read output till the next prompt
*
* @return string|false
*/
public function readTillPrompt() {
$output = "";
do {
$chunk = $this->readLine('\> ');
if ($chunk === false) {
return false;
}
$output .= $chunk;
} while (strlen($chunk) == 4096 && strpos($chunk, "smb:") === false);
return $output;
}
/**
* read a line of output
*
* @return string|false
*/
public function readLine(string $end = "\n") {
return stream_get_line($this->getOutputStream(), 4096, $end);
}
/**
* read a line of output
*
* @return string|false
*/
public function readError() {
$line = stream_get_line($this->getErrorStream(), 4086);
return $line !== false ? trim($line) : false;
}
/**
* get all output until the process closes
*
* @return string[]
*/
public function readAll(): array {
$output = [];
while ($line = $this->readLine()) {
$output[] = $line;
}
return $output;
}
/**
* @return resource
*/
public function getInputStream() {
return $this->pipes[0];
}
/**
* @return resource
*/
public function getOutputStream() {
return $this->pipes[1];
}
/**
* @return resource
*/
public function getErrorStream() {
return $this->pipes[2];
}
/**
* @return resource|null
*/
public function getAuthStream() {
return $this->authStream;
}
/**
* @return resource
*/
public function getFileInputStream() {
return $this->pipes[4];
}
/**
* @return resource
*/
public function getFileOutputStream() {
return $this->pipes[5];
}
/**
* @param string|null $user
* @param string|null $password
* @psalm-assert resource $this->authStream
*/
public function writeAuthentication(?string $user, ?string $password): void {
$auth = ($password === null)
? "username=$user"
: "username=$user\npassword=$password\n";
$this->authStream = fopen('php://temp', 'w+');
fwrite($this->authStream, $auth);
rewind($this->authStream);
}
/**
* @param bool $terminate
* @psalm-assert null $this->process
*/
public function close(bool $terminate = true): void {
$this->close_process($terminate);
}
/**
* @param bool $terminate
* @psalm-assert null $this->process
*/
protected function close_process(bool $terminate = true): void {
if (!is_resource($this->process)) {
return;
}
if ($terminate) {
proc_terminate($this->process);
}
proc_close($this->process);
$this->process = null;
}
public function reconnect(): void {
$this->close();
$this->connect();
}
public function __destruct() {
$this->close();
}
}
+103
View File
@@ -0,0 +1,103 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Wrapped;
use Icewind\SMB\AbstractServer;
use Icewind\SMB\Exception\AuthenticationException;
use Icewind\SMB\Exception\ConnectException;
use Icewind\SMB\Exception\ConnectionException;
use Icewind\SMB\Exception\ConnectionRefusedException;
use Icewind\SMB\Exception\Exception;
use Icewind\SMB\Exception\InvalidHostException;
use Icewind\SMB\IShare;
use Icewind\SMB\ISystem;
class Server extends AbstractServer {
/**
* Check if the smbclient php extension is available
*
* @param ISystem $system
* @return bool
*/
public static function available(ISystem $system): bool {
return $system->getSmbclientPath() !== null;
}
private function getAuthFileArgument(): string {
if ($this->getAuth()->getUsername()) {
return '--authentication-file=' . $this->system->getFD(3);
} else {
return '';
}
}
/**
* @return IShare[]
*
* @throws AuthenticationException
* @throws InvalidHostException
* @throws ConnectException
*/
public function listShares(): array {
$maxProtocol = $this->options->getMaxProtocol();
$minProtocol = $this->options->getMinProtocol();
$smbClient = $this->system->getSmbclientPath();
if ($smbClient === null) {
throw new Exception("Backend not available");
}
$command = sprintf(
'%s %s %s %s %s -L %s',
$smbClient,
$this->getAuthFileArgument(),
$this->getAuth()->getExtraCommandLineArguments(),
$maxProtocol ? "--option='client max protocol=" . $maxProtocol . "'" : "",
$minProtocol ? "--option='client min protocol=" . $minProtocol . "'" : "",
escapeshellarg('//' . $this->getHost())
);
$connection = new RawConnection($command);
$connection->writeAuthentication($this->getAuth()->getUsername(), $this->getAuth()->getPassword());
$connection->connect();
if (!$connection->isValid()) {
throw new ConnectionException((string)$connection->readLine());
}
$parser = new Parser('UTC');
$output = $connection->readAll();
if (isset($output[0])) {
$parser->checkConnectionError($output[0]);
}
// sometimes we get an empty line first
if (count($output) < 2) {
$output = $connection->readAll();
}
if (isset($output[0])) {
$parser->checkConnectionError($output[0]);
}
if (count($output) === 0) {
throw new ConnectionRefusedException();
}
$shareNames = $parser->parseListShares($output);
$shares = [];
foreach ($shareNames as $name => $_description) {
$shares[] = $this->getShare($name);
}
return $shares;
}
/**
* @param string $name
* @return IShare
*/
public function getShare(string $name): IShare {
return new Share($this, $name, $this->system);
}
}
+553
View File
@@ -0,0 +1,553 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\SMB\Wrapped;
use Icewind\SMB\AbstractShare;
use Icewind\SMB\ACL;
use Icewind\SMB\Exception\AlreadyExistsException;
use Icewind\SMB\Exception\AuthenticationException;
use Icewind\SMB\Exception\ConnectException;
use Icewind\SMB\Exception\ConnectionException;
use Icewind\SMB\Exception\DependencyException;
use Icewind\SMB\Exception\Exception;
use Icewind\SMB\Exception\FileInUseException;
use Icewind\SMB\Exception\InvalidHostException;
use Icewind\SMB\Exception\InvalidTypeException;
use Icewind\SMB\Exception\NotFoundException;
use Icewind\SMB\Exception\InvalidRequestException;
use Icewind\SMB\IFileInfo;
use Icewind\SMB\INotifyHandler;
use Icewind\SMB\IServer;
use Icewind\SMB\ISystem;
use Icewind\Streams\CallbackWrapper;
use Icewind\SMB\Native\NativeShare;
use Icewind\SMB\Native\NativeServer;
class Share extends AbstractShare {
/**
* @var IServer $server
*/
private $server;
/**
* @var string $name
*/
private $name;
/**
* @var Connection|null $connection
*/
public $connection = null;
/**
* @var Parser
*/
protected $parser;
/**
* @var ISystem
*/
private $system;
const MODE_MAP = [
FileInfo::MODE_READONLY => 'r',
FileInfo::MODE_HIDDEN => 'h',
FileInfo::MODE_ARCHIVE => 'a',
FileInfo::MODE_SYSTEM => 's'
];
const EXEC_CMD = 'exec';
/**
* @param IServer $server
* @param string $name
* @param ISystem $system
*/
public function __construct(IServer $server, string $name, ISystem $system) {
parent::__construct();
$this->server = $server;
$this->name = $name;
$this->system = $system;
$this->parser = new Parser('UTC');
}
private function getAuthFileArgument(): string {
if ($this->server->getAuth()->getUsername()) {
return '--authentication-file=' . $this->system->getFD(3);
} else {
return '';
}
}
protected function getConnection(): Connection {
$maxProtocol = $this->server->getOptions()->getMaxProtocol();
$minProtocol = $this->server->getOptions()->getMinProtocol();
$smbClient = $this->system->getSmbclientPath();
$stdBuf = $this->system->getStdBufPath();
if ($smbClient === null) {
throw new Exception("Backend not available");
}
$command = sprintf(
'%s %s%s -t %s %s %s %s %s %s',
self::EXEC_CMD,
$stdBuf ? $stdBuf . ' -o0 ' : '',
$smbClient,
$this->server->getOptions()->getTimeout(),
$this->getAuthFileArgument(),
$this->server->getAuth()->getExtraCommandLineArguments(),
$maxProtocol ? "--option='client max protocol=" . $maxProtocol . "'" : "",
$minProtocol ? "--option='client min protocol=" . $minProtocol . "'" : "",
escapeshellarg('//' . $this->server->getHost() . '/' . $this->name)
);
$connection = new Connection($command, $this->parser);
$connection->writeAuthentication($this->server->getAuth()->getUsername(), $this->server->getAuth()->getPassword());
$connection->connect();
if (!$connection->isValid()) {
throw new ConnectionException((string)$connection->readLine());
}
// some versions of smbclient add a help message in first of the first prompt
$connection->clearTillPrompt();
return $connection;
}
/**
* @throws ConnectionException
* @throws AuthenticationException
* @throws InvalidHostException
* @psalm-assert Connection $this->connection
*/
protected function connect(): Connection {
if ($this->connection and $this->connection->isValid()) {
return $this->connection;
}
$this->connection = $this->getConnection();
return $this->connection;
}
/**
* @throws ConnectionException
* @throws AuthenticationException
* @throws InvalidHostException
* @psalm-assert Connection $this->connection
*/
protected function reconnect(): void {
if ($this->connection === null) {
$this->connect();
} else {
$this->connection->reconnect();
if (!$this->connection->isValid()) {
throw new ConnectionException();
}
}
}
/**
* Get the name of the share
*
* @return string
*/
public function getName(): string {
return $this->name;
}
protected function simpleCommand(string $command, string $path): bool {
$escapedPath = $this->escapePath($path);
$cmd = $command . ' ' . $escapedPath;
$output = $this->execute($cmd);
return $this->parseOutput($output, $path);
}
/**
* List the content of a remote folder
*
* @param string $path
* @return IFileInfo[]
*
* @throws NotFoundException
* @throws InvalidTypeException
*/
public function dir(string $path): array {
$escapedPath = $this->escapePath($path);
$output = $this->execute('cd ' . $escapedPath);
//check output for errors
$this->parseOutput($output, $path);
$output = $this->execute('dir');
$this->execute('cd /');
return $this->parser->parseDir($output, $path, function (string $path) {
return $this->getAcls($path);
});
}
/**
* @param string $path
* @return IFileInfo
*/
public function stat(string $path): IFileInfo {
// some windows server setups don't seem to like the allinfo command
// use the dir command instead to get the file info where possible
if ($path !== "" && $path !== "/") {
$parent = dirname($path);
$dir = $this->dir($parent);
$file = array_values(array_filter($dir, function (IFileInfo $info) use ($path) {
return $info->getPath() === $path;
}));
if ($file) {
return $file[0];
}
}
$escapedPath = $this->escapePath($path);
$output = $this->execute('allinfo ' . $escapedPath);
// Windows and non Windows Fileserver may respond different
// to the allinfo command for directories. If the result is a single
// line = error line, redo it with a different allinfo parameter
if ($escapedPath == '""' && count($output) < 2) {
$output = $this->execute('allinfo ' . '"."');
}
if (count($output) < 3) {
$this->parseOutput($output, $path);
}
$stat = $this->parser->parseStat($output);
return new FileInfo($path, basename($path), $stat['size'], $stat['mtime'], $stat['mode'], function () use ($path) {
return $this->getAcls($path);
});
}
/**
* Create a folder on the share
*
* @param string $path
* @return bool
*
* @throws NotFoundException
* @throws AlreadyExistsException
*/
public function mkdir(string $path): bool {
return $this->simpleCommand('mkdir', $path);
}
/**
* Remove a folder on the share
*
* @param string $path
* @return bool
*
* @throws NotFoundException
* @throws InvalidTypeException
*/
public function rmdir(string $path): bool {
return $this->simpleCommand('rmdir', $path);
}
/**
* Delete a file on the share
*
* @param string $path
* @param bool $secondTry
* @return bool
* @throws InvalidTypeException
* @throws NotFoundException
* @throws \Exception
*/
public function del(string $path, bool $secondTry = false): bool {
//del return a file not found error when trying to delete a folder
//we catch it so we can check if $path doesn't exist or is of invalid type
try {
return $this->simpleCommand('del', $path);
} catch (NotFoundException $e) {
//no need to do anything with the result, we just check if this throws the not found error
try {
$this->simpleCommand('ls', $path);
} catch (NotFoundException $e2) {
throw $e;
} catch (\Exception $e2) {
throw new InvalidTypeException($path);
}
throw $e;
} catch (FileInUseException $e) {
if ($secondTry) {
throw $e;
}
$this->reconnect();
return $this->del($path, true);
}
}
/**
* Rename a remote file
*
* @param string $from
* @param string $to
* @return bool
*
* @throws NotFoundException
* @throws AlreadyExistsException
*/
public function rename(string $from, string $to): bool {
$path1 = $this->escapePath($from);
$path2 = $this->escapePath($to);
$output = $this->execute('rename ' . $path1 . ' ' . $path2);
return $this->parseOutput($output, $to);
}
/**
* Upload a local file
*
* @param string $source local file
* @param string $target remove file
* @return bool
*
* @throws NotFoundException
* @throws InvalidTypeException
*/
public function put(string $source, string $target): bool {
$path1 = $this->escapeLocalPath($source); //first path is local, needs different escaping
$path2 = $this->escapePath($target);
$output = $this->execute('put ' . $path1 . ' ' . $path2);
return $this->parseOutput($output, $target);
}
/**
* Download a remote file
*
* @param string $source remove file
* @param string $target local file
* @return bool
*
* @throws NotFoundException
* @throws InvalidTypeException
*/
public function get(string $source, string $target): bool {
$path1 = $this->escapePath($source);
$path2 = $this->escapeLocalPath($target); //second path is local, needs different escaping
$output = $this->execute('get ' . $path1 . ' ' . $path2);
return $this->parseOutput($output, $source);
}
/**
* Open a readable stream to a remote file
*
* @param string $source
* @return resource a read only stream with the contents of the remote file
*
* @throws NotFoundException
* @throws InvalidTypeException
*/
public function read(string $source) {
$source = $this->escapePath($source);
// since returned stream is closed by the caller we need to create a new instance
// since we can't re-use the same file descriptor over multiple calls
$connection = $this->getConnection();
stream_set_blocking($connection->getOutputStream(), false);
$connection->write('get ' . $source . ' ' . $this->system->getFD(5));
$connection->write('exit');
$fh = $connection->getFileOutputStream();
$fh = CallbackWrapper::wrap($fh, function() use ($connection) {
$connection->write('');
});
if (!is_resource($fh)) {
throw new Exception("Failed to wrap file output");
}
return $fh;
}
/**
* Open a writable stream to a remote file
*
* @param string $target
* @return resource a write only stream to upload a remote file
*
* @throws NotFoundException
* @throws InvalidTypeException
*/
public function write(string $target) {
$target = $this->escapePath($target);
// since returned stream is closed by the caller we need to create a new instance
// since we can't re-use the same file descriptor over multiple calls
$connection = $this->getConnection();
$fh = $connection->getFileInputStream();
$connection->write('put ' . $this->system->getFD(4) . ' ' . $target);
$connection->write('exit');
// use a close callback to ensure the upload is finished before continuing
// this also serves as a way to keep the connection in scope
$stream = CallbackWrapper::wrap($fh, function() use ($connection) {
$connection->write('');
}, null, function () use ($connection) {
$connection->close(false); // dont terminate, give the upload some time
});
if (is_resource($stream)) {
return $stream;
} else {
throw new InvalidRequestException($target);
}
}
/**
* Append to stream
* Note: smbclient does not support this (Use php-libsmbclient)
*
* @param string $target
*
* @throws DependencyException
*/
public function append(string $target) {
throw new DependencyException('php-libsmbclient is required for append');
}
/**
* @param string $path
* @param int $mode a combination of FileInfo::MODE_READONLY, FileInfo::MODE_ARCHIVE, FileInfo::MODE_SYSTEM and FileInfo::MODE_HIDDEN, FileInfo::NORMAL
* @return mixed
*/
public function setMode(string $path, int $mode) {
$modeString = '';
foreach (self::MODE_MAP as $modeByte => $string) {
if ($mode & $modeByte) {
$modeString .= $string;
}
}
$path = $this->escapePath($path);
// first reset the mode to normal
$cmd = 'setmode ' . $path . ' -rsha';
$output = $this->execute($cmd);
$this->parseOutput($output, $path);
if ($mode !== FileInfo::MODE_NORMAL) {
// then set the modes we want
$cmd = 'setmode ' . $path . ' ' . $modeString;
$output = $this->execute($cmd);
return $this->parseOutput($output, $path);
} else {
return true;
}
}
/**
* @param string $path
* @return INotifyHandler
* @throws ConnectionException
* @throws DependencyException
*/
public function notify(string $path): INotifyHandler {
if (!$this->system->getStdBufPath()) { //stdbuf is required to disable smbclient's output buffering
throw new DependencyException('stdbuf is required for usage of the notify command');
}
$connection = $this->getConnection(); // use a fresh connection since the notify command blocks the process
$command = 'notify ' . $this->escapePath($path);
$connection->write($command . PHP_EOL);
return new NotifyHandler($connection, $path);
}
/**
* @param string $command
* @return string[]
*/
protected function execute(string $command): array {
$this->connect()->write($command);
return $this->connect()->read();
}
/**
* check output for errors
*
* @param string[] $lines
* @param string $path
*
* @return bool
* @throws AlreadyExistsException
* @throws \Icewind\SMB\Exception\AccessDeniedException
* @throws \Icewind\SMB\Exception\NotEmptyException
* @throws InvalidTypeException
* @throws \Icewind\SMB\Exception\Exception
* @throws NotFoundException
*/
protected function parseOutput(array $lines, string $path = ''): bool {
if (count($lines) === 0) {
return true;
} else {
$this->parser->checkForError($lines, $path);
}
}
/**
* @param string $string
* @return string
*/
protected function escape(string $string): string {
return escapeshellarg($string);
}
/**
* @param string $path
* @return string
*/
protected function escapePath(string $path): string {
$this->verifyPath($path);
if ($path === '/') {
$path = '';
}
$path = str_replace('/', '\\', $path);
$path = str_replace('"', '^"', $path);
$path = ltrim($path, '\\');
return '"' . $path . '"';
}
/**
* @param string $path
* @return string
*/
protected function escapeLocalPath(string $path): string {
$path = str_replace('"', '\"', $path);
return '"' . $path . '"';
}
/**
* @param string $path
* @return ACL[]
* @throws ConnectionException
* @throws ConnectException
*/
protected function getAcls(string $path): array {
$commandPath = $this->system->getSmbcAclsPath();
if (!$commandPath) {
return [];
}
$command = sprintf(
'%s %s %s %s/%s %s',
$commandPath,
$this->getAuthFileArgument(),
$this->server->getAuth()->getExtraCommandLineArguments(),
escapeshellarg('//' . $this->server->getHost()),
escapeshellarg($this->name),
escapeshellarg($path)
);
$connection = new RawConnection($command);
$connection->writeAuthentication($this->server->getAuth()->getUsername(), $this->server->getAuth()->getPassword());
$connection->connect();
if (!$connection->isValid()) {
throw new ConnectionException((string)$connection->readLine());
}
$rawAcls = $connection->readAll();
return $this->parser->parseACLs($rawAcls);
}
public function getServer(): IServer {
return $this->server;
}
public function __destruct() {
unset($this->connection);
}
}
+19
View File
@@ -0,0 +1,19 @@
Copyright (c) 2015 Robin Appelman <robin@icewind.nl>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+235
View File
@@ -0,0 +1,235 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.
The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.
An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based on the Program.
To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If 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 convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.
You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <http://www.gnu.org/licenses/>.
+121
View File
@@ -0,0 +1,121 @@
Creative Commons Legal Code
CC0 1.0 Universal
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
HEREUNDER.
Statement of Purpose
The laws of most jurisdictions throughout the world automatically confer
exclusive Copyright and Related Rights (defined below) upon the creator
and subsequent owner(s) (each and all, an "owner") of an original work of
authorship and/or a database (each, a "Work").
Certain owners wish to permanently relinquish those rights to a Work for
the purpose of contributing to a commons of creative, cultural and
scientific works ("Commons") that the public can reliably and without fear
of later claims of infringement build upon, modify, incorporate in other
works, reuse and redistribute as freely as possible in any form whatsoever
and for any purposes, including without limitation commercial purposes.
These owners may contribute to the Commons to promote the ideal of a free
culture and the further production of creative, cultural and scientific
works, or to gain reputation or greater distribution for their Work in
part through the use and efforts of others.
For these and/or other purposes and motivations, and without any
expectation of additional consideration or compensation, the person
associating CC0 with a Work (the "Affirmer"), to the extent that he or she
is an owner of Copyright and Related Rights in the Work, voluntarily
elects to apply CC0 to the Work and publicly distribute the Work under its
terms, with knowledge of his or her Copyright and Related Rights in the
Work and the meaning and intended legal effect of CC0 on those rights.
1. Copyright and Related Rights. A Work made available under CC0 may be
protected by copyright and related or neighboring rights ("Copyright and
Related Rights"). Copyright and Related Rights include, but are not
limited to, the following:
i. the right to reproduce, adapt, distribute, perform, display,
communicate, and translate a Work;
ii. moral rights retained by the original author(s) and/or performer(s);
iii. publicity and privacy rights pertaining to a person's image or
likeness depicted in a Work;
iv. rights protecting against unfair competition in regards to a Work,
subject to the limitations in paragraph 4(a), below;
v. rights protecting the extraction, dissemination, use and reuse of data
in a Work;
vi. database rights (such as those arising under Directive 96/9/EC of the
European Parliament and of the Council of 11 March 1996 on the legal
protection of databases, and under any national implementation
thereof, including any amended or successor version of such
directive); and
vii. other similar, equivalent or corresponding rights throughout the
world based on applicable law or treaty, and any national
implementations thereof.
2. Waiver. To the greatest extent permitted by, but not in contravention
of, applicable law, Affirmer hereby overtly, fully, permanently,
irrevocably and unconditionally waives, abandons, and surrenders all of
Affirmer's Copyright and Related Rights and associated claims and causes
of action, whether now known or unknown (including existing as well as
future claims and causes of action), in the Work (i) in all territories
worldwide, (ii) for the maximum duration provided by applicable law or
treaty (including future time extensions), (iii) in any current or future
medium and for any number of copies, and (iv) for any purpose whatsoever,
including without limitation commercial, advertising or promotional
purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
member of the public at large and to the detriment of Affirmer's heirs and
successors, fully intending that such Waiver shall not be subject to
revocation, rescission, cancellation, termination, or any other legal or
equitable action to disrupt the quiet enjoyment of the Work by the public
as contemplated by Affirmer's express Statement of Purpose.
3. Public License Fallback. Should any part of the Waiver for any reason
be judged legally invalid or ineffective under applicable law, then the
Waiver shall be preserved to the maximum extent permitted taking into
account Affirmer's express Statement of Purpose. In addition, to the
extent the Waiver is so judged Affirmer hereby grants to each affected
person a royalty-free, non transferable, non sublicensable, non exclusive,
irrevocable and unconditional license to exercise Affirmer's Copyright and
Related Rights in the Work (i) in all territories worldwide, (ii) for the
maximum duration provided by applicable law or treaty (including future
time extensions), (iii) in any current or future medium and for any number
of copies, and (iv) for any purpose whatsoever, including without
limitation commercial, advertising or promotional purposes (the
"License"). The License shall be deemed effective as of the date CC0 was
applied by Affirmer to the Work. Should any part of the License for any
reason be judged legally invalid or ineffective under applicable law, such
partial invalidity or ineffectiveness shall not invalidate the remainder
of the License, and in such case Affirmer hereby affirms that he or she
will not (i) exercise any of his or her remaining Copyright and Related
Rights in the Work or (ii) assert any associated claims and causes of
action with respect to the Work, in either case contrary to Affirmer's
express Statement of Purpose.
4. Limitations and Disclaimers.
a. No trademark or patent rights held by Affirmer are waived, abandoned,
surrendered, licensed or otherwise affected by this document.
b. Affirmer offers the Work as-is and makes no representations or
warranties of any kind concerning the Work, express, implied,
statutory or otherwise, including without limitation warranties of
title, merchantability, fitness for a particular purpose, non
infringement, or the absence of latent or other defects, accuracy, or
the present or absence of errors, whether or not discoverable, all to
the greatest extent permissible under applicable law.
c. Affirmer disclaims responsibility for clearing rights of other persons
that may apply to the Work or any use thereof, including without
limitation any person's Copyright and Related Rights in the Work.
Further, Affirmer disclaims responsibility for obtaining any necessary
consents, permissions or other rights required for any use of the
Work.
d. Affirmer understands and acknowledges that Creative Commons is not a
party to this document and has no duty or obligation with respect to
this CC0 or use of the Work.
+9
View File
@@ -0,0 +1,9 @@
MIT License
Copyright (c) <year> <copyright holders>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+2
View File
@@ -0,0 +1,2 @@
SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
SPDX-License-Identifier: MIT
+131
View File
@@ -0,0 +1,131 @@
<?php
/**
* SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
* SPDX-License-Identifier: MIT
*/
namespace Icewind\Streams;
/**
* Wrapper that provides callbacks for write, read and close
*
* The following options should be passed in the context when opening the stream
* [
* 'callback' => [
* 'source' => resource
* 'read' => function($count){} (optional)
* 'write' => function($data){} (optional)
* 'close' => function(){} (optional)
* 'readdir' => function(){} (optional)
* ]
* ]
*
* All callbacks are called after the operation is executed on the source stream
*/
class CallbackWrapper extends Wrapper {
/**
* @var callable|null
*/
protected $readCallback;
/**
* @var callable|null
*/
protected $writeCallback;
/**
* @var callable|null
*/
protected $closeCallback;
/**
* @var callable|null
*/
protected $readDirCallBack;
/**
* @var callable|null
*/
protected $preCloseCallback;
/**
* Wraps a stream with the provided callbacks
*
* @param resource $source
* @param callable|null $read (optional)
* @param callable|null $write (optional)
* @param callable|null $close (optional)
* @param callable|null $readDir (optional)
* @param callable|null $preClose (optional)
* @return resource|false
*
*/
public static function wrap($source, $read = null, $write = null, $close = null, $readDir = null, $preClose = null) {
$context = [
'source' => $source,
'read' => $read,
'write' => $write,
'close' => $close,
'readDir' => $readDir,
'preClose' => $preClose,
];
return self::wrapSource($source, $context);
}
protected function open() {
$context = $this->loadContext();
$this->readCallback = $context['read'];
$this->writeCallback = $context['write'];
$this->closeCallback = $context['close'];
$this->readDirCallBack = $context['readDir'];
$this->preCloseCallback = $context['preClose'];
return true;
}
public function dir_opendir($path, $options) {
return $this->open();
}
public function stream_open($path, $mode, $options, &$opened_path) {
return $this->open();
}
public function stream_read($count) {
$result = parent::stream_read($count);
if (is_callable($this->readCallback)) {
call_user_func($this->readCallback, strlen($result));
}
return $result;
}
public function stream_write($data) {
$result = parent::stream_write($data);
if (is_callable($this->writeCallback)) {
call_user_func($this->writeCallback, $data);
}
return $result;
}
public function stream_close() {
if (is_callable($this->preCloseCallback)) {
call_user_func($this->preCloseCallback, $this->source);
// prevent further calls by potential PHP 7 GC ghosts
$this->preCloseCallback = null;
}
$result = parent::stream_close();
if (is_callable($this->closeCallback)) {
call_user_func($this->closeCallback);
// prevent further calls by potential PHP 7 GC ghosts
$this->closeCallback = null;
}
return $result;
}
public function dir_readdir() {
$result = parent::dir_readdir();
if (is_callable($this->readDirCallBack)) {
call_user_func($this->readDirCallBack);
}
return $result;
}
}

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