feat: initial ACRIB WordPress deployment

- WordPress 6.9.4 (es_ES) with Kadence theme
- Homepage: Hero, La Asociación, Pilares, Beneficios, Eventos, Miembros, Hazte Miembro, Contacto
- Brand identity: #13294b navy, #a12932 burgundy, #c69c48 gold
- Fonts: Raleway (headings) + Source Sans 3 (body) + Lato (UI)
- Plugins: Kadence Blocks, Polylang, Contact Form 7
- Custom CSS with full brand styling and responsive layout
- HTTPS enforced via wp-config.php proxy detection
This commit is contained in:
Malin
2026-05-19 19:25:59 +02:00
commit f3ff7b7186
6119 changed files with 1984255 additions and 0 deletions

View File

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is 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. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
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.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
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 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. Use with the GNU Affero General Public License.
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 Affero 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 special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU 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 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 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 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 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
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 GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View File

@@ -0,0 +1,313 @@
# StellarWP Uplink
[![CI](https://github.com/stellarwp/uplink/workflows/CI/badge.svg)](https://github.com/stellarwp/uplink/actions?query=branch%3Amain) [![Static Analysis](https://github.com/stellarwp/uplink/actions/workflows/static-analysis.yml/badge.svg)](https://github.com/stellarwp/uplink/actions/workflows/static-analysis.yml)
## Installation
It's recommended that you install Uplink as a project dependency via [Composer](https://getcomposer.org/):
```bash
composer require stellarwp/uplink
```
> We _actually_ recommend that this library gets included in your project using [Strauss](https://github.com/BrianHenryIE/strauss).
>
> Luckily, adding Strauss to your `composer.json` is only slightly more complicated than adding a typical dependency, so checkout our [strauss docs](https://github.com/stellarwp/global-docs/blob/main/docs/strauss-setup.md).
## Initialize the library
Initializing the StellarWP Uplink library should be done within the `plugins_loaded` action, preferably at priority `0`.
```php
use StellarWP\Uplink\Uplink;
add_action( 'plugins_loaded', function() {
/**
* Configure the container.
*
* The container must be compatible with stellarwp/container-contract.
* See here: https://github.com/stellarwp/container-contract#usage.
*
* If you do not have a container, we recommend https://github.com/lucatume/di52
* and the corresponding wrapper:
* https://github.com/stellarwp/container-contract/blob/main/examples/di52/Container.php
*/
$container = new Container();
Config::set_container( $container );
Config::set_hook_prefix( 'my-custom-prefix' );
/*
* If you wish to allow a customer to authorize their product, set your Token Auth Prefix.
*
* This will allow storage of a unique token associated with the customer's license/domain.
*
* Important: The Token auth prefix should be the same across all of your products.
*/
Config::set_token_auth_prefix( 'my_origin' );
// Optionally, change the default auth token caching.
Config::set_auth_cache_expiration( WEEK_IN_SECONDS );
// Or, disable it completely.
Config::set_auth_cache_expiration( -1 );
Uplink::init();
}, 0 );
```
> 💡 See [multisite license documentation](./docs/features.md#multisite-licenses) to enable
> network licensing features.
## Translation
Package is using `__( 'Invalid request: nonce field is expired. Please try again.', '%TEXTDOMAIN%' )` function for translation. In order to change domain placeholder `'%TEXTDOMAIN%'` to your plugin translation domain run
```bash
./bin/stellar-uplink domain=<your-plugin-domain>
```
or
```bash
./bin/stellar-uplink
```
and prompt the plugin domain
You can also add lines below to your composer file in order to run command automatically
```json
"scripts": {
"stellar-uplink": [
"vendor/bin/stellar-uplink domain=<your-plugin-domain>"
],
"post-install-cmd": [
"@stellar-uplink"
],
"post-update-cmd": [
"@stellar-uplink"
]
}
```
## Embedding a license in your plugin
StellarWP Uplink plugins are downloaded with an embedded license key so that users do not need to manually enter the key when activating their plugin. To make this possible, the class must be in a specific location so that the licensing server can find it.
```bash
# The class file should be in this path:
src/Uplink/Helper.php
```
The file should match the following - keeping the `KEY` constant set to a blank string, or, if you want a default license key, set it to that.:
```php
<?php declare( strict_types=1 );
namespace Whatever\Namespace\Uplink;
final class Helper {
public const KEY = '';
}
```
## Registering a plugin
Registers a plugin for licensing and updates.
```php
use StellarWP\Uplink\Register;
$plugin_slug = 'my-plugin';
$plugin_name = 'My Plugin';
$plugin_version = MyPlugin::VERSION;
$plugin_path = 'my-plugin/my-plugin.php';
$plugin_class = MyPlugin::class;
$license_class = MyPlugin\Uplink\Helper::class;
Register::plugin(
$plugin_slug,
$plugin_name,
$plugin_version,
$plugin_path,
$plugin_class,
$license_class // This is optional.
);
```
## Registering a service
Registers a service for licensing. Since services require a plugin, we pull version and class information from the plugin.
```php
use StellarWP\Uplink\Register;
$service_slug = 'my-service';
$service_name = 'My Service';
$service_version = MyPlugin::VERSION;
$plugin_path = 'my-plugin/my-plugin.php';
$plugin_class = MyPlugin::class;
Register::service(
$service_slug,
$service_name,
$service_version,
$plugin_path,
$plugin_class
);
```
## Render license key form on your settings page
In order to render license key form just add the following to your settings page, tab, etc.
> ⚠️ This will render license key fields for all of your registered plugins/services in the same Uplink/Container instance.
```php
use StellarWP\Uplink\Config;
$fields = \StellarWP\Uplink\get_license_field();
// Do one of the following:
$fields->render(); // Render the fields, titles, and submit button.
$fields->render( false ); // Render the fields without the titles.
$fields->render( false, false ); // Render the fields without the titles or submit buttons.
```
To render a single product's license key, use the following:
```php
use StellarWP\Uplink\Config;
$fields = \StellarWP\Uplink\get_license_field();
// Do one of the following:
$fields->render_single( 'my-plugin' ); // Render the fields, titles, and submit button.
$fields->render_single( 'my-plugin', false ); // Render the fields without the titles.
$fields->render_single( 'my-plugin', false, false ); // Render the fields without the titles or submit buttons.
```
### Example: Register settings page and render license fields
Register a settings page for a plugin if you need it
```php
add_action( 'admin_menu', function () {
add_menu_page(
'Sample',
'Sample',
'manage_options',
'sample-plugin-lib',
'render_settings_page',
'',
null
);
}, 11 );
```
Add lines below to your settings page. This will render license key form with titles and a submit button
```php
use StellarWP\Uplink\Config;
function render_settings_page() {
// ...
$fields = \StellarWP\Uplink\get_license_field();
$fields->render(); // or $fields->render_single( 'my-plugin' ); to render a single plugin
//....
}
```
## License Authorization
> ⚠️ Your `auth_url` is set on the Origins table on the [Stellar Licensing](https://github.com/stellarwp/licensing) server!
> You must first request to have this added before proceeding.
There may be certain functionality you wish to make available when you know a license is authorized.
This library provides the tools to fetch and store unique tokens, working together with the Uplink Origin
plugin.
After following the instructions at the top to define a `Config::set_token_auth_prefix()`, this will enable the following
functionality:
1. The ability to render a "Connect" button anywhere in your plugin while the user is in wp-admin, using the provided function below.
2. The button will display "Disconnect" once they are authorized, which deletes the locally stored Token.
3. The ability for the customer's site to accept specific Query Variables in wp-admin, that will store the generated Token, and an optional new License Key for a Product Slug.
4. Check if a license is authorized, either in the License Validation payload, or manually.
> ⚠️ Generating a Token requires manual configuration on your Origin site using the [Uplink Origin Plugin](https://github.com/stellarwp/uplink-origin).
### Render Authorize Button
> 💡 Note: the button is only rendered if the following conditions are met:
1. You have an `auth_url` set on the StellarWP Licensing Server.
2. The current user is a Super Admin (can be changed with a WP filter).
3. This is not a multisite installation, or...
4. If multisite and using subfolders, only on the root network dashboard.
5. If multisite and NOT using subfolders and on a subsite AND a token doesn't already exist at the network level, in which case it needs to be managed at the network.
```php
// Call the namespaced function with your plugin slug.
\StellarWP\Uplink\render_authorize_button( 'my-plugin-slug' );
```
You can also pass in a custom license domain, which can be fetched on the Uplink Origin side from the `uplink_domain` query variable:
```php
// Call the namespaced function with your plugin slug and license domain.
\StellarWP\Uplink\render_authorize_button( 'my-plugin-slug', \StellarWP\Uplink\get_license_domain() );
```
> 💡 The button is very customizable with filters, see [Authorize_Button_Controller.php](src/Uplink/Components/Admin/Authorize_Button_Controller.php).
### Manually Check if a License is Remotely Authorized
This connects to the licensing server to check in real time if the license is authorized. Use sparingly.
```php
$is_authorized = \StellarWP\Uplink\is_authorized_by_resource( 'my-plugin-slug' );
echo $is_authorized ? esc_html__( 'authorized' ) : esc_html__( 'not authorized' );
```
Or, if you have more complex licensing needs, you can provide specific data:
```php
$token = \StellarWP\Uplink\get_authorization_token( 'my-plugin-slug' );
$license_key = \StellarWP\Uplink\get_license_key( 'my-plugin-slug' );
$domain = \StellarWP\Uplink\get_license_domain();
if ( ! $token || ! $license_key || ! $domain ) {
return; // or, log/show errors.
}
$is_authorized = \StellarWP\Uplink\is_authorized( $license_key, 'my-plugin-slug', $token, $domain );
echo $is_authorized ? esc_html__( 'authorized' ) : esc_html__( 'not authorized' );
```
### Manually Fetch Auth URL
If for some reason you need to fetch your `auth_url` manually, you can do so by:
```php
echo esc_url( \StellarWP\Uplink\get_auth_url( 'my-plugin-slug' ) );
```
> 💡 Auth URL connections are cached for one day using transients.
### Callback Redirect
The Callback Redirect generated by the Origin looks something like this, where `uplinksample.lndo.site` is your
customer's website:
```
https://uplinksample.lndo.site/wp-admin/import.php?uplink_token=d9a407d0-0eb1-41cf-8cd0-e5da668143b4&_uplink_nonce=Oyj13TCvhaa12IJm
```
The Origin is responsible for asking StellarWP Licensing to generate a token and redirect back to where the customer originally
clicked on the button.
The following Query Variables are available for reference:
> 💡 Note: This data automatically gets stored when detected, using the `admin_init` hook!
1. `uplink_token` - The unique UUIDv4 token generated by StellarWP Licensing.
2. `_uplink_nonce` - The original nonce sent with the callback URL, as part of the "Connect" button.
3. `uplink_slug` The Product or Service Slug that we're updating the license for.
4. `uplink_license` (optional) - Whether we should also update or set a License Key.

View File

@@ -0,0 +1,65 @@
#!/usr/bin/env php
<?php declare(strict_types=1);
function ask( string $question, string $default = '' ): string {
$answer = readline( $question . ( $default ? " ($default)" : null ) . ': ' );
if ( ! $answer ) {
return $default;
}
return $answer;
}
function confirm( string $question, bool $default = false ): bool {
$answer = ask( $question . ' (' . ( $default ? 'Y/n' : 'y/N' ) . ')' );
if ( ! $answer ) {
return $default;
}
return strtolower( $answer ) === 'y';
}
function replace_in_file( string $file, array $replacements ): void {
$contents = file_get_contents( $file );
file_put_contents(
$file,
str_replace(
array_keys( $replacements ),
array_values( $replacements ),
$contents
)
);
}
function writeln( string $line ): void {
echo $line . PHP_EOL;
}
function run( string $command ): string {
return trim( shell_exec( $command ) ?: '' );
}
parse_str( implode( '&', array_slice( $argv, 1 ) ), $result );
$domain = $result['domain'] ?? ask( 'Text Domain Name', 'my-text-domain' );
if ( empty( $domain ) ) {
writeln( 'Translation domain could not be empty' );
exit( 0 );
}
if ( ! confirm( 'Modify files?', true ) ) {
exit( 1 );
}
$files = explode( PHP_EOL, run( 'grep -E -r -l -i "%TEXTDOMAIN%" "' . dirname( __FILE__, 2 ) . '/src"' ) );
$files = array_filter( $files );
foreach ( $files as $file ) {
replace_in_file( $file, [
'%TEXTDOMAIN%' => $domain
] );
}

View File

@@ -0,0 +1,191 @@
# Uplink features
The goals of this library are to provide a simple way to register one or more plugins / services for licensing and updates. It should provide:
* An API and documentation for registering plugins/services
* Support for plugins that embed license keys within the code
* A user interface for entering / changing license keys
* Support for fetching and installing plugin updates from Stellar Licensing
## Expectations
1. This library will exist within multiple plugins--ideally included via Compuser using Strauss to avoid collisions with other installed versions of the same library.
2. This library may be included in a plugin collection that has a shared codebase, so multiple plugins need to be able to register themselves using a shared library. An example of this usecase would be The Events Calendar and Event Tickets, which have a shared library that all of The Events Calendar add-ons utilize.
3. This library should be as unopinionated as possible when it comes to the UI. It should provide page content that plugins can render where they see fit.
## Features
### Registration
Registration of plugins and services should happen programmatically and the intended API is documented in this repository's [README](/README.md).
### License keys & validation
The Uplink library should communicate with the Stellar Licensing system at specific moments. Those moments are:
1. When a user interacts with a page in the dashboard where Uplink's license key field UI is rendered.
2. When an authorized user* navigates to the plugins page and there has not been a request to the Stellar Licensing system within the past 12 hours.
3. When an authorized user* attempts to upgrade plugins.
_* An authorized user is defined as a user with the `install_plugins` capability._
When a page is loaded where the Uplink library should call home to the Stellar Licensing system, this flow should be followed:
```mermaid
sequenceDiagram
autonumber
participant wp as WordPress
participant plugin as Plugin
participant uplink as Uplink
participant stellar as Stellar Licensing
link uplink: stellarwp/uplink @ https://github.com/stellarwp/uplink
link stellar: the-events-calendar/pue-service @ https://github.com/the-events-calendar/pue-service
link stellar: stellarwp/licensing @ https://github.com/stellarwp/licensing
wp->>plugin: plugins_loaded action
plugin->>uplink: Register::plugin()
Note over wp, stellar: The following is triggered by the 3 conditions mentioned above.
alt License key in wp_options
uplink-->>+wp: Check for license key in wp_options
wp->>-uplink: license key
else License key embedded in plugin
uplink-->>+plugin: Check for embedded license key in plugin
plugin->>-uplink: license key
end
uplink->>stellar: POST /api/plugins/v2/license/validate
stellar-->>+uplink: 200 OK response
uplink-->>wp: Store response in wp_options
uplink->>uplink: Check for response_key in response
opt replacement_key in response
uplink-->>-wp: Update stored license key in wp_options
Note over wp, uplink: The replacement_key is typically only set if the provided license key is a placeholder key from the<br>WordPress Marketplace.
end
```
#### Embedded keys
The Stellar Licensing service has the capability of embedding license keys within the plugin code for products that have that capability enabled. The embedding happens at the moment of download. For plugins that expect an embedded license key to exist, the Uplink library needs to be notified of that license key's existence during registration of the plugin. You can see the expected structure in the [README](/README.md#embedding-a-license-in-your-plugin).
You can see an example of this in the wild within the [Events Calendar Pro plugin](https://github.com/the-events-calendar/events-pro/blob/master/src/Tribe/PUE/Helper.php).
#### UI for entering keys
Uplink should provide a UI for entering license keys. Ideally, Uplink should have a way to render license key fields, notifications, enqueue relevent styles & JS, etc within an administrative page as dictated by the plugin. For example, The Events Calendar needs to be able to choose to have the license keys fields/notices for Events Calendar Pro, Filter Bar, Virtual Events, etc (which are all add-ons of TEC) rendered on the _Events > Settings > Licenses_ page in the dashboard. Whereas Restrict Content Pro should be able to have _its_ license key fields rendered on a different Dashboard page.
When a license field is rendered, manipulated, or saved, a validation request should be triggered (see the diagram above).
### Product updates
The Uplink library should mark a registered plugin as needing an update when a validation response comes back from the Stellar Licensing system with a version number greater than the version number that is currently installed. You can see a reference implementation in [`tribe-common`](https://github.com/the-events-calendar/tribe-common/blob/master/src/Tribe/PUE/Checker.php#L1537).
#### Plugin page
On the _Plugins_ page in the WP Dashboard, any plugin that has an update available should display the update similar to how WordPress core does it. If a user click on `Update`, the zip files should be fetched from the Stellar Licensing system and installed if their license key is valid.
### Multisite Licenses
Out of the box, Uplink treats all sub-sites as their _own independent site_, storing license keys and authorization tokens
in the options table of that sub-site.
If your product supports multisite level licenses, you can configure Uplink to allow one license key/auth token for the entire
multisite network across multiple situations.
> 💡 To operate at the network level, your plugin **must be network activated** and the proper configuration options enabled.
| Install Type | Network Activated? | Clause | Uplink Config Option (default is false) | License & Token Storage Location |
|----------------------------|--------------------|--------|-----------------------------------------------------|----------------------------------|
| Standard | | | | Site level |
| Multisite (subfolders) | Yes | AND | `Config::set_network_subfolder_license(true)` | Network level |
| Multisite (subfolders) | No | OR | `Config::set_network_subfolder_license(false)` | Site Level |
| Multisite (subdomains) | Yes | AND | `Config::set_network_subdomain_license(true)` | Network level |
| Multisite (subdomains) | No | OR | `Config::set_network_subdomain_license(false)` | Site Level |
| Multisite (domain mapping) | Yes | AND | `Config::set_network_domain_mapping_license(true)` | Network level |
| Multisite (domain mapping) | No | OR | `Config::set_network_domain_mapping_license(false)` | Site Level |
#### Examples
After [library initialization](../README.md#initialize-the-library), the above config options can be set, e.g.
```php
use StellarWP\Uplink\Uplink;
// ...other config above
// Allow a single network license for multisite subfolders.
Config::set_network_subfolder_license( true );
// Allow a single network license for multisite using subdomains.
Config::set_network_subdomain_license( true );
// Allow a single network license for custom domains/mapped domains.
Config::set_network_domain_mapping_license( true );
Uplink::init();
```
> 🚨 Consider moving your plugin UI and the Uplink License Field settings to the WordPress network UI to prevent
> sub-sites being able to control licensing and token authorization for the entire multisite network if you enable
> any of the multisite config options.
Each config option can also be filtered at runtime, assuming your plugin's slug is registered as `my-plugin-slug`:
```php
add_action( 'init', static function(): void {
// Replace with a call to your own plugin's config/option to check whether it should be managed in the network.
$network_enabled = true;
add_filter( 'stellarwp/uplink/my-plugin-slug/allows_network_subfolder_license',
static function () use ( $network_enabled ): bool {
return $network_enabled;
}, 10 );
add_filter( 'stellarwp/uplink/my-plugin-slug/allows_network_subdomain_license',
static function () use ( $network_enabled ): bool {
return $network_enabled;
}, 10 );
add_filter( 'stellarwp/uplink/my-plugin-slug/allows_network_domain_mapping_license',
static function () use ( $network_enabled ): bool {
return $network_enabled;
}, 10 );
} );
```
#### Functions
Uplink provides some handy functions that include automated support for fetching or storing data from
the correct location.
```php
// Checks if the current WordPress user is authorized to make license/token changes (is_super_admin() out of the box).
\StellarWP\Uplink\is_user_authorized();
// Get a stored license key, will fetch from the current site's options or network, depending on your config.
\StellarWP\Uplink\get_license_key( 'my-plugin-slug' );
// Store a license key, will store in the current site's options or network, depending on your config.
\StellarWP\Uplink\set_license_key( 'my-plugin-slug', 'new_license_key' );
// Get the domain associated with a license.
// Note that if any of the multisite options are enabled, the root multisite domain contains a unique suffix
// so that it doesn't override the license key/token for the entire multisite network if it's converted back
// to single site.
// Depending on your configuration, this may the multisite domain with suffix, e.g. example.com/2626gsg
// or, it could be the sub-site domain with path, e.g. example.com/sub1, example.com/sub2 etc...
\StellarWP\Uplink\get_license_domain();
// This will get the license domain without any added suffixes.
\StellarWP\Uplink\get_original_domain();
// Gets the local URL to disconnect a token (delete it locally).
\StellarWP\Uplink\get_disconnect_url( 'my-plugin-slug' );
// Checks if the current site (e.g. the sub-site on multisite) would support multisite licensing.
\StellarWP\Uplink\allows_multisite_license( 'my-plugin-slug' );
```

View File

@@ -0,0 +1,23 @@
# Automated tests
This repository uses Codeception for automated testing and leverages [`slic`](https://github.com/stellarwp/slic) for running the tests.
## Pre-requisites
* Docker
* A system-level PHP installation with MySQL libraries
* [`slic`](https://github.com/stellarwp/slic) set up and usable on your system (follow setup instructions in that repo)
## Running tests
### First time run
To run tests for the first time, there are a couple of things you need to do:
1. Run `slic here` in the parent directory from where this library is cloned. (e.g. If you ran `git clone` in your `wp-content/plugins` directory, run `slic here` from `wp-content/plugins`)
2. Run `slic use uplink` to tell `slic` to point to the uplink library.
2. Run `slic composer install` to bring in all the dependencies.
### Running the tests
You can simply run `slic run` or `slic run SUITE_YOU_WANT_TO_RUN` to quickly run automated tests for this library. If you want to use xdebug with your tests, you'll need to open a `slic ssh` session and turn xdebugging on (there's help text to show you how).

View File

@@ -0,0 +1 @@
<?php

View File

@@ -0,0 +1,250 @@
<?php
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\API;
use KadenceWP\KadenceBlocks\StellarWP\ContainerContract\ContainerInterface;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Config;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources\Resource;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Site\Data;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Utils;
/**
* API Client class.
*
* @since 1.0.0
*
* @property-read string $api_root The API root path.
* @property-read string $base_url The service base URL.
* @property-read ContainerInterface $container Container instance.
*/
class Client {
/**
* API base endpoint.
*
* @since 1.0.0
*
* @var string
*/
protected $api_root = '/api/plugins/v2/';
/**
* Base URL for the license key server.
*
* @since 1.0.0
*
* @var string
*/
protected $base_url = 'https://licensing.stellarwp.com';
/**
* Container.
*
* @since 1.0.0
*
* @var ContainerInterface
*/
protected $container;
/**
* Constructor.
*
* @since 1.0.0
*/
public function __construct() {
// @phpstan-ignore-next-line
$this->container = Config::get_container();
if ( defined( 'STELLARWP_UPLINK_API_BASE_URL' ) && STELLARWP_UPLINK_API_BASE_URL ) {
$this->base_url = preg_replace( '!/$!', '', STELLARWP_UPLINK_API_BASE_URL );
}
if ( defined( 'STELLARWP_UPLINK_API_ROOT' ) && STELLARWP_UPLINK_API_ROOT ) {
$this->api_root = trailingslashit( STELLARWP_UPLINK_API_ROOT );
}
}
/**
* Build hash.
*
* @since 1.0.0
*
* @param array<mixed> $args Arguments to hash.
*
* @return string
*/
public function build_hash( $args ) {
$args = array_filter( $args );
ksort( $args );
$args = json_encode( $args );
if ( ! $args ) {
return '';
}
return hash( 'sha256', $args );
}
/**
* GET request.
*
* @since 1.0.0
*
* @param string $endpoint
* @param array<mixed> $args
*
* @return mixed
*/
protected function get( $endpoint, $args ) {
return $this->request( 'GET', $endpoint, $args );
}
/**
* Get API base URL.
*
* @since 1.0.0
*
* @return string
*/
public function get_api_base_url() : string {
/**
* Filter the API base URL.
*
* @since 1.0.0
*
* @param string $base_url Base URL.
*/
return apply_filters( 'stellarwp/uplink/' . Config::get_hook_prefix() . '/api_get_base_url', $this->base_url );
}
/**
* POST request.
*
* @since 1.0.0
*
* @param string $endpoint
* @param array<mixed> $args
*
* @return mixed
*/
protected function post( $endpoint, $args ) {
return $this->request( 'POST', $endpoint, $args );
}
/**
* Send a request to the StellarWP Uplink API.
*
* @since 1.0.0
*
* @param string $method
* @param string $endpoint
* @param array<mixed> $args
*
* @return \stdClass|null
*/
protected function request( $method, $endpoint, $args ) {
$request_args = [
'method' => strtoupper( $method ),
'headers' => [
'Content-Type' => 'application/json',
],
'body' => wp_json_encode( $args ),
'timeout' => 15, // Seconds.
];
/**
* Filter the request arguments.
*
* @since 1.0.0
*
* @param array<mixed> $request_args Request arguments.
* @param string $endpoint Request method.
* @param array<mixed> $args Request data.
*/
$request_args = apply_filters( 'stellarwp/uplink/' . Config::get_hook_prefix() . '/api_request_args', $request_args, $endpoint, $args );
$url = $this->get_api_base_url() . $this->api_root . $endpoint;
$response = wp_remote_get( $url, $request_args );
$response_body = wp_remote_retrieve_body( $response );
$result = json_decode( $response_body );
/**
* Filter the API response.
*
* @since 1.0.0
*
* @param \stdClass|null $result API response.
* @param string $endpoint API endpoint.
* @param array<mixed> $args API arguments.
*/
return apply_filters( 'stellarwp/uplink/' . Config::get_hook_prefix() . '/api_response', $result, $endpoint, $args );
}
/**
* Validates the license.
*
* @since 1.0.0
*
* @param Resource $resource Resource to validate.
* @param string|null $key License key.
* @param string $validation_type Validation type (local or network).
* @param bool $force Force the validation.
*
* @throws \RuntimeException
*
* @return mixed
*/
public function validate_license( Resource $resource, ?string $key = null, string $validation_type = 'local', bool $force = false ) {
/** @var Data */
$site_data = $this->container->get( Data::class );
$args = $resource->get_validation_args();
if ( ! empty( $key ) ) {
$args['key'] = Utils\Sanitize::key( $key );
}
$args['domain'] = $site_data->get_domain();
$args['stats'] = $site_data->get_stats();
$args['stats']['network']['network_activated'] = $resource->is_network_activated();
/**
* Filter the license validation arguments.
*
* @since 1.0.0
*
* @param array<mixed> $args License validation arguments.
*/
$args = apply_filters( 'stellarwp/uplink/' . Config::get_hook_prefix() . '/client_validate_license_args', $args );
$request_hash = $this->build_hash( $args );
$cache_key = 'stellarwp_uplink_validate_license_' . $request_hash;
$results = $this->container->has( $cache_key ) ? $this->container->get( $cache_key ) : null;
if ( $force || ! $results ) {
$results = $this->post( 'license/validate', $args );
$this->container->bind( $cache_key, function() use ( $results ) { return $results; } );
}
if ( $results !== null && ! is_object( $results ) ) {
$results = null;
}
$results = new Validation_Response( $key, $validation_type, $results, $resource );
/**
* Filter the license validation results.
*
* @since 1.0.0
*
* @param Validation_Response $results License validation results.
* @param array<mixed> $args License validation arguments.
*/
return apply_filters( 'stellarwp/uplink/' . Config::get_hook_prefix() . '/client_validate_license', $results, $args );
}
}

View File

@@ -0,0 +1,56 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\API\V3\Auth;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\API\V3\Contracts\Client_V3;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Traits\With_Debugging;
use WP_Error;
/**
* Fetch a Product's Auth URL, which is a custom URL on the Origin's
* server where authorization would occur.
*/
final class Auth_Url implements Contracts\Auth_Url {
use With_Debugging;
/**
* @var Client_V3
*/
private $client;
/**
* @param Client_V3 $client The V3 API Client.
*/
public function __construct( Client_V3 $client ) {
$this->client = $client;
}
/**
* Retrieve an Origin's auth url, if it exists.
*
* @param string $slug The product slug.
*
* @return string
*/
public function get( string $slug ): string {
$response = $this->client->get( 'tokens/auth_url', [
'slug' => $slug,
] );
if ( $response instanceof WP_Error ) {
if ( $this->is_wp_debug() ) {
error_log( sprintf(
'Token auth failed for slug: "%s". Errors: %s',
$slug,
implode( ', ', $response->get_error_messages() )
) );
}
return '';
}
return $response['body']['data']['auth_url'] ?? '';
}
}

View File

@@ -0,0 +1,76 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\API\V3\Auth;
use InvalidArgumentException;
/**
* Auth URL cache decorator.
*/
final class Auth_Url_Cache_Decorator implements Contracts\Auth_Url {
public const TRANSIENT_PREFIX = 'stellarwp_auth_url_';
/**
* @var Auth_Url
*/
private $auth_url;
/**
* The cache expiration in seconds.
*
* @var int
*/
private $expiration;
/**
* @param Auth_Url $auth_url Remotely fetch the Origin's Auth URL.
* @param int $expiration The cache expiration in seconds.
*/
public function __construct( Auth_Url $auth_url, int $expiration = DAY_IN_SECONDS ) {
$this->auth_url = $auth_url;
$this->expiration = $expiration;
}
/**
* Cache the auth url response.
*
* @param string $slug The product slug.
*
* @throws InvalidArgumentException
*
* @return string
*/
public function get( string $slug ): string {
if ( ! $slug ) {
throw new InvalidArgumentException( __( 'The Product Slug cannot be empty', '%TEXTDOMAIN%' ) );
}
$transient = $this->build_transient( $slug );
$url = get_transient( $transient );
if ( $url !== false ) {
return $url;
}
$url = $this->auth_url->get( $slug );
// We'll cache empty auth URLs to prevent further remote requests.
set_transient( $transient, $url, $this->expiration );
return $url;
}
/**
* Build the transient key based on the provided slug.
*
* @param string $slug
*
* @return string
*/
private function build_transient( string $slug ): string {
return self::TRANSIENT_PREFIX . str_replace( '-', '_', $slug );
}
}

View File

@@ -0,0 +1,16 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\API\V3\Auth\Contracts;
interface Auth_Url {
/**
* Retrieve an Origin's auth url, if it exists.
*
* @param string $slug The product slug.
*
* @return string
*/
public function get( string $slug ): string;
}

View File

@@ -0,0 +1,23 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\API\V3\Auth\Contracts;
use WP_Error;
interface Token_Authorizer {
/**
* Check if a license is authorized.
*
* @see is_authorized()
* @see \KadenceWP\KadenceBlocks\StellarWP\Uplink\API\V3\Auth\Token_Authorizer
*
* @param string $license The license key.
* @param string $slug The plugin/service slug.
* @param string $token The stored token.
* @param string $domain The user's domain.
*
* @return bool|WP_Error
*/
public function is_authorized( string $license, string $slug, string $token, string $domain );
}

View File

@@ -0,0 +1,65 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\API\V3\Auth;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\API\V3\Contracts\Client_V3;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Traits\With_Debugging;
use WP_Error;
use WP_Http;
use function KadenceWP\KadenceBlocks\StellarWP\Uplink\is_authorized;
/**
* Manages authorization.
*/
class Token_Authorizer implements Contracts\Token_Authorizer {
use With_Debugging;
/**
* @var Client_V3
*/
private $client;
public function __construct( Client_V3 $client ) {
$this->client = $client;
}
/**
* Manually check if a license is authorized.
*
* @param string $license The license key.
* @param string $slug The plugin/service slug.
* @param string $token The stored token.
* @param string $domain The user's domain.
*
* @return bool|WP_Error
*
* @see is_authorized()
*/
public function is_authorized( string $license, string $slug, string $token, string $domain ) {
$response = $this->client->get( 'tokens/auth', [
'license' => $license,
'slug' => $slug,
'token' => $token,
'domain' => $domain,
] );
if ( $response instanceof WP_Error ) {
if ( $this->is_wp_debug() ) {
error_log( sprintf(
__( 'Authorization error occurred: License: "%s", Token: "%s", Domain: "%s". Errors: %s', '%TEXTDOMAIN%' ),
$license,
$token,
$domain,
implode( ', ', $response->get_error_messages() )
) );
}
return $response;
}
return $response['response']['code'] === WP_Http::OK;
}
}

View File

@@ -0,0 +1,104 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\API\V3\Auth;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\API\V3\Provider;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Config;
/**
* Token Authorizer Cache Decorator.
*
* @see Config::set_auth_cache_expiration() to enable.
*/
final class Token_Authorizer_Cache_Decorator implements Contracts\Token_Authorizer {
public const TRANSIENT_PREFIX = 'stellarwp_auth_';
public const AUTHORIZED = 'authorized';
public const NOT_AUTHORIZED = 'not_authorized';
/**
* @var Token_Authorizer
*/
private $authorizer;
/**
* The cache expiration in seconds.
*
* @var int
*/
private $expiration;
/**
* @see Config::set_auth_cache_expiration()
* @see Provider::register_token_authorizer()
*
* @param Token_Authorizer $authorizer The original authorizer.
* @param int $expiration The expiration time in seconds.
*/
public function __construct(
Token_Authorizer $authorizer,
int $expiration = 21600
) {
$this->authorizer = $authorizer;
$this->expiration = $expiration;
}
/**
* Check if a license is authorized and cache successful responses.
*
* @see Config::set_auth_cache_expiration()
* @see is_authorized()
* @see Token_Authorizer
*
* @param string $license The license key.
* @param string $slug The plugin/service slug.
* @param string $token The stored token.
* @param string $domain The user's domain.
*
* @return bool
*/
public function is_authorized( string $license, string $slug, string $token, string $domain ): bool {
$transient = $this->build_transient( [ $token, $license, $slug, $domain ] );
$cached = get_transient( $transient );
if ( $cached === self::AUTHORIZED ) {
return true;
} elseif ( $cached === self::NOT_AUTHORIZED ) {
return false;
}
$is_authorized = $this->authorizer->is_authorized( $license, $slug, $token, $domain );
if ( is_wp_error( $is_authorized ) ) {
// Don't cache errors.
return false;
}
set_transient( $transient, $is_authorized ? self::AUTHORIZED : self::NOT_AUTHORIZED, $this->expiration );
return $is_authorized;
}
/**
* Build a transient key.
*
* @param array<int, string> $args
*
* @return string
*/
public function build_transient( array $args ): string {
return self::TRANSIENT_PREFIX . $this->build_transient_no_prefix( $args );
}
/**
* Build a transient key without the prefix.
*
* @param array $args
*
* @return string
*/
public function build_transient_no_prefix( array $args ): string {
return hash( 'sha256', json_encode( $args ) );
}
}

View File

@@ -0,0 +1,156 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\API\V3;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\API\V3\Contracts\Client_V3;
use WP_Error;
use WP_Http;
use WpOrg\Requests\Utility\CaseInsensitiveDictionary;
/**
* The Version 3 client for the licensing server.
*
* @see \KadenceWP\KadenceBlocks\StellarWP\Uplink\API\V3\Provider::register()
*/
final class Client implements Client_V3 {
/**
* API base endpoint.
*
* @var string
*/
private $api_root;
/**
* Base URL for the license key server.
*
* @var string
*/
private $base_url;
/**
* The default request arguments to send with WP_Http
*
* @var array<string, mixed>
*/
private $request_args;
/**
* @var WP_Http
*/
private $wp_http;
/**
* @param string $api_root
* @param string $base_url
* @param array<string, mixed> $request_args
* @param WP_Http $wp_http
*/
public function __construct( string $api_root, string $base_url, array $request_args, WP_Http $wp_http ) {
$this->api_root = $api_root;
$this->base_url = $base_url;
$this->request_args = $request_args;
$this->wp_http = $wp_http;
}
/**
* Perform a GET request.
*
* @param string $endpoint
* @param array<string, mixed> $params
*
* @return WP_Error|array{
* 'body' : array<string, mixed>,
* 'headers' : CaseInsensitiveDictionary,
* 'response' : array{
* 'code' : int,
* 'message' : string,
* },
* 'cookies' : array<int, \WP_Http_Cookie>,
* 'filename' : string|null,
* 'http_response' : \WP_HTTP_Requests_Response
* }
*/
public function get( string $endpoint, array $params = [] ) {
$args = array_merge( $this->request_args, [
'body' => $params,
] );
return $this->request( $endpoint, 'GET', $args );
}
/**
* Perform a POST request.
*
* @param string $endpoint
* @param array<string, mixed> $params
*
* @return WP_Error|array{
* 'body' : array<string, mixed>,
* 'headers' : CaseInsensitiveDictionary,
* 'response' : array{
* 'code' : int,
* 'message' : string,
* },
* 'cookies' : array<int, \WP_Http_Cookie>,
* 'filename' : string|null,
* 'http_response' : \WP_HTTP_Requests_Response
* }
*/
public function post( string $endpoint, array $params = [] ) {
$args = array_merge( $this->request_args, [
'body' => $params,
] );
return $this->request( $endpoint, 'POST', $args );
}
/**
* Perform any other request.
*
* @param string $endpoint
* @param string $method
* @param array<string, mixed> $params
*
* @return WP_Error|array{
* 'body' : array<string, mixed>,
* 'headers' : CaseInsensitiveDictionary,
* 'response' : array{
* 'code' : int,
* 'message' : string,
* },
* 'cookies' : array<int, \WP_Http_Cookie>,
* 'filename' : string|null,
* 'http_response' : \WP_HTTP_Requests_Response
* }
*/
public function request( string $endpoint, string $method = 'GET', array $params = [] ) {
$url = $this->build_url( $endpoint );
$args = array_merge( $this->request_args, [
'method' => strtoupper( $method ),
], $params );
$response = $this->wp_http->request( $url, $args );
if ( $response instanceof WP_Error ) {
return $response;
}
$response['body'] = json_decode( $response['body'], true );
return $response;
}
/**
* Build the complete URL from a provided endpoint.
*
* @param string $endpoint The relative endpoint.
*
* @return string
*/
private function build_url( string $endpoint ): string {
return rtrim( $this->base_url, '/' ) . trailingslashit( $this->api_root ) . ltrim( $endpoint, '/' );
}
}

View File

@@ -0,0 +1,72 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\API\V3\Contracts;
use WP_Error;
use WpOrg\Requests\Utility\CaseInsensitiveDictionary;
interface Client_V3 {
/**
* Perform a GET request.
*
* @param string $endpoint
* @param array<string, mixed> $params
*
* @return WP_Error|array{
* 'body' : array<string, mixed>,
* 'headers' : CaseInsensitiveDictionary,
* 'response' : array{
* 'code' : int,
* 'message' : string,
* },
* 'cookies' : array<int, \WP_Http_Cookie>,
* 'filename' : string|null,
* 'http_response' : \WP_HTTP_Requests_Response
* }
*/
public function get( string $endpoint, array $params = [] );
/**
* Perform a POST request.
*
* @param string $endpoint
* @param array<string, mixed> $params
*
* @return WP_Error|array{
* 'body' : array<string, mixed>,
* 'headers' : CaseInsensitiveDictionary,
* 'response' : array{
* 'code' : int,
* 'message' : string,
* },
* 'cookies' : array<int, \WP_Http_Cookie>,
* 'filename' : string|null,
* 'http_response' : \WP_HTTP_Requests_Response
* }
*/
public function post( string $endpoint, array $params = [] );
/**
* Perform any other request.
*
* @param string $endpoint
* @param string $method
* @param array<string, mixed> $params
*
* @return WP_Error|array{
* 'body' : array<string, mixed>,
* 'headers' : CaseInsensitiveDictionary,
* 'response' : array{
* 'code' : int,
* 'message' : string,
* },
* 'cookies' : array<int, \WP_Http_Cookie>,
* 'filename' : string|null,
* 'http_response' : \WP_HTTP_Requests_Response
* }
*/
public function request( string $endpoint, string $method = 'GET', array $params = [] );
}

View File

@@ -0,0 +1,91 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\API\V3;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\API\V3\Auth\Auth_Url_Cache_Decorator;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\API\V3\Auth\Contracts\Auth_Url;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\API\V3\Auth\Contracts\Token_Authorizer;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\API\V3\Auth\Token_Authorizer_Cache_Decorator;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\API\V3\Contracts\Client_V3;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Config;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Contracts\Abstract_Provider;
use WP_Http;
final class Provider extends Abstract_Provider {
/**
* @inheritDoc
*/
public function register() {
$this->container->bind( Auth_Url::class, Auth_Url_Cache_Decorator::class );
$this->container->singleton( Client_V3::class, static function (): Client {
$prefix = 'stellarwp/uplink/' . Config::get_hook_prefix();
$api_root = '/api/stellarwp/v3/';
if ( defined( 'STELLARWP_UPLINK_V3_API_ROOT' ) && STELLARWP_UPLINK_V3_API_ROOT ) {
$api_root = STELLARWP_UPLINK_V3_API_ROOT;
}
$base_url = 'https://licensing.stellarwp.com';
if ( defined( 'STELLARWP_UPLINK_API_BASE_URL' ) && STELLARWP_UPLINK_API_BASE_URL ) {
$base_url = preg_replace( '!/$!', '', STELLARWP_UPLINK_API_BASE_URL );
}
/**
* Filter the V3 api root.
*
* @param string $api_root The base endpoint for the v3 API.
*/
$api_root = apply_filters( $prefix . '/v3/client/api_root', $api_root );
/**
* Filter the V3 api base URL.
*
* @param string $base_url The base URL for the v3 API.
*/
$base_url = apply_filters( $prefix . '/v3/client/base_url', $base_url );
$request_args = apply_filters( $prefix . '/v3/client/request_args', [
'headers' => [
'Content-Type' => 'application/json',
],
'timeout' => 15, // Seconds.
] );
return new Client( $api_root, $base_url, $request_args, new WP_Http() );
} );
$this->register_token_authorizer();
}
/**
* Based on the developer's configuration, determine if we will enable Token Authorization caching.
*
* @return void
*/
private function register_token_authorizer(): void {
$expiration = Config::get_auth_cache_expiration();
if ( $expiration >= 0 ) {
$this->container->bind(
Token_Authorizer::class,
static function ( $c ) use ( $expiration ): Token_Authorizer {
return new Token_Authorizer_Cache_Decorator(
$c->get( Auth\Token_Authorizer::class ),
$expiration
);
}
);
return;
}
$this->container->bind(
Token_Authorizer::class,
Auth\Token_Authorizer::class
);
}
}

View File

@@ -0,0 +1,553 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\API;
use stdClass;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Messages;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources\Resource;
class Validation_Response {
/**
* Validation response message.
*
* @since 1.0.0
*
* @var string
*/
protected $api_response_message;
/**
* Current resource key.
*
* @since 1.0.0
*
* @var string
*/
protected $current_key;
/**
* Daily limit from the validation.
*
* @since 1.0.0
*
* @var int
*/
protected $daily_limit;
/**
* Expiration from the validation.
*
* @since 1.0.0
*
* @var string
*/
protected $expiration;
/**
* Is response valid.
*
* @since 1.0.0
*
* @var bool
*/
protected $is_valid = true;
/**
* License key.
*
* @since 1.0.0
*
* @var string
*/
protected $key;
/**
* Replacement key.
*
* @since 1.0.0
*
* @var string|null
*/
protected $replacement_key;
/**
* Resource instance.
*
* @since 1.0.0
*
* @var Resource
*/
protected $resource;
/**
* Validation response.
*
* @since 1.0.0
*
* @var stdClass|null
*/
protected $response;
/**
* Result of the validation.
*
* @since 1.0.0
*
* @var string
*/
protected $result = 'success';
/**
* Validation type.
*
* @since 1.0.0
*
* @var string
*/
protected $validation_type;
/**
* Version from validation response.
*
* @since 1.0.0
*
* @var string
*/
protected $version;
/**
* Constructor.
*
* @since 1.0.0
*
* @param string|null $key License key.
* @param string $validation_type Validation type (local or network).
* @param stdClass|null $response Validation response.
* @param Resource $resource Resource instance.
*/
public function __construct( ?string $key, string $validation_type, ?stdClass $response, Resource $resource ) {
$this->key = $key ?: '';
$this->validation_type = 'network' === $validation_type ? 'network' : 'local';
$this->response = $response;
$this->resource = $resource;
if ( isset( $this->response->results ) ) {
$this->response = is_array( $this->response->results ) ? reset( $this->response->results ) : $this->response->results;
}
$this->parse();
}
/**
* Gets the daily limit from the validation response.
*
* @since 1.0.0
*
* @return int
*/
public function get_daily_limit() : int {
return $this->daily_limit;
}
/**
* Gets the validation response key.
*
* @since 1.0.0
*
* @return string
*/
public function get_key() : string {
return ! empty( $this->replacement_key ) ? $this->replacement_key : $this->key;
}
/**
* Gets the message from the validation response.
*
* @since 1.0.0
*
* @return Messages\Message_Abstract
*/
public function get_message() {
switch ( $this->result ) {
case 'unreachable':
$message = new Messages\Unreachable();
break;
case 'expired':
$message = new Messages\Expired_Key();
break;
case 'invalid':
case 'upgrade':
$message = new Messages\API( $this->api_response_message, $this->version, $this->resource );
break;
case 'success':
case 'new':
$message = $this->get_success_message();
break;
default:
$message = new Messages\Update_Available( $this->resource );
}
return $message;
}
/**
* Gets the network level message from the validation response.
*
* @since 1.0.0
*
* @return Messages\Message_Abstract
*/
public function get_network_message() {
$referer = wp_get_referer();
// If this request came from the network admin, show regular messaging.
if ( $referer && wp_doing_ajax() && str_contains( $referer, network_admin_url() ) ) {
return $this->get_message();
}
if ( $this->is_valid() ) {
return new Messages\Network_Licensed();
}
if ( 'expired' === $this->result ) {
return new Messages\Network_Expired();
}
return new Messages\Network_Unlicensed();
}
/**
* Gets the raw response from the validation request.
*
* @since 1.0.0
*
* @return stdClass
*/
public function get_raw_response(): ?stdClass {
return $this->response;
}
/**
* Gets the validation response result.
*
* @since 1.0.0
*
* @return string
*/
public function get_result() : string {
return $this->result;
}
/**
* Gets the success message of the validation response.
*
* @since 1.0.0
*
* @return Messages\Message_Abstract
*/
private function get_success_message() {
if ( ! empty( $this->api_response_message ) ) {
return new Messages\API( $this->api_response_message, $this->version, $this->resource );
}
return new Messages\Valid_Key( $this->expiration );
}
/**
* Get update details from the validation response.
*
* @since 1.0.0
*
* @return stdClass
*/
public function get_update_details(): stdClass {
$update = new stdClass;
if ( ! empty( $this->response->api_invalid ) ) {
return $this->handle_api_errors();
}
$id = $this->response->id ?? '';
$plugin = $this->response->plugin ?? '';
$slug = $this->response->slug ?? '';
if ( empty( $id ) ) {
$id = sprintf(
'stellarwp/plugins/%s',
empty( $slug ) ? $this->resource->get_slug() : $slug
);
}
if ( empty( $plugin ) ) {
$plugin = $this->resource->get_path();
}
$update->id = $id;
$update->plugin = $plugin;
$update->slug = $slug;
$update->new_version = $this->response->version ?? '';
$update->url = $this->response->homepage ?? '';
$update->tested = $this->response->tested ?? '';
$update->requires = $this->response->requires ?? '';
$update->package = ! empty( $this->response->download_url ) ? $this->response->download_url . '&key=' . urlencode( $this->get_key() ) : '';
if ( ! empty( $this->response->upgrade_notice ) ) {
$update->upgrade_notice = $this->response->upgrade_notice;
}
// Support custom $update properties coming straight from PUE
if ( ! empty( $this->response->custom_update ) ) {
$custom_update = get_object_vars( $this->response->custom_update );
foreach ( $custom_update as $field => $custom_value ) {
if ( is_object( $custom_value ) ) {
$custom_value = get_object_vars( $custom_value );
}
$update->$field = $custom_value;
}
}
return $update;
}
/**
* @return stdClass
*/
public function handle_api_errors() : stdClass {
$update = new stdClass;
$copy_fields = [
'id',
'slug',
'version',
'homepage',
'download_url',
'upgrade_notice',
'sections',
'plugin',
'api_expired',
'api_upgrade',
'api_invalid',
'api_invalid_message',
'api_inline_invalid_message',
'custom_update',
];
foreach ( $copy_fields as $field ) {
if ( ! isset( $this->response->$field ) ) {
continue;
}
$update->$field = $this->response->$field;
}
$update->license_error = $this->get_message()->get();
$update->slug = $this->resource->get_slug();
$update->new_version = $this->response->version ?? '';
$update->package = 'invalid_license';
return $update;
}
/**
* Get expiration details from response
*
* @return stdClass
*/
public function get_expire_details() : stdClass {
$update = new stdClass;
$update->version = $this->response->version ?: '';
$update->message = $this->response->api_invalid_message ?: '';
$update->inline_message = $this->response->api_inline_invalid_message ?: '';
$update->api_expired = $this->response->api_expired ?: '';
$update->sections = $this->response->sections ?: new stdClass;
return $update;
}
/**
* Gets the version from the validation response.
*
* @since 1.0.0
*
* @return string
*/
public function get_version() : string {
return $this->version ?: '';
}
/**
* Returns where or not the response has a replacement key.
*
* @since 1.0.0
*
* @return bool
*/
public function has_replacement_key() : bool {
return ! empty( $this->replacement_key );
}
/**
* Returns where or not the license key was valid.
*
* @since 1.0.0
*
* @return bool
*/
public function is_valid() : bool {
return $this->is_valid;
}
/**
* Set the is_valid value.
*
* @since 1.0.0
*
* @param bool $is_valid Whether the validation response should be set as valid or not.
*
* @return void
*/
public function set_is_valid( bool $is_valid ): void {
$this->is_valid = $is_valid;
}
/**
* Parses the response from the API.
*
* @since 1.0.0
*
* @return void
*/
private function parse(): void {
$this->current_key = $this->resource->get_license_key( $this->validation_type );
$this->expiration = $this->response->expiration ?? __( 'unknown date', '%TEXTDOMAIN%' );
if ( ! empty( $this->response->api_inline_invalid_message ) ) {
$this->api_response_message = wp_kses( $this->response->api_inline_invalid_message, 'post' );
}
if ( ! empty( $this->response->home_url ) ) {
$this->resource->set_home_url( $this->response->home_url );
}
if ( ! empty( $this->response->version ) ) {
$this->version = sanitize_text_field( $this->response->version );
}
$this->version = $this->version ?: $this->resource->get_version();
if ( null === $this->response ) {
$this->result = 'unreachable';
} elseif ( isset( $this->response->api_expired ) && 1 === (int) $this->response->api_expired ) {
$this->result = 'expired';
$this->set_is_valid( false );
} elseif ( isset( $this->response->api_upgrade ) && 1 === (int) $this->response->api_upgrade ) {
$this->result = 'upgrade';
$this->set_is_valid( false );
} elseif ( isset( $this->response->api_invalid ) && 1 === (int) $this->response->api_invalid ) {
$this->result = 'invalid';
$this->set_is_valid( false );
} else {
if ( isset( $this->response->api_message ) ) {
$this->api_response_message = wp_kses( $this->response->api_message, 'data' );
}
if ( isset( $this->response->daily_limit ) ) {
$this->daily_limit = intval( $this->response->daily_limit );
}
// If the license key is new or not the same as the one we have, mark it as a new key.
if ( ! ( $this->current_key && $this->current_key === $this->key ) ) {
$this->result = 'new';
}
}
if ( ! empty( $this->response->replacement_key ) ) {
$this->replacement_key = $this->response->replacement_key;
}
}
/**
* Transform plugin info into the format used by the native WordPress.org API
*
* @return StdClass
*/
public function to_wp_format(): stdClass {
$info = new StdClass;
// The custom update API is built so that many fields have the same name and format
// as those returned by the native WordPress.org API. These can be assigned directly.
$same_format = [
'name',
'slug',
'version',
'requires',
'tested',
'rating',
'upgrade_notice',
'num_ratings',
'downloaded',
'homepage',
'last_updated',
'api_expired',
'api_upgrade',
'api_invalid',
];
foreach ( $same_format as $field ) {
if ( isset( $this->$field ) ) {
$info->$field = $this->$field;
} else {
$info->$field = null;
}
}
//Other fields need to be renamed and/or transformed.
$info->download_link = $this->response->download_url ?? '';
if ( ! empty( $this->author_homepage ) && ! empty( $this->response->author ) ) {
$info->author = sprintf( '<a href="%s">%s</a>', esc_url( $this->author_homepage ), $this->response->author );
} else {
$info->author = $this->response->author ?? '';
}
if ( isset( $this->response->sections ) && is_object( $this->response->sections ) ) {
$info->sections = get_object_vars( $this->response->sections );
} elseif ( isset( $this->response->sections ) && is_array( $this->response->sections ) ) {
$info->sections = $this->response->sections;
} else {
$info->sections = [ 'description' => '' ];
}
$slug = ! empty( $info->slug ) ? $info->slug : 'unknown';
$info = apply_filters('stellarwp/uplink/' . $slug . '/to_wp_format', $info);
return $info;
}
/**
* Magic getter for the response properties.
*
* @param string $key Response value to fetch.
*
* @return mixed
*/
public function __get( $key ) {
if ( ! isset( $this->response->$key ) ) {
return null;
}
return $this->response->$key;
}
/**
* Magic isset for the response properties.
*
* @param string $key
*
* @return bool
*/
public function __isset( $key ) {
return isset( $this->response->$key );
}
}

View File

@@ -0,0 +1,83 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Admin;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\License\License_Manager;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources\Collection;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Utils;
class Ajax {
/**
* @var Collection
*/
protected $resources;
/**
* @var License_Field
*/
protected $field;
/**
* @var License_Manager
*/
protected $license_manager;
/**
* Constructor.
*
* @param Collection $resources The plugin/services collection.
* @param License_Field $field The license field.
* @param License_Manager $license_manager The license manager.
*/
public function __construct(
Collection $resources,
License_Field $field,
License_Manager $license_manager
) {
$this->resources = $resources;
$this->field = $field;
$this->license_manager = $license_manager;
}
/**
* @since 1.0.0
* @return void
*/
public function validate_license(): void {
$submission = [
'_wpnonce' => sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ?? '' ) ),
'slug' => sanitize_text_field( wp_unslash( $_POST['slug'] ?? '' ) ),
'key' => Utils\Sanitize::key( wp_unslash( $_POST['key'] ?? '' ) ),
];
if ( empty( $submission['key'] ) || ! wp_verify_nonce( $submission['_wpnonce'], $this->field->get_group_name() ) ) {
wp_send_json_error( [
'status' => 0,
'message' => __( 'Invalid request: nonce field is expired. Please try again.', '%TEXTDOMAIN%' ),
] );
}
$plugin = $this->resources->offsetGet( $submission['slug'] );
if ( ! $plugin ) {
wp_send_json_error( [
'message' => sprintf(
__( 'Error: The plugin with slug "%s" was not found. It is impossible to validate the license key, please contact the plugin author.', '%TEXTDOMAIN%' ),
$submission['slug']
),
'submission' => $submission,
] );
}
$network_validate = $this->license_manager->allows_multisite_license( $plugin );
$results = $plugin->validate_license( $submission['key'], $network_validate );
$message = $network_validate ? $results->get_network_message()->get() : $results->get_message()->get();
wp_send_json( [
'status' => absint( $results->is_valid() ),
'message' => $message,
] );
}
}

View File

@@ -0,0 +1,201 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Admin;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Config;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources\Collection;
abstract class Field {
public const STELLARWP_UPLINK_GROUP = 'stellarwp_uplink_group';
/**
* Path to page template
*
* @since 1.0.0
*
* @var string
*/
protected $path = '';
/**
* @since 1.0.0
*
* @return void
*/
abstract public function register_settings(): void;
/**
* Renders the field.
*
* @since 1.0.0
*
* @param bool $show_title Whether to show the title or not.
* @param bool $show_button Whether to show the submit button or not.
*
* @return void
*/
abstract public function render( bool $show_title = true, bool $show_button = true ): void;
/**
* @param array<string> $args
*
* @return void
*/
public function get_description( array $args = [] ): void {
if ( empty( $args['description'] ) ) {
return;
}
printf(
'<p class="regular-text">%s</p>',
esc_html( $args['description'] )
);
}
/**
* @param array<string> $args
*
* @return string
*/
public function get_html_content( array $args = [] ) : string {
if ( empty( $args['html'] ) ) {
return '';
}
return $args['html'];
}
/**
* @param string $group_modifier
*
* @return string
*/
public function get_group_name( string $group_modifier = '' ) : string {
$group_name = sprintf( '%s_%s', self::STELLARWP_UPLINK_GROUP, $group_modifier );
return apply_filters( 'stellarwp/uplink/' . Config::get_hook_prefix() . '/license_field_group_name', $group_name, self::STELLARWP_UPLINK_GROUP, $group_modifier );
}
/**
* @param array<string> $args
*
* @return void
*/
public function field_html( array $args = [] ): void {
$field = sprintf(
'<div class="%6$s" id="%2$s" data-slug="%2$s" data-plugin="%9$s" data-plugin-slug="%10$s" data-action="%11$s">
<fieldset class="stellarwp-uplink__settings-group">
<input type="%1$s" name="%3$s" value="%4$s" placeholder="%5$s" class="regular-text stellarwp-uplink__settings-field" />
%7$s
</fieldset>
%8$s
</div>',
esc_attr( $args['type'] ),
esc_attr( $args['path'] ),
esc_attr( $args['id'] ),
esc_attr( $args['value'] ),
esc_attr( $args['placeholder'] ),
esc_attr( $args['html_classes'] ?: '' ),
$this->get_html_content( $args ),
$this->add_nonce_field(),
esc_attr( $args['plugin'] ),
esc_attr( $args['plugin_slug'] ),
esc_attr( Config::get_hook_prefix_underscored() )
);
echo apply_filters( 'stellarwp/uplink/' . Config::get_hook_prefix() . '/license_field_html_render', $field, $args );
$this->get_description( $args );
}
/**
* @return string
*/
public function add_nonce_field() : string {
return '<input type="hidden" value="' . wp_create_nonce( self::get_group_name() ) . '" class="wp-nonce" />';
}
/**
* @param array<mixed> $context
*
* @return false|string
*/
protected function get_content( array $context = [] ) {
extract( $context );
ob_start();
include $this->get_path();
return ob_get_clean();
}
/**
* @return string
*/
public function get_path() : string {
return apply_filters( 'stellarwp/uplink/' . Config::get_hook_prefix() . '/field-template_path', dirname( __DIR__, 2 ) . $this->path, $this->path );
}
/**
* Get the collection of Plugins/Services.
*
* @return Collection
*/
protected function get_resources(): Collection {
return Config::get_container()->get( Collection::class );
}
/**
* Prints out the settings fields for a particular settings section.
*
* Part of the Settings API. Use this in a settings page to output
* a specific section. Should normally be called by do_settings_sections()
* rather than directly.
*
* @global array $wp_settings_fields Storage array of settings fields and their pages/sections.
*
* @since 1.0.0
*
* @param string $page Slug title of the admin page whose settings fields you want to show.
* @param string $section Slug title of the settings section whose fields you want to show.
* @param string $plugin_slug Slug title of the settings section whose fields you want to show.
* @param bool $show_title Whether to show the title or not.
*/
public function do_settings_fields( string $page, string $section, string $plugin_slug, bool $show_title = true ): void {
global $wp_settings_fields;
if ( ! isset( $wp_settings_fields[ $page ][ $section ] ) ) {
return;
}
foreach ( (array) $wp_settings_fields[ $page ][ $section ] as $field ) {
$class = '';
if ( ! empty( $field['args']['class'] ) ) {
$class = ' class="' . esc_attr( $field['args']['class'] ) . '"';
}
if ( ! empty( $plugin_slug ) ) {
$field['args']['slug'] = $plugin_slug;
}
if ( $show_title ) {
echo "<tr{$class}>";
if ( ! empty( $field['args']['label_for'] ) ) {
echo '<th scope="row"><label for="' . esc_attr( $field['args']['label_for'] ) . '">' . $field['title'] . '</label></th>';
} else {
echo '<th scope="row">' . $field['title'] . '</th>';
}
echo '<td>';
}
call_user_func( $field['callback'], $field['args'] );
if ( $show_title ) {
echo '</td>';
echo '</tr>';
}
}
}
}

View File

@@ -0,0 +1,178 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Admin;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\License\License_Manager;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Config;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources\Plugin;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources\Resource;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources\Service;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Uplink;
class License_Field extends Field {
public const LICENSE_FIELD_ID = 'stellarwp_uplink_license';
/**
* @var string
*/
protected $path = '/admin-views/fields/settings.php';
/**
* The license manager.
*
* @var License_Manager
*/
private $license_manager;
/**
* The script and style handle when registering assets for this field.
*
* @var string
*/
private $handle;
/**
* Constructor.
*
* @param License_Manager $license_manager
*
* @throws \RuntimeException
*/
public function __construct( License_Manager $license_manager ) {
$this->license_manager = $license_manager;
$this->handle = sprintf( 'stellarwp-uplink-license-admin-%s', Config::get_hook_prefix() );
}
/**
* @param Plugin|Service|Resource $plugin
*
* @return string
*/
public static function get_section_name( $plugin ) : string {
return sprintf( '%s_%s', self::LICENSE_FIELD_ID, sanitize_title( $plugin->get_slug() ) );
}
/**
* @since 1.0.0
*
* @return void
*/
public function register_settings(): void {
foreach ( $this->get_resources() as $resource ) {
add_settings_section(
self::get_section_name( $resource ),
'',
[ $this, 'description' ], // @phpstan-ignore-line
$this->get_group_name( sanitize_title( $resource->get_slug() ) )
);
register_setting(
$this->get_group_name( sanitize_title( $resource->get_slug() ) ),
$resource->get_license_object()->get_key_option_name()
);
$network = $this->license_manager->allows_multisite_license( $resource );
add_settings_field(
$resource->get_license_object()->get_key_option_name(),
__( 'License Key', '%TEXTDOMAIN%' ),
[ $this, 'field_html' ],
$this->get_group_name( sanitize_title( $resource->get_slug() ) ),
self::get_section_name( $resource ),
[
'id' => $resource->get_license_object()->get_key_option_name(),
'label_for' => $resource->get_license_object()->get_key_option_name(),
'type' => 'text',
'path' => $resource->get_path(),
'value' => $resource->get_license_key( $network ? 'network' : 'any' ),
'placeholder' => __( 'License Number', '%TEXTDOMAIN%' ),
'html' => $this->get_field_html( $resource ),
'html_classes' => 'stellarwp-uplink-license-key-field',
'plugin' => $resource->get_path(),
'plugin_slug' => $resource->get_slug(),
]
);
}
}
/**
* @since 1.0.0
*
* @param Plugin|Service|Resource $plugin
*
* @return string
*/
public function get_field_html( $plugin ) : string {
$html = sprintf( '<p class="tooltip description">%s</p>', __( 'A valid license key is required for support and updates', '%TEXTDOMAIN%' ) );
$html .= '<div class="license-test-results"><img src="' . esc_url( admin_url( 'images/wpspin_light.gif' ) ) . '" class="ajax-loading-license" alt="Loading" style="display: none"/>';
$html .= '<div class="key-validity"></div></div>';
return apply_filters( 'stellarwp/uplink/' . Config::get_hook_prefix() . '/license_field_html', $html, $plugin->get_slug() );
}
/**
* Renders a license field for all registered Resources.
*
* @inheritDoc
*/
public function render( bool $show_title = true, bool $show_button = true ): void {
foreach ( $this->get_resources() as $resource ) {
$this->render_single( $resource->get_slug(), $show_title, $show_button );
}
}
/**
* Renders a single resource's license field.
*
* @param string $plugin_slug The plugin slug to render.
* @param bool $show_title Whether to show the title or not.
* @param bool $show_button Whether to show the submit button or not.
*
* @return void
*/
public function render_single( string $plugin_slug, bool $show_title = true, bool $show_button = true ): void {
$this->enqueue_assets();
$resource = $this->get_resources()->offsetGet( $plugin_slug );
if ( ! $resource ) {
return;
}
echo $this->get_content( [
'plugin' => $resource,
'show_title' => $show_title,
'show_button' => $show_button,
] );
}
/**
* @since 1.0.0
*
* @return void
*/
public function register_assets(): void {
$path = Config::get_container()->get( Uplink::UPLINK_ASSETS_URI );
$js_src = apply_filters( 'stellarwp/uplink/' . Config::get_hook_prefix() . '/admin_js_source', $path . '/js/key-admin.js' );
wp_register_script( $this->handle, $js_src, [ 'jquery' ], '1.0.0', true );
$action_postfix = Config::get_hook_prefix_underscored();
wp_localize_script( $this->handle, sprintf( 'stellarwp_config_%s', $action_postfix ), [ 'action' => sprintf( 'pue-validate-key-uplink-%s', $action_postfix ) ] );
$css_src = apply_filters( 'stellarwp/uplink/' . Config::get_hook_prefix() . '/admin_css_source', $path . '/css/main.css' );
wp_register_style( $this->handle, $css_src );
}
/**
* Enqueue the registered scripts and styles, only when rendering fields.
*
* @return void
*/
protected function enqueue_assets(): void {
wp_enqueue_script( $this->handle );
wp_enqueue_style( $this->handle );
}
}

View File

@@ -0,0 +1,115 @@
<?php
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Admin;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Config;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Messages\Expired_Key;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Messages\Unlicensed;
class Notice {
const INVALID_KEY = 'invalid_key';
const UPGRADE_KEY = 'upgrade_key';
const EXPIRED_KEY = 'expired_key';
const STORE_KEY = 'stellarwp_uplink_key_notices';
/**
* @var array<mixed>
*/
protected $saved_notices = [];
/**
* @var array<mixed>
*/
protected $notices = [];
/**
* @since 1.0.0
*
* @return void
*/
public function setup_notices() {
if ( empty( $this->notices ) ) {
return;
}
foreach ( $this->notices as $notice_type => $plugin ) {
$message = null;
switch ( $notice_type ) {
case self::EXPIRED_KEY:
$message = new Expired_Key();
break;
case self::INVALID_KEY:
$message = new Unlicensed();
break;
}
if ( empty( $message ) ) {
continue;
}
echo $message;
}
}
/**
* @since 1.0.0
*
* @param string $plugin_name
*
* @param string $notice_type
*
* @return void
*/
public function add_notice( string $notice_type, string $plugin_name ) {
$this->clear_notices( $plugin_name, true );
$this->notices[ $notice_type ][ $plugin_name ] = true;
$this->save_notices();
}
/**
* Removes any notifications for the specified plugin.
*
* Useful when a valid license key is detected for a plugin, where previously
* it might have been included under a warning notification.
*
* If the optional second param is set to true then this change will not
* immediately be committed to storage (useful if we know this will happen in
* any case later on in the same request).
*
* @param string $plugin_name
* @param bool $defer_saving_change = false
*
* @return void
*/
public function clear_notices( string $plugin_name, bool $defer_saving_change = false ) {
foreach ( $this->notices as $notice_type => &$list_of_plugins ) {
unset( $list_of_plugins[ $plugin_name ] );
}
if ( ! $defer_saving_change ) {
$this->save_notices();
}
}
/**
* Saves any license key notices already added.
*
* @since 1.0.0
*
* @return void
*/
public function save_notices() {
update_option( self::STORE_KEY, $this->notices );
/**
* Fires after PUE license key notices have been saved.
*
* @param array $current_notices
* @param array $previously_saved_notices
*/
do_action( 'stellarwp/uplink/' . Config::get_hook_prefix() . '/notices_save_notices', $this->notices, $this->saved_notices );
}
}

View File

@@ -0,0 +1,215 @@
<?php
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Admin;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\API;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Config;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources;
use WP_Error;
use WP_Upgrader;
class Package_Handler {
/**
* @var WP_Upgrader
*/
public $upgrader;
/**
* Filters the package download step to store the downloaded file with a shorter file name.
*
* @param bool|WP_Error $reply Whether to bail without returning the package.
* Default false.
* @param string|null $package The package file name or URL.
* @param WP_Upgrader $upgrader The WP_Upgrader instance.
* @param array $hook_extra Extra arguments passed to hooked filters.
*
* @return string|bool|WP_Error
*/
public function filter_upgrader_pre_download( $reply, $package, WP_Upgrader $upgrader, $hook_extra ) {
if ( empty( $package ) || 'invalid_license' === $package ) {
return new WP_Error(
'download_failed',
__( 'Failed to update plugin. Check your license details first.', '%TEXTDOMAIN%' ),
''
);
}
if ( $this->is_uplink_package_url( $package, $hook_extra ) ) {
$this->upgrader = $upgrader;
return $this->download( $package );
}
return $reply;
}
/**
* Filters the source file location.
*
* @since 1.0.0
*
* @param array<mixed> $result Result of the upgrader process.
* @param array<mixed> $extras Extra args for the upgrader process.
*
* @return array
*/
public function filter_upgrader_install_package_result( $result, $extras ) {
global $wp_filesystem;
if ( ! isset( $extras['plugin'] ) ) {
return $result;
}
$plugin = $extras['plugin'];
// Bail if we are not dealing with a plugin we own.
if ( ! $this->is_uplink_package( $plugin ) ) {
return $result;
}
$containing_dir = dirname( $result['remote_destination'] );
$intended_dir = dirname( $plugin );
$actual_dir = basename( $result['remote_destination'] );
// @phpstan-ignore-next-line
$protected_directories = [ ABSPATH, WP_CONTENT_DIR, WP_PLUGIN_DIR, WP_CONTENT_DIR . '/themes' ];
if (
$intended_dir !== $actual_dir
&& ! in_array( $containing_dir . '/' . $actual_dir, $protected_directories, true )
&& ! in_array( $containing_dir . '/' . $intended_dir, $protected_directories, true )
) {
$wp_filesystem->move( $containing_dir . '/' . $actual_dir, $containing_dir . '/' . $intended_dir );
$result['remote_destination'] = $containing_dir . '/' . $intended_dir;
activate_plugin( $plugin );
}
return $result;
}
/**
* Whether the current package is an StellarWP product or not.
*
* @param string $plugin The plugin file relative to the plugins dir.
*
* @return bool
*/
protected function is_uplink_package( string $plugin ) : bool {
if ( empty( $plugin ) ) {
return false;
}
$container = Config::get_container();
$resource = $container->get( Resources\Collection::class )->get_by_path( $plugin );
return (bool) $resource->count();
}
/**
* Whether the current package is an StellarWP product or not.
*
* @param string $package The package file name or URL.
* @param array $hook_extra Extra arguments passed to hooked filters.
*
* @return bool
*/
protected function is_uplink_package_url( string $package, $hook_extra ) : bool {
if ( empty( $hook_extra['plugin'] ) ) {
return false;
}
if (
empty( $package )
|| ! preg_match( '!^(http|https|ftp)://!i', $package )
) {
return false;
}
$query_vars = parse_url( $package, PHP_URL_QUERY );
if ( empty( $query_vars ) ) {
return false;
}
if ( ! $this->is_uplink_package( $hook_extra['plugin'] ) ) {
return false;
}
$container = Config::get_container();
$api_base_url = $container->get( API\Client::class )->get_api_base_url();
return preg_match( '!^' . preg_quote( $api_base_url, '!' ) . '!i', $package );
}
/**
* A mimic of the `WP_Upgrader::download_package` method that adds a step to store the temp file with a shorter
* file name.
*
* @see WP_Upgrader::download_package()
*
* @param string $package The URI of the package. If this is the full path to an
* existing local file, it will be returned untouched.
*
* @return string|bool|WP_Error The full path to the downloaded package file, or a WP_Error object.
*/
protected function download( string $package ) {
if ( empty( $this->filesystem ) ) {
// try to connect
// @phpstan-ignore-next-line
$this->upgrader->fs_connect( [ WP_CONTENT_DIR, WP_PLUGIN_DIR ] );
global $wp_filesystem;
// still empty?
if ( empty( $wp_filesystem ) ) {
// bail
return false;
}
// @phpstan-ignore-next-line
$this->filesystem = $wp_filesystem;
}
$this->upgrader->skin->feedback( 'downloading_package', $package );
$download_file = download_url( $package );
if ( is_wp_error( $download_file ) ) {
return new WP_Error(
'download_failed',
$this->upgrader->strings['download_failed'],
$download_file->get_error_message()
);
}
$file = $this->get_short_filename( $download_file );
$moved = $this->filesystem->move( $download_file, $file );
if ( empty( $moved ) ) {
// We tried, we failed, we bail and let WP do its job
return false;
}
return $file;
}
/**
* Returns the absolute path to a shorter filename version of the original download temp file.
*
* The path will point to the same temp dir (WP handled) but shortening the filename to a
* 6 chars hash to cope with OSes limiting the max number of chars in a file path.
* The original filename would be a sanitized version of the URL including query args.
*
* @param string $download_file The absolute path to the original download file.
*
* @return string The absolute path to a shorter name version of the downloaded file.
*/
protected function get_short_filename( string $download_file ) : string {
$extension = pathinfo( $download_file, PATHINFO_EXTENSION );
$filename = substr( md5( $download_file ), 0, 5 );
$file = dirname( $download_file ) . '/' . $filename . '.' . $extension;
return $file;
}
}

View File

@@ -0,0 +1,226 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Admin;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Config;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources\Collection;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources\Plugin;
use Throwable;
class Plugins_Page {
/**
* Storing the `plugin_notice` message for each plugin.
*
* @var array<string, array{slug: string, message_row_html: string}>
*/
private $plugin_notices = [];
/**
* The memoization cache for existing plugins.
*
* @var ?Collection<Plugin>
*/
private $plugins;
/**
* Displays messages on the plugins page in the dashboard.
*
* @since 1.0.0
*
* @param string $page
*
* @return void
*/
public function display_plugin_messages( string $page ): void {
if ( 'plugins.php' !== $page ) {
return;
}
$messages = [];
$plugins = $this->get_plugins();
$plugin_updates = get_plugin_updates();
foreach ( $plugins as $plugin ) {
$plugin_file = $plugin->get_path();
$resource = $plugin_updates[ $plugin_file ] ?? null;
if ( empty( $resource ) ) {
continue;
}
if ( ! empty( $resource->update->license_error ) ) {
$messages[] = $resource->update->license_error;
}
if ( empty( $messages ) ) {
continue;
}
$message_row_html = '';
foreach ( $messages as $message ) {
$message_row_html .= sprintf(
'<div class="update-message notice inline notice-warning notice-alt">%s</div>',
$message
);
}
$message_row_html = sprintf(
'<tr class="plugin-update-tr active"><td colspan="4" class="plugin-update">%s</td></tr>',
$message_row_html
);
$this->plugin_notices[ $plugin->get_slug() ] = [
'slug' => $plugin->get_slug(),
'message_row_html' => $message_row_html,
];
}
}
/**
* Get plugin notices.
*
* @since 1.0.0
*
* @return array<string, array{slug: string, message_row_html: string}>
*/
public function get_plugin_notices(): array {
return apply_filters( 'stellarwp/uplink/' . Config::get_hook_prefix() . '/plugin_notices', $this->plugin_notices );
}
/**
* Add notices as JS variable
*
* @param string $page
*
* @return void
*/
public function store_admin_notices( string $page ): void {
if ( 'plugins.php' !== $page ) {
return;
}
add_action( 'admin_footer', [ $this, 'output_notices_script' ] );
}
/**
* Output the plugin-specific notices script.
*
* @since 1.0.0
*
* @return void
*/
public function output_notices_script(): void {
$notices = $this->get_plugin_notices();
if ( empty( $notices ) ) {
return;
}
foreach ( $this->get_plugins() as $resource ) :
$notice = $notices[ $resource->get_slug() ] ?? null;
if ( ! $notice ) {
continue;
}
?>
<script>
/**
* Appends license key notifications inline within the plugin table.
*
* This is done via JS because the options for achieving the same things
* server-side are currently limited.
*/
(function( $, my ) {
'use strict';
my.init = function() {
var $active_plugin_row = $( 'tr.active[data-slug="<?php echo esc_attr( $resource->get_slug() ); ?>"]' );
if ( ! $active_plugin_row.length ) {
return;
}
var notice = <?php echo wp_json_encode( $notice ); ?>;
if ( ! notice.message_row_html ) {
return;
}
// Add the .update class to the plugin row and append our new row with the update message
$active_plugin_row.addClass( 'update' ).after( notice.message_row_html );
};
$( function() {
my.init();
} );
})( jQuery, {} );
</script>
<?php
endforeach;
}
/**
* @param mixed $transient
*
* @return mixed
*/
public function check_for_updates( $transient ) {
try {
/** @var Plugin $resource */
foreach ( $this->get_plugins() as $resource ) {
$transient = $resource->check_for_updates( $transient );
}
} catch ( Throwable $exception ) {
return $transient;
}
return $transient;
}
/**
* Get the collection of Plugins/Services.
*
* @return Collection<Plugin>
*/
protected function get_plugins(): Collection {
if ( isset( $this->plugins ) ) {
return $this->plugins;
}
return $this->plugins = Config::get_container()->get( Collection::class )->get_plugins();
}
/**
* Intercept plugins_api() calls that request information about our plugin and
* use the configured API endpoint to satisfy them.
*
* @see plugins_api()
*
* @param mixed $result
* @param string|null $action
* @param array<mixed>|object|null $args
*
* @return mixed
*/
public function inject_info( $result, ?string $action = null, $args = null ) {
$relevant = ( 'plugin_information' === $action ) && is_object( $args ) && ! empty( $args->slug );
if ( ! $relevant ) {
return $result;
}
if ( apply_filters( 'stellarwp/uplink/' . $args->slug . '/prevent_update_check', false ) ) {
return $result;
}
$plugin = $this->get_plugins()->offsetGet( $args->slug );
if ( ! $plugin ) {
return $result;
}
return $plugin->validate_license()->to_wp_format();
}
}

View File

@@ -0,0 +1,202 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Admin;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Config;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Contracts\Abstract_Provider;
class Provider extends Abstract_Provider {
/**
* Register the service provider.
*
* @since 1.0.0
*
* @return void
*/
public function register() {
$this->container->singleton( Plugins_Page::class, Plugins_Page::class );
$this->container->singleton( License_Field::class, License_Field::class );
$this->container->singleton( Notice::class, Notice::class );
$this->container->singleton( Ajax::class, Ajax::class );
$this->container->singleton( Package_Handler::class, Package_Handler::class );
$this->container->singleton( Update_Prevention::class, Update_Prevention::class );
$this->register_hooks();
}
/**
* Register the hooks for the service provider.
*
* @since 1.0.0
*
* @return void
*/
public function register_hooks() {
add_filter( 'plugins_api', [ $this, 'filter_plugins_api' ], 10, 3 );
add_filter( 'pre_set_site_transient_update_plugins', [ $this, 'filter_pre_set_site_transient_update_plugins' ], 10, 1 );
add_filter( 'upgrader_pre_download', [ $this, 'filter_upgrader_pre_download' ], 5, 4 );
add_filter( 'upgrader_install_package_result', [ $this, 'filter_upgrader_install_package_result' ], 10, 2 );
add_filter( 'upgrader_source_selection', [ $this, 'filter_upgrader_source_selection_for_update_prevention' ], 15, 4 );
$action = sprintf( 'wp_ajax_pue-validate-key-uplink-%s', Config::get_hook_prefix_underscored() );
add_action($action, [ $this, 'ajax_validate_license' ], 10, 0 );
add_action( 'admin_init', [ $this, 'admin_init' ], 10, 0 );
add_action( 'admin_enqueue_scripts', [ $this, 'display_plugin_messages' ], 1, 1 );
add_action( 'admin_enqueue_scripts', [ $this, 'register_assets' ], 10, 0 );
add_action( 'admin_enqueue_scripts', [ $this, 'store_admin_notices' ], 10, 1 );
add_action( 'admin_notices', [ $this, 'admin_notices' ], 10, 0 );
}
/**
* Filter the plugins API response.
*
* @since 1.0.0
*
* @param mixed $result
* @param string $action
* @param array<mixed>|object $args
*
* @return mixed
*/
public function filter_plugins_api( $result, $action, $args ) {
return $this->container->get( Plugins_Page::class )->inject_info( $result, $action, $args );
}
/**
* Filter the plugins transient.
*
* @since 1.0.0
*
* @param object $transient
*
* @return mixed
*/
public function filter_pre_set_site_transient_update_plugins( $transient ) {
return $this->container->get( Plugins_Page::class )->check_for_updates( $transient );
}
/**
* Validate the license.
*
* @since 1.0.0
*
* @return void
*/
public function ajax_validate_license(): void {
$this->container->get( Ajax::class )->validate_license();
}
/**
* Hooked to the admin_init action. Register the settings.
*
* @since 1.0.0
*
* @return void
*/
public function admin_init(): void {
if ( wp_doing_ajax() ) {
return;
}
$this->container->get( License_Field::class )->register_settings();
}
/**
* Hooked to the admin_enqueue_scripts action. Register assets.
*
* @since 1.0.0
*
* @return void
*/
public function register_assets(): void {
$this->container->get( License_Field::class )->register_assets();
}
/**
* Hooked to the admin_notices action. Sets up notices.
*
* @since 1.0.0
*
* @return void
*/
public function admin_notices(): void {
$this->container->get( Notice::class )->setup_notices();
}
/**
* Display plugin messages.
*
* @since 1.0.0
*
* @param mixed $page
*
* @return void
*/
public function display_plugin_messages( $page ): void {
$this->container->get( Plugins_Page::class )->display_plugin_messages( (string) $page );
}
/**
* Store admin notices.
*
* @since 1.0.0
*
* @param mixed $page
*
* @return void
*/
public function store_admin_notices( $page ): void {
$this->container->get( Plugins_Page::class )->store_admin_notices( (string) $page );
}
/**
* Filter the upgrader pre download.
*
* @since 1.0.0
*
* @param bool|\WP_Error $reply Whether to bail without returning the package.
* Default false.
* @param string|null $package The package file name or URL.
* @param \WP_Upgrader $upgrader The WP_Upgrader instance.
* @param array $hook_extra Extra arguments passed to hooked filters.
*
* @return string|bool|\WP_Error
*/
public function filter_upgrader_pre_download( $reply, $package, $upgrader, $hook_extra ) {
return $this->container->get( Package_Handler::class )->filter_upgrader_pre_download( $reply, $package, $upgrader, $hook_extra );
}
/**
* Filter the upgrader source selection to handle final destination dir name.
*
* @since 1.0.0
*
* @param array $result Final arguments for the result.
* @param array $extras Extra arguments passed to hooked filters.
*
* @return array
*/
public function filter_upgrader_install_package_result( $result, $extras ) {
return $this->container->get( Package_Handler::class )->filter_upgrader_install_package_result( $result, $extras );
}
/**
* Filter the upgrader source selection to handle Update Prevention.
*
* @since 1.0.0
*
* @param string|\WP_Error $source File source location or a WP_Error.
* @param mixed $remote_source Remote file source location.
* @param \WP_Upgrader $upgrader WP_Upgrader instance.
* @param array $extras Extra arguments passed to hooked filters.
*
* @return string|\WP_Error
*/
public function filter_upgrader_source_selection_for_update_prevention( $source, $remote_source, $upgrader, $extras ) {
if ( is_wp_error( $source ) ) {
return $source;
}
return $this->container->get( Update_Prevention::class )->filter_upgrader_source_selection( $source, $remote_source, $upgrader, $extras );
}
}

View File

@@ -0,0 +1,96 @@
<?php
declare (strict_types=1);
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Admin;
use KadenceWP\KadenceBlocks\StellarWP\ContainerContract\ContainerInterface;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Config;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources\Collection;
use WP_Error;
use WP_Upgrader;
/**
* Class Update_Prevention engine for a plugin with invalid/empty keys
*
* @package \KadenceWP\KadenceBlocks\StellarWP\Uplink\Admin;
*/
class Update_Prevention
{
/**
* @var ContainerInterface
*/
protected $container;
public function __construct()
{
$this->container = Config::get_container();
}
/**
* Checks for the list of constants associate with plugin to make sure we are dealing
* with a plugin owned by the plugin using this library.
*
* @since 4.9.12
*
* @param string $plugin Plugin file partial path, folder and main php file.
*
* @return bool
*/
public function is_stellar_uplink_resource(string $plugin): bool
{
$collection = $this->container->get(Collection::class);
$resources = $collection->get_by_path($plugin);
if (!$resources->count()) {
return false;
}
return (bool) $collection->get_plugins($resources)->count();
}
/**
* Filters the source file location for the upgrade package for the PUE Update_Prevention engine.
*
* @since 4.9.12
*
* @param string|WP_Error $source File source location.
* @param mixed $remote_source Remote file source location.
* @param WP_Upgrader $upgrader WP_Upgrader instance.
* @param array<mixed> $extras Extra arguments passed to hooked filters.
*
* @return string|WP_Error
*/
public function filter_upgrader_source_selection($source, $remote_source, WP_Upgrader $upgrader, array $extras)
{
if (!isset($extras['plugin'])) {
return $source;
}
$plugin = $extras['plugin'];
// Bail if we are not dealing with a plugin we own.
if (!$this->is_stellar_uplink_resource($plugin)) {
return $source;
}
$incompatible_plugins = apply_filters('stellarwp/uplink/' . Config::get_hook_prefix() . '/update_prevention_incompatible_plugins', [], $source, $remote_source);
// Bail when there are no incompatible plugins.
if (empty($incompatible_plugins)) {
return $source;
}
/**
* Filter if we should prevent the update.
*
* @since 4.9.12
*
* @param bool $should_revent Flag false to skip the prevention.
* @param string $plugin Plugin core file path
* @param array $incompatible_plugins Which plugins were incompatible with new version of the plugin.
* @param string $source File source location.
* @param string $remote_source Remote file source location.
* @param WP_Upgrader $upgrader WP_Upgrader instance.
* @param array $extra Extra arguments passed to hooked filters.
*/
$should_prevent_update = apply_filters('stellarwp/uplink/' . Config::get_hook_prefix() . '/should_prevent_update_without_license', true, $plugin, $incompatible_plugins, $source, $remote_source, $upgrader, $extras);
// Bail if the filter above returns anything but true.
if (true !== $should_prevent_update) {
return $source;
}
$full_plugin_path = $remote_source . '/' . $plugin;
$plugin_data = get_plugin_data($full_plugin_path);
$link_read_more = '<a href="http://evnt.is/1aev" target="_blank">' . esc_html__('Read more', '%TEXTDOMAIN%') . '.</a>';
$message = sprintf(esc_html__('Your update failed due to an incompatibility between the version (%1$s) of the %2$s you tried to update to. %3$s', '%TEXTDOMAIN%'), esc_html($plugin_data['Version']), esc_html($plugin_data['Name']), $link_read_more);
return new WP_Error('stellarwp-uplink-updater-failed-prevention', $message, []);
}
}

View File

@@ -0,0 +1,122 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\Admin\Connect_Controller;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\Admin\Disconnect_Controller;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Config;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources\Collection;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources\Resource;
/**
* Manages Token Authorization WordPress actions to connect/disconnect
* tokens.
*/
final class Action_Manager {
public const ACTION = 'admin_action';
/**
* @var Disconnect_Controller
*/
private $disconnect_controller;
/**
* @var Connect_Controller
*/
private $connect_controller;
/**
* @var Collection
*/
private $resources;
/**
* @param Disconnect_Controller $disconnect_controller
* @param Connect_Controller $connect_controller
* @param Collection $resources
*/
public function __construct(
Disconnect_Controller $disconnect_controller,
Connect_Controller $connect_controller,
Collection $resources
) {
$this->disconnect_controller = $disconnect_controller;
$this->connect_controller = $connect_controller;
$this->resources = $resources;
}
/**
* Get the resource's unique hook name.
*
* @param Resource $resource The resource.
*
* @throws \RuntimeException
*
* @return string
*/
public function get_hook_name( Resource $resource ): string {
return sprintf( 'stellarwp/uplink/%s/%s_%s',
Config::get_hook_prefix(),
self::ACTION,
$resource->get_slug()
);
}
/**
* Register a unique action for each resource in order to fire off connect/disconnect logic
* uniquely so as one plugin would not interfere with another.
*
* @action admin_init
*
* @throws \RuntimeException
*
* @return void
*/
public function add_actions(): void {
foreach ( $this->resources as $resource ) {
$hook_name = $this->get_hook_name( $resource );
add_action(
$hook_name,
[ $this->disconnect_controller, 'maybe_disconnect' ]
);
add_action(
$hook_name,
[ $this->connect_controller, 'maybe_store_token_data' ]
);
}
}
/**
* When an `uplink_slug` query parameter is available, fire off the appropriate
* resource action.
*
* @action current_screen
*
* @throws \RuntimeException
*
* @return void
*/
public function do_action(): void {
if ( empty( $_REQUEST[ Disconnect_Controller::SLUG ] ) ) {
return;
}
$action = $_REQUEST[ Disconnect_Controller::SLUG ];
/**
* Fires when an 'uplink_slug' request variable is sent.
*
* The dynamic portion of the hook name, `$action`, refers to
* the action derived from the `GET` or `POST` request.
*/
do_action( sprintf( 'stellarwp/uplink/%s/%s_%s',
Config::get_hook_prefix(),
self::ACTION,
$action
) );
}
}

View File

@@ -0,0 +1,183 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\Admin;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\Authorizer;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\License\License_Manager;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\Nonce;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\Token\Connector;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\Token\Exceptions\InvalidTokenException;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Notice\Notice_Handler;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Notice\Notice;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources\Collection;
/**
* Handles storing token data after successfully redirecting
* back from an Origin site that has authorized their license.
*/
final class Connect_Controller {
public const TOKEN = 'uplink_token';
public const LICENSE = 'uplink_license';
public const SLUG = 'uplink_slug';
public const NONCE = '_uplink_nonce';
/**
* @var Connector
*/
private $connector;
/**
* @var Notice_Handler
*/
private $notice;
/**
* @var Collection
*/
private $collection;
/**
* @var License_Manager
*/
private $license_manager;
/**
* @var Authorizer
*/
private $authorizer;
public function __construct(
Connector $connector,
Notice_Handler $notice,
Collection $collection,
License_Manager $license_manager,
Authorizer $authorizer
) {
$this->connector = $connector;
$this->notice = $notice;
$this->collection = $collection;
$this->license_manager = $license_manager;
$this->authorizer = $authorizer;
}
/**
* Store the token data passed back from the Origin site.
*
* @action stellarwp/uplink/{$prefix}/admin_action_{$slug}
*
* @throws \RuntimeException
*/
public function maybe_store_token_data(): void {
if ( ! is_admin() || wp_doing_ajax() ) {
return;
}
$args = array_intersect_key( $_GET, [
self::TOKEN => true,
self::NONCE => true,
self::LICENSE => true,
self::SLUG => true,
] );
if ( ! $args ) {
return;
}
if ( ! $this->authorizer->can_auth() ) {
$this->notice->add( new Notice( Notice::ERROR,
__( 'Sorry, you do not have permission to connect a token.', '%TEXTDOMAIN%' ),
true
) );
return;
}
if ( ! Nonce::verify( $args[ self::NONCE ] ?? '' ) ) {
if ( ! function_exists( 'is_plugin_active' ) ) {
require_once ABSPATH . 'wp-admin/includes/plugin.php';
}
// The Litespeed plugin allows completely disabling transients for some reason...
if ( is_plugin_active( 'litespeed-cache/litespeed-cache.php' ) ) {
$this->notice->add( new Notice( Notice::ERROR,
sprintf(
__( 'The Litespeed plugin was detected, ensure "Store Transients" is set to ON and try again. See the <a href="%s" target="_blank">Litespeed documentation</a> for more information.', '%TEXTDOMAIN%' ),
esc_url( 'https://docs.litespeedtech.com/lscache/lscwp/cache/#store-transients' )
),
true
) );
}
$this->notice->add( new Notice( Notice::ERROR,
__( 'Unable to save token data: nonce verification failed.', '%TEXTDOMAIN%' ),
true
) );
return;
}
$slug = $args[ self::SLUG ] ?? '';
$plugin = $this->collection->offsetGet( $slug );
if ( ! $plugin ) {
$this->notice->add( new Notice( Notice::ERROR,
__( 'Plugin or Service slug not found.', '%TEXTDOMAIN%' ),
true
) );
return;
}
try {
if ( ! $this->connector->connect( $args[ self::TOKEN ] ?? '', $plugin ) ) {
$this->notice->add( new Notice( Notice::ERROR,
__( 'Error storing token.', '%TEXTDOMAIN%' ),
true
) );
return;
}
} catch ( InvalidTokenException $e ) {
$this->notice->add( new Notice( Notice::ERROR,
sprintf( '%s.', $e->getMessage() ),
true
) );
return;
}
$license = $args[ self::LICENSE ] ?? '';
// Store or override an existing license.
if ( $license ) {
$network = $this->license_manager->allows_multisite_license( $plugin );
$response = $plugin->validate_license( $license, $network );
if ( ! $response->is_valid() ) {
$this->notice->add( new Notice( Notice::ERROR,
__( 'Provided license key is not valid.', '%TEXTDOMAIN%' ),
true
) );
return;
}
if ( ! $plugin->set_license_key( $license, $network ? 'network' : 'local' ) ) {
$this->notice->add( new Notice( Notice::ERROR,
__( 'Error storing license key.', '%TEXTDOMAIN%' ),
true
) );
return;
}
}
$this->notice->add(
new Notice( Notice::SUCCESS,
__( 'Connected successfully.', '%TEXTDOMAIN%' ),
true
)
);
}
}

View File

@@ -0,0 +1,165 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\Admin;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\API\V3\Auth\Token_Authorizer_Cache_Decorator;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\Authorizer;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\Token\Disconnector;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\Token\Token_Factory;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Notice\Notice_Handler;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Notice\Notice;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources\Resource;
final class Disconnect_Controller {
public const ARG = 'uplink_disconnect';
public const SLUG = 'uplink_slug';
public const CACHE_KEY = 'uplink_cache';
/**
* @var Authorizer
*/
private $authorizer;
/**
* @var Disconnector
*/
private $disconnect;
/**
* @var Notice_Handler
*/
private $notice;
/**
* @var Token_Factory
*/
private $token_factory;
/**
* @var Token_Authorizer_Cache_Decorator
*/
private $cache;
/**
* @param Authorizer $authorizer The authorizer.
* @param Disconnector $disconnect Disconnects a Token, if the user has the capability.
* @param Notice_Handler $notice Handles storing and displaying notices.
* @param Token_Factory $token_factory The token factory.
* @param Token_Authorizer_Cache_Decorator $cache The token cache.
*/
public function __construct(
Authorizer $authorizer,
Disconnector $disconnect,
Notice_Handler $notice,
Token_Factory $token_factory,
Token_Authorizer_Cache_Decorator $cache
) {
$this->authorizer = $authorizer;
$this->disconnect = $disconnect;
$this->notice = $notice;
$this->token_factory = $token_factory;
$this->cache = $cache;
}
/**
* Get the disconnect URL to render.
*
* @param Resource $plugin The plugin/service.
*
* @return string
*/
public function get_url( Resource $plugin ): string {
$token = $this->token_factory->make( $plugin )->get();
if ( ! $token ) {
return '';
}
$cache_key = $this->cache->build_transient_no_prefix( [ $token ] );
return wp_nonce_url( add_query_arg( [
self::ARG => true,
self::SLUG => $plugin->get_slug(),
self::CACHE_KEY => $cache_key,
], get_admin_url( get_current_blog_id() ) ), self::ARG );
}
/**
* Disconnect (delete) a token if the user is allowed to.
*
* @action stellarwp/uplink/{$prefix}/admin_action_{$slug}
*
* @throws \RuntimeException
*
* @return void
*/
public function maybe_disconnect(): void {
if ( empty( $_GET[ self::ARG ] ) || empty( $_GET['_wpnonce'] ) || empty( $_GET[ self::SLUG ] ) || empty( $_GET[ self::CACHE_KEY ] ) ) {
return;
}
if ( ! is_admin() || wp_doing_ajax() ) {
return;
}
if ( wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), self::ARG ) ) {
if ( $this->authorizer->can_auth() && $this->disconnect->disconnect( $_GET[ self::SLUG ], $_GET[ self::CACHE_KEY ] ) ) {
$this->notice->add(
new Notice( Notice::SUCCESS,
__( 'Token disconnected.', '%TEXTDOMAIN%' ),
true
)
);
} else {
$this->notice->add(
new Notice( Notice::ERROR,
__( 'Unable to disconnect token, ensure you have admin permissions.', '%TEXTDOMAIN%' ),
true
)
);
}
} else {
$this->notice->add(
new Notice( Notice::ERROR,
__( 'Unable to disconnect token: nonce verification failed.', '%TEXTDOMAIN%' ),
true
)
);
}
$this->maybe_redirect_back();
}
/**
* Attempts to redirect the user back to their previous dashboard page while
* ensuring that any "Connect" token query variables are removed if they immediately
* attempt to Disconnect after Connecting. This prevents them from automatically
* getting connected again if the nonce is still valid.
*
* This will ensure the Notices set above are displayed.
*
* @return void
*/
private function maybe_redirect_back(): void {
$referer = wp_get_referer();
if ( ! $referer ) {
return;
}
$referer = remove_query_arg(
[
Connect_Controller::TOKEN,
Connect_Controller::LICENSE,
Connect_Controller::SLUG,
Connect_Controller::NONCE,
],
$referer
);
wp_safe_redirect( esc_url_raw( $referer ) );
exit;
}
}

View File

@@ -0,0 +1,73 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\API\V3\Auth\Contracts\Auth_Url;
final class Auth_Url_Builder {
/**
* @var Nonce
*/
private $nonce;
/**
* @var Auth_Url
*/
private $auth_url_manager;
/**
* @param Nonce $nonce The Nonce creator.
* @param Auth_Url $auth_url_manager The auth URL manager.
*/
public function __construct(
Nonce $nonce,
Auth_Url $auth_url_manager
) {
$this->nonce = $nonce;
$this->auth_url_manager = $auth_url_manager;
}
/**
* Build a brand's authorization URL, with the uplink_callback base64 query variable.
*
* @note This URL requires escaping.
*
* @param string $slug The product/service slug.
* @param string $domain An optional domain associated with a license key to pass along.
*
* @return string
*/
public function build( string $slug, string $domain = '' ): string {
global $pagenow;
if ( empty( $pagenow ) ) {
return '';
}
$auth_url = $this->auth_url_manager->get( $slug );
if ( ! $auth_url ) {
return '';
}
// Query arguments to combine with $_GET and add to the authorization URL.
$args = [
'uplink_domain' => $domain,
'uplink_slug' => $slug,
];
$url = add_query_arg(
array_filter( array_merge( $_GET, $args ) ),
admin_url( $pagenow )
);
return sprintf( '%s?%s',
$auth_url,
http_build_query( [
'uplink_callback' => base64_encode( $this->nonce->create_url( $url ) ),
] )
);
}
}

View File

@@ -0,0 +1,26 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Config;
/**
* Determines if the current site will allow the user to use the authorize button.
*/
final class Authorizer {
/**
* Checks if the current user can perform an action.
*
* @throws \RuntimeException
*
* @return bool
*/
public function can_auth(): bool {
return (bool) apply_filters(
'stellarwp/uplink/' . Config::get_hook_prefix() . '/auth/user_check',
is_super_admin()
);
}
}

View File

@@ -0,0 +1,62 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\License;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Config;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Pipeline\Pipeline;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources\Resource;
final class License_Manager {
/**
* The multisite processing pipeline.
*
* @var Pipeline
*/
private $pipeline;
/**
* Cached results for existing resources.
*
* @var array<string, bool>
*/
private $cache;
/**
* @param Pipeline $pipeline
*/
public function __construct( Pipeline $pipeline ) {
$this->pipeline = $pipeline;
}
/**
* Check if the current multisite and Uplink configuration allows a multisite
* license for the current subsite.
*
* Out of the box, sub-sites act independently of the network.
*
* @see Config::set_network_subfolder_license()
* @see Config::set_network_subdomain_license()
* @see Config::set_network_domain_mapping_license()
*
* @param Resource $resource The current resource to check against.
*
* @return bool
*/
public function allows_multisite_license( Resource $resource ): bool {
$key = $resource->get_slug();
$cache = $this->cache[ $key ] ?? null;
if ( $cache !== null ) {
return $cache;
}
// We're on single site or, the plugin isn't network activated.
if ( ! is_multisite() || ! $resource->is_network_activated() ) {
return $this->cache[ $key ] = false;
}
return $this->cache[ $key ] = $this->pipeline->send( false )->thenReturn();
}
}

View File

@@ -0,0 +1,37 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\License\Pipeline\Processors;
use Closure;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\License\Pipeline\Traits\Multisite_Trait;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Config;
use Throwable;
final class Multisite_Domain_Mapping {
use Multisite_Trait;
/**
* Checks if a sub-site already has a network token.
*
* @param bool $is_multisite_license
* @param Closure $next
*
* @return bool
*/
public function __invoke( bool $is_multisite_license, Closure $next ): bool {
if ( is_main_site() ) {
return $next( $is_multisite_license );
}
try {
if ( $this->is_unique_domain() ) {
return Config::allows_network_domain_mapping_license();
}
} catch ( Throwable $e ) {
return false;
}
return $next( $is_multisite_license );
}
}

View File

@@ -0,0 +1,29 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\License\Pipeline\Processors;
use Closure;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Config;
final class Multisite_Main_Site {
/**
* If we're on the main site any of the multisite licensing options are enabled,
* licensing is enabled.
*
* @param bool $is_multisite_license
* @param Closure $next
*
* @throws \RuntimeException
*
* @return bool
*/
public function __invoke( bool $is_multisite_license, Closure $next ): bool {
if ( is_main_site() && Config::allows_network_licenses() ) {
$is_multisite_license = true;
}
return $next( $is_multisite_license );
}
}

View File

@@ -0,0 +1,38 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\License\Pipeline\Processors;
use Closure;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\License\Pipeline\Traits\Multisite_Trait;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Config;
use Throwable;
final class Multisite_Subdomain {
use Multisite_Trait;
/**
* Checks if a sub-site already has a network token.
*
* @param bool $is_multisite_license
* @param Closure $next
*
* @return bool
*/
public function __invoke( bool $is_multisite_license, Closure $next ): bool {
if ( is_main_site() ) {
return $next( $is_multisite_license );
}
try {
if ( $this->is_subdomain() ) {
return Config::allows_network_subdomain_license();
}
} catch ( Throwable $e ) {
return false;
}
return $next( $is_multisite_license );
}
}

View File

@@ -0,0 +1,33 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\License\Pipeline\Processors;
use Closure;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\License\Pipeline\Traits\Multisite_Trait;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Config;
final class Multisite_Subfolder {
use Multisite_Trait;
/**
* Check if we're using multisite subfolders and if that type of network license is allowed.
*
* @param bool $is_multisite_license
* @param Closure $next
*
* @return bool
*/
public function __invoke( bool $is_multisite_license, Closure $next ): bool {
if ( is_main_site() ) {
return $next( $is_multisite_license );
}
if ( $this->is_subfolder_install() ) {
return Config::allows_network_subfolder_license();
}
return $next( $is_multisite_license );
}
}

View File

@@ -0,0 +1,83 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\License\Pipeline\Traits;
use RuntimeException;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Utils\Checks;
trait Multisite_Trait {
private function get_main_site_url(): string {
return get_site_url( get_main_site_id() );
}
private function get_current_site_url(): string {
return get_site_url();
}
/**
* Get the hostname for the main site.
*
* @throws RuntimeException
*
* @return string
*/
private function get_main_site_hostname(): string {
$result = wp_parse_url( $this->get_main_site_url(), PHP_URL_HOST );
if ( ! $result ) {
throw new RuntimeException( 'Unable to determine the main site hostname' );
}
return $result;
}
/**
* Get the current site's hostname.
*
* @throws RuntimeException
*
* @return string
*/
private function get_current_site_hostname(): string {
$result = wp_parse_url( $this->get_current_site_url(), PHP_URL_HOST );
if ( ! $result ) {
throw new RuntimeException( 'Unable to determine the current site hostname' );
}
return $result;
}
/**
* Checks if we're running multisite in subfolder mode.
*
* @return bool
*/
private function is_subfolder_install(): bool {
return Checks::str_starts_with( $this->get_current_site_url(), $this->get_main_site_url() );
}
/**
* Check if the current site is a subdomain of the main site.
*
* @throws RuntimeException
*
* @return bool
*/
private function is_subdomain(): bool {
return Checks::str_ends_with( $this->get_current_site_hostname(), $this->get_main_site_hostname() );
}
/**
* Checks if the current site is a different domain from the main site.
*
* @throws RuntimeException
*
* @return bool
*/
private function is_unique_domain(): bool {
return ! str_contains( $this->get_current_site_hostname(), $this->get_main_site_hostname() );
}
}

View File

@@ -0,0 +1,84 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Config;
final class Nonce {
/**
* The suffix for the transient name to store the nonce.
*/
public const NONCE_SUFFIX = '_uplink_nonce';
/**
* How long a nonce is valid for in seconds.
*
* @var int
*/
private $expiration;
/**
* @param int $expiration How long the nonce is valid for in seconds.
*/
public function __construct( int $expiration = 2100 ) {
$this->expiration = $expiration;
}
/**
* Verify a nonce.
*
* @param string $nonce The nonce token.
*
* @return bool
*/
public static function verify( string $nonce ): bool {
if ( ! $nonce ) {
return false;
}
return $nonce === get_transient( Config::get_hook_prefix_underscored() . self::NONCE_SUFFIX );
}
/**
* Create or reuse a non-expired nonce.
*
* @return string
*/
public function create(): string {
$existing = get_transient( $this->key() );
if ( $existing ) {
return $existing;
}
$nonce = wp_generate_password( 16, false );
set_transient( $this->key(), $nonce, $this->expiration );
return $nonce;
}
/**
* Attach a nonce to a URL.
*
* @note Unlike WordPress' function, you should escape this manually.
*
* @param string $url The existing URL to attach the nonce to.
*
* @return string
*/
public function create_url( string $url ): string {
return esc_url_raw( add_query_arg( '_uplink_nonce', $this->create(), $url ) );
}
/**
* Get the transient key, combining the configured hook prefix with our suffix.
*
* @return string
*/
private function key(): string {
return Config::get_hook_prefix_underscored() . self::NONCE_SUFFIX;
}
}

View File

@@ -0,0 +1,109 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\Admin\Connect_Controller;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\Admin\Disconnect_Controller;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\License\License_Manager;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\License\Pipeline\Processors\Multisite_Domain_Mapping;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\License\Pipeline\Processors\Multisite_Main_Site;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\License\Pipeline\Processors\Multisite_Subdomain;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\License\Pipeline\Processors\Multisite_Subfolder;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\Token\Managers\Network_Token_Manager;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\Token\Managers\Token_Manager;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Config;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Contracts\Abstract_Provider;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Pipeline\Pipeline;
final class Provider extends Abstract_Provider {
/**
* @inheritDoc
*/
public function register() {
if ( ! $this->container->has( Config::TOKEN_OPTION_NAME ) ) {
return;
}
$this->container->singleton(
Token_Manager::class,
static function ( $c ) {
return new Token_Manager( $c->get( Config::TOKEN_OPTION_NAME ) );
}
);
$this->container->singleton(
Network_Token_Manager::class,
static function ( $c ) {
return new Network_Token_Manager( $c->get( Config::TOKEN_OPTION_NAME ) );
}
);
$this->register_nonce();
$this->register_license_manager();
$this->register_auth_connect_disconnect();
}
/**
* Register nonce container definitions.
*
* @return void
*/
private function register_nonce(): void {
/**
* Filter how long the callback nonce is valid for.
*
* @note There is also an expiration time in the Uplink Origin plugin.
*
* Default: 35 minutes, to allow time for them to properly log in.
*
* @param int $expiration Nonce expiration time in seconds.
*/
$expiration = apply_filters( 'stellarwp/uplink/' . Config::get_hook_prefix() . '/auth/nonce_expiration', 2100 );
$expiration = absint( $expiration );
$this->container->singleton( Nonce::class, new Nonce( $expiration ) );
}
/**
* Register the license manager and its pipeline to detect different
* mulitsite licenses.
*
* @return void
*/
private function register_license_manager(): void {
$pipeline = ( new Pipeline( $this->container ) )->through( [
Multisite_Main_Site::class,
Multisite_Subfolder::class,
Multisite_Subdomain::class,
Multisite_Domain_Mapping::class,
] );
$this->container->singleton(
License_Manager::class,
static function () use ( $pipeline ) {
return new License_Manager( $pipeline );
}
);
}
/**
* Register token auth connection/disconnection definitions and hooks.
*
* @return void
*/
private function register_auth_connect_disconnect(): void {
$this->container->singleton( Disconnect_Controller::class, Disconnect_Controller::class );
$this->container->singleton( Connect_Controller::class, Connect_Controller::class );
$this->container->singleton( Action_Manager::class, Action_Manager::class );
$action_manager = $this->container->get( Action_Manager::class );
// Register a unique action for each resource slug.
add_action( 'admin_init', [ $action_manager, 'add_actions' ] );
// Execute the above actions when an uplink_slug query variable and the current_screen hook is fired (which is run after admin_init).
add_action( 'current_screen', [ $action_manager, 'do_action' ], 10, 0 );
}
}

View File

@@ -0,0 +1,37 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\Token;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\Token\Exceptions\InvalidTokenException;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources\Resource;
final class Connector {
/**
* @var Token_Factory
*/
private $token_manager_factory;
/**
* @param Token_Factory $token_manager_factory The Token Manager Factory.
*/
public function __construct( Token_Factory $token_manager_factory ) {
$this->token_manager_factory = $token_manager_factory;
}
/**
* Store a token if the user is allowed to.
*
* @throws InvalidTokenException
*/
public function connect( string $token, Resource $resource ): bool {
$token_manager = $this->token_manager_factory->make( $resource );
if ( ! $token_manager->validate( $token ) ) {
throw new InvalidTokenException( 'Invalid token format' );
}
return $token_manager->store( $token );
}
}

View File

@@ -0,0 +1,54 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\Token\Contracts;
interface Token_Manager {
/**
* This makes up the suffix of the option name when combined
* with the custom token prefix.
*
* @see Config::set_token_auth_prefix()
*/
public const TOKEN_SUFFIX = 'uplink_auth_token';
/**
* Returns the option_name/network_option_name that is used to store tokens.
*
* @return string
*/
public function option_name(): string;
/**
* Validates a token is in the accepted UUIDv4 format.
*
* @param string $token
*
* @return bool
*/
public function validate( string $token ): bool;
/**
* Stores the token in the database.
*
* @param string $token
*
* @return bool
*/
public function store( string $token ): bool;
/**
* Retrieves the stored token.
*
* @return string|null
*/
public function get(): ?string;
/**
* Deletes the token from the database.
*
* @return bool
*/
public function delete(): bool;
}

View File

@@ -0,0 +1,57 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\Token;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\API\V3\Auth\Token_Authorizer_Cache_Decorator;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources\Collection;
final class Disconnector {
/**
* @var Token_Factory
*/
private $token_manager_factory;
/**
* @var Collection
*/
private $resources;
/**
* @param Token_Factory $token_manager_factory The Token Manager Factory.
* @param Collection $resources The resources collection.
*/
public function __construct(
Token_Factory $token_manager_factory,
Collection $resources
) {
$this->token_manager_factory = $token_manager_factory;
$this->resources = $resources;
}
/**
* Delete a token if the current user is allowed to.
*
* @param string $slug The plugin or service slug.
* @param string $cache_key The token cache key.
*
* @return bool
*/
public function disconnect( string $slug, string $cache_key ): bool {
$plugin = $this->resources->offsetGet( $slug );
if ( ! $plugin ) {
return false;
}
$result = $this->token_manager_factory->make( $plugin )->delete();
if ( $result ) {
// Delete the authorization cache.
delete_transient( Token_Authorizer_Cache_Decorator::TRANSIENT_PREFIX . $cache_key );
}
return $result;
}
}

View File

@@ -0,0 +1,7 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\Token\Exceptions;
final class InvalidTokenException extends \Exception {
}

View File

@@ -0,0 +1,84 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\Token\Managers;
use RuntimeException;
/**
* Manages storing authorization tokens in a network, used when a
* plugin is network activated.
*
* @note All *_network_option() functions will fall back to
* single site functions if multisite is not enabled.
*/
final class Network_Token_Manager extends Token_Manager {
/**
* Store the token.
*
* @param string $token
*
* @throws RuntimeException
*
* @return bool
*/
public function store( string $token ): bool {
$this->multisite_check();
if ( ! $token ) {
return false;
}
// WordPress would otherwise return false if the items match.
if ( $token === $this->get() ) {
return true;
}
return update_network_option( get_current_network_id(), $this->option_name, $token );
}
/**
* Get the token.
*
* @throws RuntimeException
*
* @return string|null
*/
public function get(): ?string {
$this->multisite_check();
return get_network_option( get_current_network_id(), $this->option_name, null );
}
/**
* Revoke the token.
*
* @throws RuntimeException
*
* @return bool
*/
public function delete(): bool {
$this->multisite_check();
// Already doesn't exist, WordPress would normally return false.
if ( $this->get() === null ) {
return true;
}
return delete_network_option( get_current_network_id(), $this->option_name );
}
/**
* Check if multisite is enabled.
*
* @throws RuntimeException
*
* @return void
*/
private function multisite_check(): void {
if ( ! is_multisite() ) {
throw new RuntimeException( 'Multisite is not enabled' );
}
}
}

View File

@@ -0,0 +1,102 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\Token\Managers;
use InvalidArgumentException;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\Token\Contracts;
/**
* Manages storing authorization tokens on a single site.
*
* Used even on multisite if a plugin is not network activated.
*/
class Token_Manager implements Contracts\Token_Manager {
/**
* The option name to store the token in wp_options table.
*
* @see Config::set_token_auth_prefix()
*
* @var string
*/
protected $option_name;
/**
* @param string $option_name The option name as set via Config::set_token_auth_prefix().
*/
public function __construct( string $option_name ) {
if ( ! $option_name ) {
throw new InvalidArgumentException(
__( 'You must set a token prefix with StellarWP\Uplink\Config::set_token_auth_prefix() before using the token manager.', '%TEXTDOMAIN%' )
);
}
$this->option_name = $option_name;
}
/**
* Returns the option_name that is used to store tokens.
*
* @return string
*/
public function option_name(): string {
return $this->option_name;
}
/**
* Validates a token is in the accepted UUIDv4 format.
*
* @param string $token
*
* @return bool
*/
public function validate( string $token ): bool {
$pattern = '/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i';
return preg_match( $pattern, $token ) === 1;
}
/**
* Store the token.
*
* @param string $token
*
* @return bool
*/
public function store( string $token ): bool {
if ( ! $token ) {
return false;
}
// WordPress would otherwise return false if the items match.
if ( $token === $this->get() ) {
return true;
}
return update_option( $this->option_name, $token );
}
/**
* Get the token.
*
* @return string|null
*/
public function get(): ?string {
return get_option( $this->option_name, null );
}
/**
* Revoke the token.
*
* @return bool
*/
public function delete(): bool {
// Already doesn't exist, WordPress would normally return false.
if ( $this->get() === null ) {
return true;
}
return delete_option( $this->option_name );
}
}

View File

@@ -0,0 +1,45 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\Token;
use KadenceWP\KadenceBlocks\StellarWP\ContainerContract\ContainerInterface;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\License\License_Manager;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\Token\Contracts\Token_Manager;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\Token\Managers\Network_Token_Manager;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources\Resource;
final class Token_Factory {
/**
* @var License_Manager
*/
private $license_manager;
/**
* @var ContainerInterface
*/
private $container;
/**
* @param License_Manager $license_manager
* @param ContainerInterface $container
*/
public function __construct( License_Manager $license_manager, ContainerInterface $container ) {
$this->license_manager = $license_manager;
$this->container = $container;
}
/**
* Makes Network or Single Site Token Manager instance.
*
* @param Resource $resource The resource to check against.
*
* @return Token_Manager
*/
public function make( Resource $resource ): Token_Manager {
$network_license = $this->license_manager->allows_multisite_license( $resource );
return $this->container->get( $network_license ? Network_Token_Manager::class : Managers\Token_Manager::class );
}
}

View File

@@ -0,0 +1,204 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Components\Admin;
use InvalidArgumentException;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\Admin\Disconnect_Controller;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\Auth_Url_Builder;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\Authorizer;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\Token\Token_Factory;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Components\Controller;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Config;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources\Collection;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\View\Contracts\View;
final class Authorize_Button_Controller extends Controller {
/**
* The view file, without ext, relative to the root views directory.
*/
public const VIEW = 'admin/authorize-button';
/**
* @var Authorizer
*/
private $authorizer;
/**
* @var Token_Factory
*/
private $token_manager_factory;
/**
* @var Auth_Url_Builder
*/
private $url_builder;
/**
* @var Collection
*/
private $resources;
/**
* @var Disconnect_Controller
*/
private $disconnect_controller;
/**
* @param View $view The View Engine to render views.
* @param Authorizer $authorizer Determines if the current user can perform actions.
* @param Token_Factory $token_manager_factory The Token Manager Factory.
* @param Auth_Url_Builder $url_builder The Auth URL Builder.
* @param Collection $resources The resources collection.
* @param Disconnect_Controller $disconnect_controller The disconnect controller.
*/
public function __construct(
View $view,
Authorizer $authorizer,
Token_Factory $token_manager_factory,
Auth_Url_Builder $url_builder,
Collection $resources,
Disconnect_Controller $disconnect_controller
) {
parent::__construct( $view );
$this->authorizer = $authorizer;
$this->token_manager_factory = $token_manager_factory;
$this->url_builder = $url_builder;
$this->resources = $resources;
$this->disconnect_controller = $disconnect_controller;
}
/**
* Renders the authorize-button view.
*
* @param array{slug?: string, domain?: string} $args The Product slug and license domain.
*
* @see src/views/admin/authorize-button.php
*
* @throws InvalidArgumentException
*/
public function render( array $args = [] ): void {
global $pagenow;
$slug = $args['slug'] ?? '';
$domain = $args['domain'] ?? '';
if ( empty ( $slug ) ) {
throw new InvalidArgumentException( __( 'The Product slug cannot be empty', '%TEXTDOMAIN%' ) );
}
$url = $this->url_builder->build( $slug, $domain );
if ( ! $url ) {
return;
}
$plugin = $this->resources->offsetGet( $slug );
if ( ! $plugin ) {
return;
}
$authenticated = false;
$target = '_blank';
$link_text = __( 'Connect', '%TEXTDOMAIN%' );
$classes = [
'uplink-authorize',
'not-authorized',
];
if ( ! $this->authorizer->can_auth() ) {
$target = '_self';
$link_text = __( 'Contact your network administrator to connect', '%TEXTDOMAIN%' );
$url = get_admin_url( get_current_blog_id(), 'network/' );
} elseif ( $this->token_manager_factory->make( $plugin )->get() ) {
$authenticated = true;
$target = '_self';
$link_text = __( 'Disconnect', '%TEXTDOMAIN%' );
$url = $this->disconnect_controller->get_url( $plugin );
$classes[1] = 'authorized';
}
$hook_prefix = Config::get_hook_prefix();
/**
* Filter the link text.
*
* @param string $link_text The current link text.
* @param bool $authenticated Whether they are authenticated.
* @param string|null $pagenow The value of WordPress's pagenow.
*/
$link_text = apply_filters(
"stellarwp/uplink/$hook_prefix/view/authorize_button/link_text",
$link_text,
$authenticated,
$pagenow
);
/**
* Filter the hyperlink url.
*
* @param string $url The current hyperlink url.
* @param bool $authenticated Whether they are authenticated.
* @param string|null $pagenow The value of WordPress's pagenow.
*/
$url = apply_filters(
"stellarwp/uplink/$hook_prefix/view/authorize_button/url",
$url,
$authenticated,
$pagenow
);
/**
* Filter the link target.
*
* @param string $target The current link target.
* @param bool $authenticated Whether they are authenticated.
* @param string|null $pagenow The value of WordPress's pagenow.
*/
$target = apply_filters(
"stellarwp/uplink/$hook_prefix/view/authorize_button/target",
$target,
$authenticated,
$pagenow
);
/**
* Filter the HTML wrapper tag.
*
* @param string $tag The HTML tag to use for the wrapper.
* @param bool $authenticated Whether they are authenticated.
* @param string|null $pagenow The value of WordPress's pagenow.
*/
$tag = apply_filters(
"stellarwp/uplink/$hook_prefix/view/authorize_button/tag",
'div',
$authenticated,
$pagenow
);
/**
* Filter the CSS classes
*
* @param array $classes An array of CSS classes.
* @param bool $authenticated Whether they are authenticated.
* @param string|null $pagenow The value of WordPress's pagenow.
*/
$classes = (array) apply_filters(
"stellarwp/uplink/$hook_prefix/view/authorize_button/classes",
$classes,
$authenticated,
$pagenow
);
echo $this->view->render( self::VIEW, [
'link_text' => $link_text,
'url' => $url,
'target' => $target,
'tag' => $tag,
'classes' => $this->classes( $classes ),
] );
}
}

View File

@@ -0,0 +1,51 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Components;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\View\Contracts\View;
/**
* Component/View controller made to accept arguments and render
* them in a view file.
*/
abstract class Controller {
/**
* The View Engine to render views.
*
* @var View
*/
protected $view;
/**
* Render the view file.
*
* @param mixed[] $args An optional array of arguments to utilize when rendering.
*/
abstract public function render( array $args = [] ): void;
/**
* @param View $view The View Engine to render views.
*/
public function __construct( View $view ) {
$this->view = $view;
}
/**
* Format an array of CSS classes into a string.
*
* @param array $classes
*
* @return string
*/
protected function classes( array $classes ): string {
if ( ! $classes ) {
return '';
}
$classes = array_unique( array_map( 'sanitize_html_class', array_filter( $classes ) ) );
return implode( ' ', $classes );
}
}

View File

@@ -0,0 +1,334 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink;
use InvalidArgumentException;
use RuntimeException;
use KadenceWP\KadenceBlocks\StellarWP\ContainerContract\ContainerInterface;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\Token\Contracts\Token_Manager;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Utils\Sanitize;
class Config {
public const TOKEN_OPTION_NAME = 'uplink.token_prefix';
/**
* The default authorization cache time in seconds (6 hours).
*/
public const DEFAULT_AUTH_CACHE = 21600;
/**
* The default state for all multisite licensing options.
*
* @var bool
*/
public const DEFAULT_MULTISITE_STATE = false;
/**
* Container object.
*
* @since 1.0.0
*
* @var ContainerInterface
*/
protected static $container;
/**
* Prefix for hook names.
*
* @since 1.0.0
*
* @var string
*/
protected static $hook_prefix = '';
/**
* How long in seconds we cache successful authorization
* token requests.
*
* @var int
*/
protected static $auth_cache_expiration = self::DEFAULT_AUTH_CACHE;
/**
* Whether your plugin allows multisite network subfolder licenses.
*
* @var bool
*/
protected static $network_subfolder_license = self::DEFAULT_MULTISITE_STATE;
/**
* Whether your plugin allows multisite subdomain licenses.
*
* @var bool
*/
protected static $network_subdomain_license = self::DEFAULT_MULTISITE_STATE;
/**
* Whether your plugin allows multisite domain mapping licenses.
*
* @var bool
*/
protected static $network_domain_mapping_license = self::DEFAULT_MULTISITE_STATE;
/**
* Get the container.
*
* @since 1.0.0
*
* @throws RuntimeException
*
* @return ContainerInterface
*/
public static function get_container() {
if ( self::$container === null ) {
throw new RuntimeException(
__( 'You must provide a container via StellarWP\Uplink\Config::set_container() before attempting to fetch it.', '%TEXTDOMAIN%' )
);
}
return self::$container;
}
/**
* Gets the hook prefix.
*
* @since 1.0.0
*
* @return string
*/
public static function get_hook_prefix(): string {
if ( self::$hook_prefix === null ) {
throw new RuntimeException(
__( 'You must provide a hook prefix via StellarWP\Uplink\Config::set_hook_prefix() before attempting to fetch it.', '%TEXTDOMAIN%' )
);
}
return static::$hook_prefix;
}
/**
* Gets the hook underscored prefix.
*
* @since 1.0.0
*
* @return string
*/
public static function get_hook_prefix_underscored(): string {
if ( self::$hook_prefix === null ) {
throw new RuntimeException(
__( 'You must provide a hook prefix via StellarWP\Uplink\Config::set_hook_prefix() before attempting to fetch it.', '%TEXTDOMAIN%' )
);
}
return strtolower( str_replace( '-', '_', sanitize_title( static::$hook_prefix ) ) );
}
/**
* Returns whether the container has been set.
*
* @since 1.0.0
*
* @return bool
*/
public static function has_container(): bool {
return self::$container !== null;
}
/**
* Resets this class back to the defaults.
*
* @since 1.0.0
*
* @return void
*/
public static function reset(): void {
static::$hook_prefix = '';
static::$auth_cache_expiration = self::DEFAULT_AUTH_CACHE;
static::$network_subfolder_license = self::DEFAULT_MULTISITE_STATE;
static::$network_subdomain_license = self::DEFAULT_MULTISITE_STATE;
static::$network_domain_mapping_license = self::DEFAULT_MULTISITE_STATE;
if ( self::has_container() ) {
self::$container->singleton( self::TOKEN_OPTION_NAME, null );
}
}
/**
* Set the container object.
*
* @since 1.0.0
*
* @param ContainerInterface $container Container object.
*
* @return void
*/
public static function set_container( ContainerInterface $container ): void {
self::$container = $container;
}
/**
* Sets the hook prefix.
*
* @since 1.0.0
*
* @param string $prefix
*
* @return void
*/
public static function set_hook_prefix( string $prefix ): void {
static::$hook_prefix = $prefix;
}
/**
* Sets a token options table prefix for storing an origin's authorization token.
*
* This should be the same across all of your products.
*
* @since 1.3.0
*
* @param string $prefix
*
* @throws RuntimeException|InvalidArgumentException
*
* @return void
*/
public static function set_token_auth_prefix( string $prefix ): void {
if ( ! self::has_container() ) {
throw new RuntimeException(
__( 'You must set a container with StellarWP\Uplink\Config::set_container() before setting a token auth prefix.', '%TEXTDOMAIN%' )
);
}
$prefix = Sanitize::sanitize_title_with_hyphens( rtrim( $prefix, '_' ) );
$key = sprintf( '%s_%s', $prefix, Token_Manager::TOKEN_SUFFIX );
// The option_name column in wp_options is a varchar(191)
$max_length = 191;
if ( strlen( $key ) > $max_length ) {
throw new InvalidArgumentException(
sprintf(
__( 'The token auth prefix must be at most %d characters, including a trailing hyphen.', '%TEXTDOMAIN%' ),
absint( $max_length - strlen( Token_Manager::TOKEN_SUFFIX ) )
)
);
}
self::get_container()->singleton( self::TOKEN_OPTION_NAME, $key );
}
/**
* Set the token authorization expiration.
*
* @param int $seconds The time seconds the cache will exist for.
* -1 = disabled, 0 = no expiration.
*
* @return void
*/
public static function set_auth_cache_expiration( int $seconds ): void {
static::$auth_cache_expiration = $seconds;
}
/**
* Get the token authorization expiration.
*
* @return int
*/
public static function get_auth_cache_expiration(): int {
return static::$auth_cache_expiration;
}
/**
* Allow or disallow multisite subfolder licenses at the network level.
*
* @param bool $allowed
*
* @return void
*/
public static function set_network_subfolder_license( bool $allowed ): void {
self::$network_subfolder_license = $allowed;
}
/**
* Whether your plugin allows multisite network subfolder licenses.
*
* @throws RuntimeException
*
* @return bool
*/
public static function allows_network_subfolder_license(): bool {
return (bool) apply_filters(
'stellarwp/uplink/' . Config::get_hook_prefix() . '/allows_network_subfolder_license',
self::$network_subfolder_license
);
}
/**
* Allow or disallow multisite subdomain licenses at the network level.
*
* @param bool $allowed
*
* @return void
*/
public static function set_network_subdomain_license( bool $allowed ): void {
self::$network_subdomain_license = $allowed;
}
/**
* Whether your plugin allows multisite network subdomain licenses.
*
* @throws RuntimeException
*
* @return bool
*/
public static function allows_network_subdomain_license(): bool {
return (bool) apply_filters(
'stellarwp/uplink/' . Config::get_hook_prefix() . '/allows_network_subdomain_license',
self::$network_subdomain_license
);
}
/**
* Allow or disallow multisite domain mapping licenses at the network level.
*
* @param bool $allowed
*
* @return void
*/
public static function set_network_domain_mapping_license( bool $allowed ): void {
self::$network_domain_mapping_license = $allowed;
}
/**
* Whether your plugin allows multisite network domain mapping licenses.
*
* @throws RuntimeException
*
* @return bool
*/
public static function allows_network_domain_mapping_license(): bool {
return (bool) apply_filters(
'stellarwp/uplink/' . Config::get_hook_prefix() . '/allows_network_domain_mapping_license',
self::$network_domain_mapping_license
);
}
/**
* Check if any of the network license options are enabled.
*
* @throws RuntimeException
*
* @return bool
*/
public static function allows_network_licenses(): bool {
$config = [
self::allows_network_subfolder_license(),
self::allows_network_subdomain_license(),
self::allows_network_domain_mapping_license(),
];
return in_array( true, $config, true );
}
}

View File

@@ -0,0 +1,24 @@
<?php
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Contracts;
use KadenceWP\KadenceBlocks\StellarWP\ContainerContract\ContainerInterface;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Config;
abstract class Abstract_Provider implements Provider_Interface {
/**
* @var ContainerInterface
*/
protected $container;
/**
* Constructor for the class.
*
* @param ContainerInterface $container
*/
public function __construct( $container = null ) {
$this->container = $container ?: Config::get_container();
}
}

View File

@@ -0,0 +1,12 @@
<?php
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Contracts;
interface Provider_Interface {
/**
* Register action/filter listeners to hook into WordPress
*
* @return void
*/
public function register();
}

View File

@@ -0,0 +1,16 @@
<?php
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Exceptions;
class ResourceAlreadyRegisteredException extends \Exception {
/**
* Constructor.
*
* @since 1.0.0
*
* @param string $slug Resource slug.
*/
public function __construct( $slug ) {
parent::__construct( sprintf( __( 'The resource "%s" is already registered.', '%TEXTDOMAIN%' ), $slug ) );
}
}

View File

@@ -0,0 +1,66 @@
<?php
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Messages;
use KadenceWP\KadenceBlocks\StellarWP\ContainerContract\ContainerInterface;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\API\Client;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources\Resource;
class API extends Message_Abstract {
/**
* API message.
*
* @var string
*/
protected $message;
/**
* Resource instance.
*
* @var Resource
*/
protected $resource;
/**
* Resource version.
*
* @var string
*/
protected $version;
/**
* Constructor.
*
* @since 1.0.0
*
* @param string $message API message.
* @param string $version Resource version.
* @param Resource $resource Resource instance.
* @param ContainerInterface|null $container Container instance.
*/
public function __construct( string $message, string $version, Resource $resource, $container = null ) {
parent::__construct( $container );
$this->message = $message;
$this->version = $version;
$this->resource = $resource;
}
/**
* @inheritDoc
*/
public function get(): string {
/** @var Client */
$api = $this->container->get( Client::class );
$message = $this->message;
$message = str_replace( '%plugin_name%', $this->resource->get_name(), $message );
$message = str_replace( '%plugin_slug%', $this->resource->get_slug(), $message );
$message = str_replace( '%update_url%', trailingslashit( $api->get_api_base_url() ), $message );
$message = str_replace( '%version%', $this->version, $message );
$message = str_replace( '%changelog%', '<a class="thickbox" title="' . $this->resource->get_name() . '" href="plugin-install.php?tab=plugin-information&plugin=' . $this->resource->get_slug() . '&TB_iframe=true&width=640&height=808">what\'s new</a>', $message );
return $message;
}
}

View File

@@ -0,0 +1,82 @@
<?php
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Messages;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Config;
class Expired_Key extends Message_Abstract {
/**
* @inheritDoc
*/
public function get(): string {
// TEC only default link for backwards compatibility.
$default_link = in_array(
Config::get_hook_prefix(),
[
'the-events-calendar',
'events-calendar-pro',
'event-tickets',
'event-tickets-plus',
'tribe-filterbar',
'events-virtual',
'events-community',
'events-community-tickets',
'event-aggregator',
'events-elasticsearch',
'image-widget-plus',
'advanced-post-manager',
'tribe-eventbrite',
'event-automator',
'tec-seating',
],
true ) ? 'https://evnt.is/195y' : '';
$message_link = apply_filters( 'stellarwp/uplink/' . Config::get_hook_prefix() . '/messages/expired_key_link', $default_link );
$renew_label = __( 'Renew Your License Now', '%TEXTDOMAIN%' );
$opens_in_new_window = __( '(opens in a new window)', '%TEXTDOMAIN%' );
$notice_text = __( 'Your license is expired', '%TEXTDOMAIN%' );
if ( ! empty( $message_link ) ) {
$message_content = sprintf(
'<p>%s <a href="%s" target="_blank" class="button button-primary">%s <span class="screen-reader-text">%s</span></a></p>',
esc_html( $notice_text ),
esc_url( $message_link ),
esc_html( $renew_label ),
esc_html( $opens_in_new_window )
);
} else {
$message_content = sprintf(
'<p>%s</p>',
esc_html( $notice_text )
);
}
$message_content = apply_filters( 'stellarwp/uplink/' . Config::get_hook_prefix() . '/messages/expired_key', $message_content );
$allowed_html = [
'a' => [
'href' => [],
'title' => [],
'target' => [],
'class' => []
],
'br' => [],
'em' => [],
'strong' => [],
'div' => [
'class' => []
],
'p' => [
'class' => []
],
'span' => [
'class' => []
],
];
$message = '<div class="notice notice-warning">';
$message .= wp_kses( $message_content, $allowed_html );
$message .= '</div>';
return $message;
}
}

View File

@@ -0,0 +1,48 @@
<?php
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Messages;
use KadenceWP\KadenceBlocks\StellarWP\ContainerContract\ContainerInterface;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Config;
abstract class Message_Abstract {
/**
* Container instance.
*
* @since 1.0.0
*
* @var ContainerInterface
*/
protected $container;
/**
* Constructor.
*
* @since 1.0.0
*
* @param ContainerInterface|null $container Container instance.
*/
public function __construct( $container = null ) {
$this->container = $container ?: Config::get_container();
}
/**
* Gets the fully built message.
*
* @since 1.0.0
*
* @return string
*/
abstract public function get(): string;
/**
* Returns the message as a string.
*
* @since 1.0.0
*
* @return string
*/
public function __toString(): string {
return $this->get();
}
}

View File

@@ -0,0 +1,12 @@
<?php
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Messages;
class Network_Licensed extends Message_Abstract {
/**
* @inheritDoc
*/
public function get(): string {
return esc_html__( 'A valid license has been entered by your network administrator.', '%TEXTDOMAIN%' );
}
}

View File

@@ -0,0 +1,12 @@
<?php
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Messages;
class Network_Unlicensed extends Message_Abstract {
/**
* @inheritDoc
*/
public function get(): string {
return esc_html__( 'No license entered. Consult your network administrator.', '%TEXTDOMAIN%' );
}
}

View File

@@ -0,0 +1,12 @@
<?php
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Messages;
class Network_Expired extends Message_Abstract {
/**
* @inheritDoc
*/
public function get(): string {
return esc_html__( 'Expired license. Consult your network administrator.', '%TEXTDOMAIN%' );
}
}

View File

@@ -0,0 +1,16 @@
<?php
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Messages;
class Unlicensed extends Message_Abstract {
/**
* @inheritDoc
*/
public function get(): string {
$message = '<div class="notice notice-warning"><p>';
$message .= esc_html__( 'No license entered.', '%TEXTDOMAIN%' );
$message .= '</p></div>';
return $message;
}
}

View File

@@ -0,0 +1,14 @@
<?php
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Messages;
class Unreachable extends Message_Abstract {
/**
* @inheritDoc
*/
public function get(): string {
$message = esc_html__( 'Sorry, key validation server is not available.', '%TEXTDOMAIN%' );
return $message;
}
}

View File

@@ -0,0 +1,43 @@
<?php
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Messages;
use KadenceWP\KadenceBlocks\StellarWP\ContainerContract\ContainerInterface;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources\Resource;
class Update_Available extends Message_Abstract {
/**
* Resource instance.
*
* @var Resource
*/
protected $resource;
/**
* Constructor.
*
* @since 1.0.0
*
* @param Resource $resource Resource instance.
* @param ContainerInterface|null $container Container instance.
*/
public function __construct( Resource $resource, $container = null ) {
parent::__construct( $container );
$this->resource = $resource;
}
/**
* @inheritDoc
*/
public function get(): string {
$link = sprintf( '<a href="%s">', $this->resource->get_home_url() ?: '' );
return sprintf(
esc_html__( 'There is an update for %s. You\'ll need to %scheck your license%s to have access to updates, downloads, and support.', '%TEXTDOMAIN%' ),
$this->resource->get_name(),
$link,
'</a>'
);
}
}

View File

@@ -0,0 +1,59 @@
<?php
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Messages;
use KadenceWP\KadenceBlocks\StellarWP\ContainerContract\ContainerInterface;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources\Plugin;
class Update_Now extends Message_Abstract {
/**
* Resource instance.
*
* @var Plugin
*/
protected $resource;
/**
* Constructor.
*
* @since 1.0.0
*
* @param Plugin $resource Resource instance.
* @param ContainerInterface|null $container Container instance.
*/
public function __construct( Plugin $resource, $container = null ) {
parent::__construct( $container );
$this->resource = $resource;
}
/**
* @inheritDoc
*/
public function get(): string {
// A plugin update is available
$update_now = sprintf(
esc_html__( 'Update now to version %s.', '%TEXTDOMAIN%' ),
$this->resource->get_update_status()->update->version
);
$update_now_link = sprintf(
' <a href="%1$s" class="update-link">%2$s</a>',
wp_nonce_url( self_admin_url( 'update.php?action=upgrade-plugin&plugin=' ) . $this->resource->get_path(), 'upgrade-plugin_' . $this->resource->get_path() ),
$update_now
);
$update_message = sprintf(
esc_html__( 'There is a new version of %1$s available. %2$s', '%TEXTDOMAIN%' ),
$this->resource->get_name(),
$update_now_link
);
$message = sprintf(
'<p>%s</p>',
$update_message
);
return $message;
}
}

View File

@@ -0,0 +1,46 @@
<?php
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Messages;
use KadenceWP\KadenceBlocks\StellarWP\ContainerContract\ContainerInterface;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Config;
class Valid_Key extends Message_Abstract {
/**
* Expiration date.
*
* @var string
*/
protected $expiration;
/**
* Constructor.
*
* @since 1.0.0
*
* @param string $expiration Expiration date.
* @param ContainerInterface|null $container Container instance.
*/
public function __construct( $expiration, $container = null ) {
parent::__construct( $container );
$this->expiration = $expiration;
}
/**
* @inheritDoc
*/
public function get(): string {
if ( $this->expiration ) {
$message = sprintf(
__( 'Valid key! Expires on %s.', '%TEXTDOMAIN%' ),
$this->expiration
);
} else {
$message = __( 'Valid key!', '%TEXTDOMAIN%' );
}
$message = apply_filters( 'stellarwp/uplink/' . Config::get_hook_prefix() . '/messages/valid_key', $message, $this->expiration );
return esc_html( $message );
}
}

View File

@@ -0,0 +1,100 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Notice;
use InvalidArgumentException;
/**
* A Notice to display in wp-admin.
*/
final class Notice {
public const INFO = 'info';
public const SUCCESS = 'success';
public const WARNING = 'warning';
public const ERROR = 'error';
public const ALLOWED_TYPES = [
self::INFO,
self::SUCCESS,
self::WARNING,
self::ERROR,
];
/**
* The notice type, one of the above constants.
*
* @var string
*/
private $type;
/**
* The already translated message to display.
*
* @see __()
*
* @var string
*/
private $message;
/**
* Whether this notice is dismissible.
*
* @var bool
*/
private $dismissible;
/**
* Whether this is an alt-notice.
*
* @var bool
*/
private $alt;
/**
* Whether this should be a large notice.
*
* @var bool
*/
private $large;
/**
* @param string $type The notice type, one of the above constants.
* @param string $message The already translated message to display.
* @param bool $dismissible Whether this notice is dismissible.
* @param bool $alt Whether this is an alt-notice.
* @param bool $large Whether this should be a large notice.
*/
public function __construct(
string $type,
string $message,
bool $dismissible = false,
bool $alt = false,
bool $large = false
) {
if ( ! in_array( $type, self::ALLOWED_TYPES, true ) ) {
throw new InvalidArgumentException( sprintf(
__( 'Notice $type must be one of: %s', '%TEXTDOMAIN%' ),
implode( ', ', self::ALLOWED_TYPES ) )
);
}
if ( empty( $message ) ) {
throw new InvalidArgumentException( __( 'The $message cannot be empty', '%TEXTDOMAIN%' ) );
}
$this->type = $type;
$this->message = $message;
$this->dismissible = $dismissible;
$this->alt = $alt;
$this->large = $large;
}
/**
* @return array{type: string, message: string, dismissible: bool, alt: bool, large: bool}
*/
public function toArray(): array {
return get_object_vars( $this );
}
}

View File

@@ -0,0 +1,64 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Notice;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Components\Controller;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\View\Exceptions\FileNotFoundException;
/**
* Renders a notice.
*/
final class Notice_Controller extends Controller {
/**
* The view file, without ext, relative to the root views directory.
*/
public const VIEW = 'admin/notice';
/**
* Render a notice.
*
* @see Notice::toArray()
* @see src/views/admin/notice.php
*
* @param array{type?: string, message?: string, dismissible?: bool, alt?: bool, large?: bool} $args The notice.
*
* @throws FileNotFoundException If the view is not found.
*
* @return void
*/
public function render( array $args = [] ): void {
$classes = [
'notice',
sprintf( 'notice-%s', $args['type'] ),
$args['dismissible'] ? 'is-dismissible' : '',
$args['alt'] ? 'notice-alt' : '',
$args['large'] ? 'notice-large' : '',
];
echo $this->view->render( self::VIEW, [
'message' => $args['message'],
'classes' => $this->classes( $classes ),
'allowed_tags' => [
'a' => [
'href' => [],
'title' => [],
'target' => [],
'rel' => [],
],
'br' => [],
'code' => [],
'em' => [],
'pre' => [],
'span' => [],
'strong' => [],
],
'allowed_protocols' => [
'http',
'https',
'mailto',
],
] );
}
}

View File

@@ -0,0 +1,89 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Notice;
/**
* An improved admin notice system for general messages.
*
* @see \KadenceWP\KadenceBlocks\StellarWP\Uplink\Admin\Notice
*/
final class Notice_Handler {
public const TRANSIENT = 'stellarwp_uplink_notices';
/**
* Handles rendering notices.
*
* @var Notice_Controller
*/
private $controller;
/**
* @var Notice[]
*/
private $notices;
public function __construct( Notice_Controller $controller ) {
$this->notices = $this->all();
$this->controller = $controller;
}
/**
* Add a notice to display.
*
* @param Notice $notice
*
* @return void
*/
public function add( Notice $notice ): void {
$this->notices = array_merge( $this->all(), [ $notice ] );
$this->save();
}
/**
* Display all notices and then clear them.
*
* @action admin_notices
*
* @return void
*/
public function display(): void {
if ( count( $this->notices ) <= 0 ) {
return;
}
foreach ( $this->notices as $notice ) {
$this->controller->render( $notice->toArray() );
}
$this->clear();
}
/**
* Get all notices.
*
* @return Notice[]
*/
private function all(): array {
return array_filter( (array) get_transient( self::TRANSIENT ) );
}
/**
* Save the existing state of notices.
*
* @return bool
*/
private function save(): bool {
return (bool) set_transient( self::TRANSIENT, $this->notices, 300 );
}
/**
* Clear all notices.
*
* @return bool
*/
private function clear(): bool {
return (bool) delete_transient( self::TRANSIENT );
}
}

View File

@@ -0,0 +1,21 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Notice;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Contracts\Abstract_Provider;
final class Provider extends Abstract_Provider {
/**
* @inheritDoc
*/
public function register(): void {
$this->container->singleton( Notice_Controller::class, Notice_Controller::class );
$this->container->singleton( Notice_Handler::class, static function ( $c ): Notice_Handler {
return new Notice_Handler( $c->get( Notice_Controller::class ) );
} );
add_action( 'admin_notices', [ $this->container->get( Notice_Handler::class ), 'display' ], 12, 0 );
}
}

View File

@@ -0,0 +1,272 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Pipeline;
use Closure;
use RuntimeException;
use KadenceWP\KadenceBlocks\StellarWP\ContainerContract\ContainerInterface;
use Throwable;
/**
* Adapted from Laravel's Pipeline to use our container system.
*
* @link https://github.com/illuminate/pipeline/blob/master/Pipeline.php
*/
final class Pipeline {
/**
* The container implementation.
*
* @var ContainerInterface|null
*/
protected $container;
/**
* The object being passed through the pipeline.
*
* @var mixed
*/
protected $passable;
/**
* The array of class pipes.
*
* @var array
*/
protected $pipes = [];
/**
* The method to call on each pipe.
*
* @var string
*/
protected $method = 'handle';
/**
* Create a new class instance.
*
* @param ContainerInterface|null $container
*
* @return void
*/
public function __construct( ContainerInterface $container = null ) {
$this->container = $container;
}
/**
* Set the object being sent through the pipeline.
*
* @param mixed $passable
*
* @return $this
*/
public function send( $passable ): Pipeline {
$this->passable = $passable;
return $this;
}
/**
* Set the array of pipes.
*
* @param array|mixed $pipes
*
* @return $this
*/
public function through( $pipes ): Pipeline {
$this->pipes = is_array( $pipes ) ? $pipes : func_get_args();
return $this;
}
/**
* Push additional pipes onto the pipeline.
*
* @param array|mixed $pipes
*
* @return $this
*/
public function pipe( $pipes ): Pipeline {
array_push( $this->pipes, ...( is_array( $pipes ) ? $pipes : func_get_args() ) );
return $this;
}
/**
* Set the method to call on the pipes.
*
* @param string $method
*
* @return $this
*/
public function via( string $method ): Pipeline {
$this->method = $method;
return $this;
}
/**
* Run the pipeline with a final destination callback.
*
* @param \Closure $destination
*
* @return mixed
*/
public function then( Closure $destination ) {
$pipeline = array_reduce(
array_reverse( $this->pipes() ), $this->carry(), $this->prepareDestination( $destination )
);
return $pipeline( $this->passable );
}
/**
* Run the pipeline and return the result.
*
* @return mixed
*/
public function thenReturn() {
return $this->then( function ( $passable ) {
return $passable;
} );
}
/**
* Get the final piece of the Closure onion.
*
* @param \Closure $destination
*
* @return \Closure
*/
protected function prepareDestination( Closure $destination ): Closure {
return function ( $passable ) use ( $destination ) {
try {
return $destination( $passable );
} catch ( Throwable $e ) {
return $this->handleException( $passable, $e );
}
};
}
/**
* Get a Closure that represents a slice of the application onion.
*
* @return \Closure
*/
protected function carry(): Closure {
return function ( $stack, $pipe ) {
return function ( $passable ) use ( $stack, $pipe ) {
try {
if ( is_callable( $pipe ) ) {
// If the pipe is a callable, then we will call it directly, but otherwise we
// will resolve the pipes out of the dependency container and call it with
// the appropriate method and arguments, returning the results back out.
return $pipe( $passable, $stack );
} elseif ( ! is_object( $pipe ) ) {
[ $name, $parameters ] = $this->parsePipeString( $pipe );
// If the pipe is a string we will parse the string and resolve the class out
// of the dependency injection container. We can then build a callable and
// execute the pipe function giving in the parameters that are required.
$pipe = $this->getContainer()->get( $name );
$parameters = array_merge( [ $passable, $stack ], $parameters );
} else {
// If the pipe is already an object we'll just make a callable and pass it to
// the pipe as-is. There is no need to do any extra parsing and formatting
// since the object we're given was already a fully instantiated object.
$parameters = [ $passable, $stack ];
}
$carry = method_exists( $pipe, $this->method )
? $pipe->{$this->method}( ...$parameters )
: $pipe( ...$parameters );
return $this->handleCarry( $carry );
} catch ( Throwable $e ) {
return $this->handleException( $passable, $e );
}
};
};
}
/**
* Parse full pipe string to get name and parameters.
*
* @param string $pipe
*
* @return array
*/
protected function parsePipeString( string $pipe ): array {
[ $name, $parameters ] = array_pad( explode( ':', $pipe, 2 ), 2, [] );
if ( is_string( $parameters ) ) {
$parameters = explode( ',', $parameters );
}
return [ $name, $parameters ];
}
/**
* Get the array of configured pipes.
*
* @return array
*/
protected function pipes(): array {
return $this->pipes;
}
/**
* Get the container instance.
*
* @throws \RuntimeException
*
* @return ContainerInterface
*/
protected function getContainer(): ContainerInterface {
if ( ! $this->container ) {
throw new RuntimeException( 'A container instance has not been passed to the Pipeline.' );
}
return $this->container;
}
/**
* Set the container instance.
*
* @param ContainerInterface $container
*
* @return $this
*/
public function setContainer( ContainerInterface $container ): Pipeline {
$this->container = $container;
return $this;
}
/**
* Handle the value returned from each pipe before passing it to the next.
*
* @param mixed $carry
*
* @return mixed
*/
protected function handleCarry( $carry ) {
return $carry;
}
/**
* Handle the given exception.
*
* @param mixed $passable
* @param \Throwable $e
*
* @throws \Throwable
*
* @return mixed
*/
protected function handleException( $passable, Throwable $e ) {
throw $e;
}
}

View File

@@ -0,0 +1,46 @@
<?php
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink;
/**
* A helper class for registering StellarWP Uplink resources.
*/
class Register
{
/**
* Register a plugin resource.
*
* @since 1.0.0
*
* @param string $slug Resource slug.
* @param string $name Resource name.
* @param string $version Resource version.
* @param string $path Resource path to bootstrap file.
* @param string $class Resource class.
* @param string $license_class Resource license class
*
* @return Resources\Resource
*/
public static function plugin($slug, $name, $version, $path, $class, $license_class = null)
{
return \KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources\Plugin::register($slug, $name, $version, $path, $class, $license_class);
}
/**
* Register a service resource.
*
* @since 1.0.0
*
* @param string $slug Resource slug.
* @param string $name Resource name.
* @param string $version Resource version.
* @param string $path Resource path to bootstrap file.
* @param string $class Resource class.
* @param string $license_class Resource license class.
*
* @return Resources\Resource
*/
public static function service($slug, $name, $version, $path, $class, $license_class = null)
{
return \KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources\Service::register($slug, $name, $version, $path, $class, $license_class);
}
}

View File

@@ -0,0 +1,232 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources;
use ArrayAccess;
use ArrayIterator;
use Countable;
use Iterator;
class Collection implements ArrayAccess, Iterator, Countable {
/**
* Collection of resources.
*
* @var array<string, Resource>
*/
private $resources;
/**
* The original Iterator, for memoization.
*
* @var Iterator<string, Resource>|null
*/
private $iterator;
/**
* @param Iterator<string, Resource>|array<string, Resource> $resources An array or iterator of Resources.
*/
public function __construct( $resources = [] ) {
if ( $resources instanceof Iterator ) {
$this->iterator = $resources;
$resources = iterator_to_array( $resources );
}
$this->resources = $resources;
}
/**
* Adds a resource to the collection.
*
* @since 1.0.0
*
* @param Resource $resource Resource instance.
*
* @return Resource
*/
public function add( Resource $resource ): Resource {
if ( ! $this->offsetExists( $resource->get_slug() ) ) {
$this->offsetSet( $resource->get_slug(), $resource );
}
return $this->offsetGet( $resource->get_slug() );
}
/**
* @return Resource
*/
#[\ReturnTypeWillChange]
public function current(): Resource {
return current( $this->resources );
}
/**
* Gets the resource with the given path.
*
* @since 1.0.0
*
* @param string $path Path to filter collection by.
* @param Iterator<string, Resource>|null $iterator Optional. Iterator to filter.
*
* @return self
*/
public function get_by_path( string $path, ?Iterator $iterator = null ): self {
$results = new Filters\Path_FilterIterator( $iterator ?: $this->getIterator(), [ $path ] );
return new self( $results );
}
/**
* Gets the resource with the given paths.
*
* @since 1.0.0
*
* @param array<string> $paths Paths to filter collection by.
* @param Iterator<string, Resource>|null $iterator Optional. Iterator to filter.
*
* @return self
*/
public function get_by_paths( array $paths, ?Iterator $iterator = null ): self {
$results = new Filters\Path_FilterIterator( $iterator ?: $this->getIterator(), $paths );
return new self( $results );
}
/**
* Gets the plugin resources.
*
* @since 1.0.0
*
* @param Iterator<string, Resource>|null $iterator Optional. Iterator to filter.
*
* @return self
*/
public function get_plugins( ?Iterator $iterator = null ): self {
$results = new Filters\Plugin_FilterIterator( $iterator ?: $this->getIterator() );
return new self( $results );
}
/**
* Gets the service resources.
*
* @since 1.0.0
*
* @param Iterator<string, Resource>|null $iterator Optional. Iterator to filter.
*
* @return self
*/
public function get_services( ?Iterator $iterator = null ): self {
$results = new Filters\Service_FilterIterator( $iterator ?: $this->getIterator() );
return new self( $results );
}
/**
* @return array-key|null
*/
#[\ReturnTypeWillChange]
public function key() {
return key( $this->resources );
}
/**
* @inheritDoc
*/
public function next(): void {
next( $this->resources );
}
/**
* @inheritDoc
*/
public function offsetExists( $offset ): bool {
return array_key_exists( $offset, $this->resources );
}
/**
* @return Resource|null
*/
#[\ReturnTypeWillChange]
public function offsetGet( $offset ): ?Resource {
return $this->resources[ $offset ] ?? null;
}
/**
* @inheritDoc
*/
public function offsetSet( $offset, $value ): void {
$this->resources[ $offset ] = $value;
}
/**
* @inheritDoc
*/
public function offsetUnset( $offset ): void {
unset( $this->resources[ $offset ] );
}
/**
* Helper function for removing a resource from the collection.
*
* @since 1.0.0
*
* @param string $slug Resource slug.
*
* @return void
*/
public function remove( string $slug ): void {
$this->offsetUnset( $slug );
}
/**
* @inheritDoc
*/
public function rewind(): void {
reset( $this->resources );
}
/**
* Sets a resource in the collection.
*
* @since 1.0.0
*
* @param string $slug Resource slug.
* @param Resource $resource Resource instance.
*
* @return Resource|null
*/
public function set( string $slug, Resource $resource ): ?Resource {
$this->offsetSet( $slug, $resource );
return $this->offsetGet( $slug );
}
/**
* @inheritDoc
*/
public function valid(): bool {
return key( $this->resources ) !== null;
}
/**
* @inheritDoc
*/
public function count(): int {
return count( $this->resources );
}
/**
* Returns a clone of the underlying iterator.
*
* @return Iterator<string, Resource>
*/
public function getIterator(): Iterator {
if ( isset( $this->iterator ) ) {
return $this->iterator;
}
return $this->iterator = new ArrayIterator( $this->resources );
}
}

View File

@@ -0,0 +1,56 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources\Filters;
use Countable;
use FilterIterator;
use Iterator;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources\Plugin;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources\Resource;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources\Service;
/**
* @method Resource|Plugin|Service current()
*/
class Path_FilterIterator extends FilterIterator implements Countable {
/**
* Paths to filter.
*
* @since 1.0.0
*
* @var array<string>
*/
private $paths;
/**
* Constructor.
*
* @since 1.0.0
*
* @param Iterator<string, Resource> $iterator Iterator to filter.
* @param string[] $paths Paths to filter.
*/
public function __construct( Iterator $iterator, array $paths ) {
parent::__construct( $iterator );
$this->paths = $paths;
}
/**
* @inheritDoc
*/
public function accept(): bool {
$resource = $this->getInnerIterator()->current();
return in_array( $resource->get_path(), $this->paths, true );
}
/**
* @inheritDoc
*/
public function count() : int {
return iterator_count( $this );
}
}

View File

@@ -0,0 +1,30 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources\Filters;
use Countable;
use FilterIterator;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources\Plugin;
/**
* @method Plugin current()
*/
class Plugin_FilterIterator extends FilterIterator implements Countable {
/**
* @inheritDoc
*/
public function accept(): bool {
$resource = $this->getInnerIterator()->current();
return 'plugin' === $resource->get_type();
}
/**
* @inheritDoc
*/
public function count() : int {
return iterator_count( $this );
}
}

View File

@@ -0,0 +1,30 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources\Filters;
use Countable;
use FilterIterator;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources\Service;
/**
* @method Service current()
*/
class Service_FilterIterator extends FilterIterator implements Countable {
/**
* @inheritDoc
*/
public function accept(): bool {
$resource = $this->getInnerIterator()->current();
return 'service' === $resource->get_type();
}
/**
* @inheritDoc
*/
public function count() : int {
return iterator_count( $this );
}
}

View File

@@ -0,0 +1,422 @@
<?php
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources;
use KadenceWP\KadenceBlocks\StellarWP\ContainerContract\ContainerInterface;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\License\License_Manager;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Config;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Site\Data;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Utils;
class License {
/**
* How often to check for updates (in hours).
*
* @var int
*/
protected $check_period = 12;
/**
* Container instance.
*
* @since 1.0.0
*
* @var ContainerInterface
*/
protected $container;
/**
* License key.
*
* @since 1.0.0
*
* @var string|null
*/
protected $key;
/**
* License origin.
*
* network_option
* site_option
* file
*
* @since 1.0.0
*
* @var string
*/
protected $key_origin;
/**
* License origin code.
*
* m = manual
* e = embedded
* o = original
*
* @since 1.0.0
*
* @var string
*/
protected $key_origin_code;
/**
* Option prefix for the key.
*
* @since 1.0.0
*
* @var string
*/
public static $key_option_prefix = 'stellarwp_uplink_license_key_';
/**
* Option prefix for the key status.
*
* @since 1.0.0
*
* @var string
*/
public static $key_status_option_prefix = 'stellarwp_uplink_license_key_status_';
/**
* Resource instance.
*
* @since 1.0.0
*
* @var Resource
*/
protected $resource;
/**
* Constructor.
*
* @since 1.0.0
*
* @param Resource $resource The resource instance.
* @param ContainerInterface|null $container Container instance.
*/
public function __construct( Resource $resource, $container = null ) {
$this->resource = $resource;
$this->container = $container ?: Config::get_container();
}
/**
* Deletes the key in site options.
*
* @since 1.0.0
*
* @param string $type Type of key (network, local).
*
* @return bool
*/
public function delete_key( string $type = 'local' ): bool {
if ( 'network' === $type && is_multisite() ) {
return delete_network_option( 0, $this->get_key_option_name() );
}
return delete_option( $this->get_key_option_name() );
}
/**
* Get the license key.
*
* @since 1.0.0
*
* @param string $type The type of key to get (any, network, local, default).
*
* @return string
*/
public function get_key( $type = 'any' ) {
if ( empty( $this->key ) && ( 'any' === $type || 'network' === $type ) ) {
$this->key = $this->get_key_from_network_option();
if ( ! empty( $this->key ) ) {
$this->key_origin = 'network_option';
}
}
if ( empty( $this->key ) && ( 'any' === $type || 'local' === $type ) ) {
$this->key = $this->get_key_from_option();
if ( ! empty( $this->key ) ) {
$this->key_origin = 'site_option';
}
}
if ( empty( $this->key ) && ( 'any' === $type || 'default' === $type ) ) {
$this->key = $this->get_key_from_license_file();
if ( ! empty( $this->key ) ) {
$this->key_origin = 'file';
}
}
/**
* Filter the license key.
*
* @since 1.0.0
*
* @param string|null $key The license key.
*/
$key = apply_filters( 'stellarwp/uplink/' . Config::get_hook_prefix(). '/license_get_key', $this->key );
return $key ?: '';
}
/**
* Get the license key from a class that holds the license key.
*
* @since 1.0.0
*
* @return string|null
*/
protected function get_key_from_license_file() {
$license_class = $this->resource->get_license_class();
$key = null;
if ( empty( $license_class ) ) {
return null;
}
if ( defined( $license_class . '::KEY' ) ) {
$key = $license_class::KEY;
} elseif ( defined( $license_class . '::DATA' ) ) {
$key = $license_class::DATA;
}
return $key;
}
/**
* Get the license key from a network option.
*
* @since 1.0.0
*
* @return string|null
*/
protected function get_key_from_network_option() {
if ( ! is_multisite() ) {
return null;
}
if ( ! $this->resource->is_network_activated() ) {
return null;
}
/** @var string|null */
return get_network_option( 0, $this->get_key_option_name(), null );
}
/**
* Get the license key from an option.
*
* @since 1.0.0
*
* @return string|null
*/
protected function get_key_from_option() {
/** @var string|null */
return get_option( $this->get_key_option_name(), null );
}
/**
* Get the option name for the license key.
*
* @since 1.0.0
*
* @return string
*/
public function get_key_option_name(): string {
return static::$key_option_prefix . $this->resource->get_slug();
}
/**
* Get the license key origin code.
*
* @since 1.0.0
*
* @return string
*/
public function get_key_origin_code(): string {
if ( ! empty( $this->key_origin_code ) ) {
return $this->key_origin_code;
}
$key = $this->get_key();
$default_key = $this->get_key( 'default' );
if ( $key === $default_key ) {
$this->key_origin_code = 'o';
} elseif ( 'file' === $this->key_origin ) {
$this->key_origin_code = 'e';
} else {
$this->key_origin_code = 'm';
}
return $this->key_origin_code;
}
/**
* Get the license key status from an option.
*
* @since 1.0.0
*
* @return string|null
*/
protected function get_key_status(): ?string {
$network = $this->container->get( License_Manager::class )->allows_multisite_license( $this->resource );
$func = 'get_option';
if ( $network ) {
$func = 'get_site_option';
}
/** @var string|null */
$status = $func( $this->get_key_status_option_name(), 'invalid' );
$key = $this->get_key( $network ? 'network' : 'local' );
if ( null === $status && $key ) {
$this->resource->validate_license( $key, $network );
$status = $func( $this->get_key_status_option_name(), 'invalid' );
}
return $status;
}
/**
* Get the option name for the license key status.
*
* @since 1.0.0
*
* @return string
*/
public function get_key_status_option_name(): string {
/** @var Data */
$data = $this->container->get( Data::class );
return static::$key_status_option_prefix . $this->resource->get_slug() . '_'. $data->get_site_domain();
}
/**
* Whether the plugin is network activated and licensed or not.
*
* @since 1.0.0
*
* @return bool
*/
public function is_network_licensed() {
$is_network_licensed = false;
if ( ! is_network_admin() && $this->resource->is_network_activated() ) {
$network_key = $this->get_key( 'network' );
$local_key = $this->get_key( 'local' );
// Check whether the network is licensed and NOT overridden by local license
if ( $network_key && ( empty( $local_key ) || $local_key === $network_key ) ) {
$is_network_licensed = true;
}
}
return $is_network_licensed;
}
/**
* Whether the plugin is validly licensed or not.
*
* @since 1.0.0
*
* @return bool
*/
public function is_valid() {
return 'valid' === $this->get_key_status();
}
/**
* Whether the plugin license is expired or not.
*
* @since 1.0.0
*
* @return bool
*/
public function is_expired(): bool {
return 'expired' === $this->get_key_status();
}
/**
* Whether the validation has expired.
*
* @since 1.0.0
*
* @return bool
*/
public function is_validation_expired() {
$option_expiration = get_option( $this->get_key_status_option_name() . '_timeout', null );
return is_null( $option_expiration ) || ( time() > $option_expiration );
}
/**
* Sets the key in site options.
*
* @since 1.0.0
*
* @param string $key License key.
* @param string $type Type of key (network, local).
*
* @return bool
*/
public function set_key( string $key, string $type = 'local' ): bool {
$key = Utils\Sanitize::key( $key );
$this->key = $key;
if ( 'network' === $type && is_multisite() && $this->resource->is_network_activated() ) {
// WordPress would otherwise return false if the keys already match.
if ( $this->get_key_from_network_option() === $key ) {
return true;
}
return update_network_option( 0, $this->get_key_option_name(), $key );
}
// WordPress would otherwise return false if the keys already match.
if ( $this->get_key_from_option() === $key ) {
return true;
}
return update_option( $this->get_key_option_name(), $key );
}
/**
* Sets the key status based on the key validation check results.
*
* @since TBD
*
* @param int $valid 0 for invalid, 1 or 2 for valid.
*
* @return void
*/
public function set_key_status( $valid ): void {
$status = Utils\Checks::is_truthy( $valid ) ? 'valid' : 'invalid';
$network = $this->container->get( License_Manager::class )->allows_multisite_license( $this->resource );
$timeout = $this->check_period * HOUR_IN_SECONDS;
$func = 'update_option';
if ( $network ) {
$func = 'update_site_option';
}
$func( $this->get_key_status_option_name(), $status );
$func( $this->get_key_status_option_name() . '_timeout', $timeout );
}
/**
* Get the key as a string.
*
* @since 1.0.0
*
* @return string
*/
public function __toString(): string {
return $this->get_key() ?: '';
}
}

View File

@@ -0,0 +1,189 @@
<?php
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Admin\Notice;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\API\Validation_Response;
class Plugin extends Resource {
/**
* Plugin update status.
*
* @since 1.0.0
*
* @var \stdClass|null
*/
protected $update_status;
/**
* @inheritDoc
*/
protected $type = 'plugin';
/**
* Update status for the resource.
*
* @since 1.0.0
*
* @var string
*/
public static $update_status_option_prefix = 'stellarwp_uplink_update_status_';
/**
* Check for plugin updates.
*
* @since 1.0.0
*
* @param mixed $transient The pre-saved value of the `update_plugins` site transient.
* @param bool $force_fetch Force fetching the update status.
*
* @return mixed
*/
public function check_for_updates( $transient, $force_fetch = false ) {
if ( ! is_object( $transient ) ) {
return $transient;
}
// Allow .org plugins to opt out of update checks.
if ( apply_filters( 'stellarwp/uplink/' . $this->get_slug() . '/prevent_update_check', false ) ) {
return $transient;
}
$status = $this->get_update_status( $force_fetch );
$status->last_check = time();
$status->checked_version = $this->get_installed_version();
// Save before actually doing the checking just in case something goes wrong. We don't want to continually recheck.
$this->set_update_status( $status );
$results = $this->validate_license();
$status->update = $results->get_raw_response();
// Prevent an empty class from being saved in the $transient.
if ( isset( $status->update->version ) ) {
$product_path = $this->get_path();
if ( version_compare( $this->get_version_from_response( $results ), $this->get_installed_version(), '>' ) ) {
/** @var \stdClass $transient */
if ( ! isset( $transient->response ) ) {
$transient->response = [];
}
$transient->response[ $product_path ] = $results->get_update_details();
// Clear the no_update property if it exists.
if ( isset( $transient->no_update[ $product_path ] ) ) {
unset( $transient->no_update[ $product_path ] );
}
if ( 'expired' === $results->get_result() ) {
$this->container->get( Notice::class )->add_notice( Notice::EXPIRED_KEY, $this->get_slug() );
}
} else {
// Clean up any stale update info.
if ( isset( $transient->response[ $product_path ] ) ) {
unset( $transient->response[ $product_path ] );
}
/**
* If the plugin is up to date, we need to add it to the `no_update` property so that enable auto updates can appear correctly in the UI.
*
* See this post for more information:
* @link https://make.wordpress.org/core/2020/07/30/recommended-usage-of-the-updates-api-to-support-the-auto-updates-ui-for-plugins-and-themes-in-wordpress-5-5/
*/
/** @var \stdClass $transient */
if ( ! isset( $transient->no_update ) ) {
$transient->no_update = [];
}
$transient->no_update[ $product_path ] = $results->get_update_details();
}
// In order to show relevant issues on plugins page parse response data and add it to transient
if ( version_compare( $this->get_version_from_response( $results ), $this->get_installed_version(), '>' ) && in_array( $results->get_result(), [ 'expired', 'invalid' ] ) ) {
/** @var \stdClass $transient */
if ( ! isset( $transient->response ) ) {
$transient->response = [];
}
$transient->response[ $product_path ] = $results->handle_api_errors();
}
}
$this->set_update_status( $status );
return $transient;
}
/**
* Retrieve version from response
*
* @param Validation_Response $response
*
* @return string
*/
protected function get_version_from_response( $response ): string {
if ( ! isset( $response->get_raw_response()->version ) ) {
return '';
}
return $response->get_raw_response()->version;
}
/**
* Get the update status of the plugin.
*
* @since 1.0.0
*
* @param bool $force_fetch Force fetching the update status.
*
* @return mixed
*/
public function get_update_status( $force_fetch = false ) {
if ( ! $force_fetch ) {
$this->update_status = get_option( $this->get_update_status_option_name(), null );
}
if ( ! is_object( $this->update_status ) ) {
$this->update_status = (object) [
'last_check' => 0,
'checked_version' => '',
'update' => null,
];
}
return $this->update_status;
}
/**
* Gets the update status option name.
*
* @since 1.0.0
*
* @return string
*/
protected function get_update_status_option_name(): string {
return static::$update_status_option_prefix . $this->get_slug();
}
/**
* @inheritDoc
*/
public static function register( $slug, $name, $version, $path, $class, string $license_class = null ) {
return parent::register_resource( static::class, $slug, $name, $version, $path, $class, $license_class );
}
/**
* Updates the update status value in options.
*
* @since 1.0.0
*
* @param mixed $status
*
* @return void
*/
protected function set_update_status( $status ) {
update_option( $this->get_update_status_option_name(), $status );
}
}

View File

@@ -0,0 +1,531 @@
<?php
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources;
use stdClass;
use KadenceWP\KadenceBlocks\StellarWP\ContainerContract\ContainerInterface;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\API;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Config;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Exceptions;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Site\Data;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Utils;
/**
* The base resource class for StellarWP Uplink plugins and services.
*
* @property-read string $class The class name.
* @property-read ContainerInterface $container Container instance.
* @property-read string $type The resource type.
* @property-read string $license_key License key.
* @property-read string $name The resource name.
* @property-read string $slug The resource slug.
* @property-read string $version The resource version.
* @property-read string $path The resource path.
*/
abstract class Resource {
/**
* Resource class.
*
* @since 1.0.0
*
* @var string
*/
protected $class;
/**
* Container instance.
*
* @since 1.0.0
*
* @var ContainerInterface
*/
protected $container;
/**
* Resource type.
*
* @since 1.0.0
*
* @var string
*/
protected $type = 'resource';
/**
* License object.
*
* @since 1.0.0
*
* @var License
*/
protected $license;
/**
* License class.
*
* @since 1.0.0
*
* @var string|null
*/
protected $license_class;
/**
* Resource name.
*
* @since 1.0.0
*
* @var string
*/
protected $name;
/**
* Resource path to bootstrap file.
*
* @since 1.0.0
*
* @var string
*/
protected $path;
/**
* Resource slug.
*
* @since 1.0.0
*
* @var string
*/
protected $slug;
/**
* Resource version.
*
* @since 1.0.0
*
* @var string
*/
protected $version;
/**
* Resource home url
*
* @since 1.0.0
*
* @var string
*/
protected $home_url;
/**
* Constructor.
*
* @since 1.0.0
*
* @param string $slug Resource slug.
* @param string $name Resource name.
* @param string $version Resource version.
* @param string $path Resource path to bootstrap file.
* @param string $class Resource class.
* @param string|null $license_class Class that holds the embedded license key.
*/
public function __construct( $slug, $name, $version, $path, $class, string $license_class = null ) {
$this->name = $name;
$this->slug = $slug;
$this->path = $path;
$this->class = $class;
$this->license_class = $license_class;
$this->version = $version;
$this->container = Config::get_container();
}
/**
* Deletes the resource license key.
*
* @since 1.0.0
*
* @param string $type The type of key to get (any, network, local, default).
*
* @return bool
*/
public function delete_license_key( $type = 'local' ): bool {
return $this->get_license_object()->delete_key( $type );
}
/**
* Gets the resource class.
*
* @since 1.0.0
*
* @return string
*/
public function get_class() {
return $this->class;
}
/**
* Get the arguments for generating the download URL.
*
* @since 1.0.0
*
* @return array<mixed>
*/
public function get_download_args() {
$args = [];
/** @var Data */
$data = $this->container->get( Data::class );
$args['plugin'] = sanitize_text_field( $this->get_slug() );
$args['installed_version'] = sanitize_text_field( $this->get_installed_version() ?: '' );
$args['domain'] = sanitize_text_field( $data->get_domain( true ) );
// get general stats
/** @var array<string,array<mixed>> */
$stats = $data->get_stats();
$args['multisite'] = $stats['network']['multisite'];
$args['network_activated'] = (int) $this->is_network_activated();
$args['active_sites'] = $stats['network']['active_sites'];
$args['wp_version'] = $stats['versions']['wp'];
// the following is for install key inclusion (will apply later with PUE addons.)
$args['key'] = Utils\Sanitize::key( $this->get_license_object()->get_key() ?: '' );
$args['dk'] = Utils\Sanitize::key( $this->get_license_object()->get_key( 'default' ) ?: '' );
$args['o'] = sanitize_text_field( $this->get_license_object()->get_key_origin_code() );
return $args;
}
/**
* Get the currently installed version of the plugin.
*
* @since 1.0.0
*
* @return string
*/
public function get_installed_version(): string {
if ( ! function_exists( 'get_plugin_data' ) ) {
require_once ABSPATH . 'wp-admin/includes/plugin.php';
}
// @phpstan-ignore-next-line
$plugin_data = get_plugin_data( WP_PLUGIN_DIR . '/' . $this->get_path() );
return $plugin_data['Version'] ?: '';
}
/**
* Get the license class.
*
* @since 1.0.0
*
* @return string|null
*/
public function get_license_class() {
return $this->license_class;
}
/**
* Gets the resource license key.
*
* @since 1.0.0
*
* @param string $type The type of key to get (any, network, local, default).
*
* @return string
*/
public function get_license_key( $type = 'any' ): string {
return $this->get_license_object()->get_key( $type );
}
/**
* Get the license object.
*
* @since 1.0.0
*
* @return License
*/
public function get_license_object() {
if ( null === $this->license ) {
$this->license = new License( $this );
}
return $this->license;
}
/**
* Gets the resource name.
*
* @since 1.0.0
*
* @return string
*/
public function get_name() {
return $this->name;
}
/**
* Gets the resource path.
*
* @since 1.0.0
*
* @return string
*/
public function get_path() {
return $this->path;
}
/**
* Gets the resource slug.
*
* @since 1.0.0
*
* @return string
*/
public function get_slug() {
/**
* Filter the resource slug.
*
* @since 1.0.0
*
* @param string $slug Resource slug.
*/
return apply_filters( 'stellarwp/uplink/' . Config::get_hook_prefix(). '/resource_get_slug', $this->slug );
}
/**
* Gets the resource type.
*
* @since 1.0.0
*
* @return string
*/
public function get_type() {
return $this->type;
}
/**
* Get the arguments for generating the validation URL.
*
* @since 1.0.0
*
* @return array<string,mixed>
*/
public function get_validation_args() {
$args = [];
$args['key'] = Utils\Sanitize::key( $this->get_license_object()->get_key() ?: '' );
$args['default_key'] = Utils\Sanitize::key( $this->get_license_object()->get_key( 'default' ) ?: '' );
$args['license_origin'] = sanitize_text_field( $this->get_license_object()->get_key_origin_code() );
$args['plugin'] = sanitize_text_field( $this->get_slug() );
$args['version'] = sanitize_text_field( $this->get_installed_version() ?: '' );
return $args;
}
/**
* Gets the resource version.
*
* @since 1.0.0
*
* @return string
*/
public function get_version() {
/**
* Filter the resource version.
*
* @since 1.0.0
*
* @param string $version Resource version.
*/
return apply_filters( 'stellarwp/uplink/' . Config::get_hook_prefix(). '/resource_get_version', $this->version );
}
public function get_home_url(): ?string {
return $this->home_url;
}
/**
* Returns whether or not the license is listed as valid.
*
* @since 1.0.0
*
* @return bool
*/
public function has_valid_license(): bool {
return $this->get_license_object()->is_valid();
}
/**
* Checks if the resource is installed at the network level.
*
* @since 1.0.0
*
* @return bool
*/
public function is_network_activated() {
if ( ! is_multisite() ) {
return false;
}
if( ! function_exists( 'get_plugin_data' ) ) {
require_once ABSPATH . 'wp-admin/includes/plugin.php';
}
return is_plugin_active_for_network( $this->get_path() );
}
/**
* Whether the plugin is network activated and licensed or not.
*
* @since 1.0.0
*
* @return bool
*/
public function is_network_licensed(): bool {
return $this->get_license_object()->is_network_licensed();
}
/**
* Register a resource and add it to the collection.
*
* @since 1.0.0
*
* @param string $name Resource name.
* @param string $slug Resource slug.
* @param string $path Resource path to bootstrap file.
* @param string $version Resource version.
* @param string $class Resource class.
* @param string|null $license_class Class that holds the embedded license key.
*
* @return Resource
*/
abstract public static function register( $name, $slug, $path, $class, $version, string $license_class = null );
/**
* Register a resource and add it to the collection.
*
* @since 1.0.0
*
* @param string $resource_class Resource class.
* @param string $slug Resource slug.
* @param string $name Resource name.
* @param string $version Resource version.
* @param string $path Resource path to bootstrap file.
* @param string $class Resource class.
* @param string|null $license_class Class that holds the embedded license key.
*
* @return Resource
*/
public static function register_resource( $resource_class, $slug, $name, $version, $path, $class, string $license_class = null ) {
/** @var Resource */
$resource = new $resource_class( $slug, $name, $version, $path, $class, $license_class );
/** @var Collection */
$collection = Config::get_container()->get( Collection::class );
/**
* Filters the registered plugin before adding to the collection.
*
* @since 1.0.0
*
* @param Resource $resource Resource instance.
*/
$resource = apply_filters( 'stellarwp/uplink/' . Config::get_hook_prefix(). '/resource_register_before_collection', $resource );
if ( ! empty( $collection[ $resource->get_slug() ] ) ) {
throw new Exceptions\ResourceAlreadyRegisteredException( $resource->get_slug() );
}
$collection->add( $resource );
/**
* Filters the registered resource.
*
* @since 1.0.0
*
* @param Resource $resource Resource instance.
*/
$resource = apply_filters( 'stellarwp/uplink/' . Config::get_hook_prefix(). '/resource_register', $resource );
return $resource;
}
/**
* Sets the license key for the resource.
*
* @since 1.0.0
*
* @param string $key License key.
* @param string $type The type of key to get (any, network, local, default).
*
* @return bool
*/
public function set_license_key( $key, $type = 'local' ): bool {
return $this->get_license_object()->set_key( $key, $type );
}
/**
* Set plugin home url
*
* @param string $url
*
* @return string
*/
public function set_home_url( $url = '' ): string {
$this->home_url = $url;
return $this->home_url;
}
/**
* Returns whether or not the license key is in need of validation.
*
* @since 1.0.0
*
* @return bool
*/
public function should_validate(): bool {
return $this->get_license_object()->is_validation_expired();
}
/**
* Validates the resource's license key.
*
* @since 1.0.0
*
* @param string|null $key License key.
* @param bool $do_network_validate Validate the key as a network key.
*
* @return API\Validation_Response
*/
public function validate_license( ?string $key = null, bool $do_network_validate = false ) {
/** @var API\Client */
$api = $this->container->get( API\Client::class );
$validation_type = $do_network_validate ? 'network' : 'local';
if ( empty( $key ) ) {
$key = $this->get_license_key( $validation_type );
}
if ( empty( $key ) ) {
$results = new API\Validation_Response( null, $validation_type, new stdClass(), $this );
$results->set_is_valid( false );
return $results;
}
$results = $api->validate_license( $this, $key, $validation_type );
$results_key = $results->get_key();
$result_type = $results->get_result();
$has_replacement_key = $results->has_replacement_key();
if (
$result_type === 'new'
|| $has_replacement_key
) {
$this->get_license_object()->set_key( $results_key, $validation_type );
}
$this->get_license_object()->set_key_status( $results->is_valid() );
return $results;
}
}

View File

@@ -0,0 +1,17 @@
<?php
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources;
class Service extends Resource {
/**
* @inheritDoc
*/
protected $type = 'service';
/**
* @inheritDoc
*/
public static function register( $slug, $name, $version, $path, $class, string $license_class = null ) {
return parent::register_resource( static::class, $slug, $name, $version, $path, $class, $license_class );
}
}

View File

@@ -0,0 +1,575 @@
<?php
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Site;
use KadenceWP\KadenceBlocks\StellarWP\ContainerContract\ContainerInterface;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Config;
class Data {
/**
* Container.
*
* @since 1.0.0
*
* @var ContainerInterface
*/
protected $container;
/**
* Constructor.
*
* @since 1.0.0
*/
public function __construct() {
// @phpstan-ignore-next-line
$this->container = Config::get_container();
}
/**
* Build full stats for endpoints
*
* @since 1.0.0
*
* @param array<string,array<mixed>> $stats Initial stats
*
* @return array<string,mixed>
*/
protected function build_full_stats( array $stats ): array {
$stats['versions']['php'] = $this->get_php_version();
$stats['versions']['mysql'] = $this->get_db_version();
$stats['theme'] = $this->get_theme_info();
$stats['site_language'] = $this->get_site_language();
$stats['user_language'] = $this->get_user_language();
$stats['is_public'] = $this->is_public();
$stats['wp_debug'] = $this->is_debug_enabled();
$stats['site_timezone'] = $this->get_timezone();
$stats['totals'] = $this->get_totals();
return $stats;
}
/**
* Build stats for sending to the license server.
*
* @since 1.0.0
*
* @return array<string,array<mixed>>
*/
protected function build_stats(): array {
$stats = [
'versions' => [
'wp' => $this->get_wp_version(),
],
'network' => [
'multisite' => (int) is_multisite(),
'network_activated' => 0,
'active_sites' => $this->get_multisite_active_sites(),
],
];
return $stats;
}
/**
* Gets the database version.
*
* @since 1.0.0
*
* @return string
*/
public function get_db_version(): string {
global $wpdb;
$version = $wpdb->db_version();
/**
* Filters the DB version.
*
* @since 1.0.0
*
* @param string $version DB version.
*/
$version = apply_filters( 'stellarwp/uplink/' . Config::get_hook_prefix(). '/get_db_version', $version );
return sanitize_text_field( $version );
}
/**
* Gets the domain for the site.
*
* @since 1.0.0
*
* @param bool $original Return the original domain without any added hashes.
*
* @throws \RuntimeException
*
* @return string
*/
public function get_domain( bool $original = false ): string {
$cache_key = 'stellarwp_uplink_domain';
$domain = $this->container->has( $cache_key ) ? $this->container->get( $cache_key ) : null;
$allows_network_subfolder_license = Config::allows_network_subfolder_license();
if ( is_multisite() ) {
// Ensure subsite also contains its path and don't cache.
if ( ! $allows_network_subfolder_license ) {
$domain = $this->get_domain_multisite_subsite_subfolder();
} elseif ( $domain === null ) {
$domain = $this->get_domain_multisite_option();
$this->container->bind( $cache_key, function() use ( $domain ) { return $domain; } );
}
/*
* Append a hash to the end of the main site domain when on multisite and network licenses
* are allowed.
*
* This prevents the main site from refreshing the token on the Licensing server
* when multisite is off or network licenses aren't enabled.
*/
if ( ! $original && Config::allows_network_licenses() ) {
$domain .= '/' . hash( 'crc32c', $domain );
}
} elseif ( $domain === null ) {
$domain = $this->get_site_domain();
$this->container->bind( $cache_key, function() use ( $domain ) { return $domain; } );
}
/**
* Filters the domain for the site.
*
* @since 1.0.0
*
* @param string $domain Domain.
* @param bool $allows_network_subfolder_license Whether network subfolder licenses are allowed.
*/
$domain = apply_filters( 'stellarwp/uplink/' . Config::get_hook_prefix(). '/get_domain', $domain, $allows_network_subfolder_license );
return sanitize_text_field( $domain );
}
/**
* Return domain for multisite
*
* @return string
*/
protected function get_domain_multisite_option(): string {
/** @var string */
$site_url = get_site_option( 'siteurl', '' ) ?: get_site_url(); // Fallback to get_site_url function if the network site url is empty which is possible.
/** @var array<string> */
$site_url = wp_parse_url( $site_url );
if ( ! $site_url || ! isset( $site_url['host'] ) ) {
return '';
}
return strtolower( $site_url['host'] );
}
/**
* When network licensing for multisite subfolders isn't active,
* each subsite domain needs to be unique, so we'll include the
* subfolder path.
*
* @return string
*/
protected function get_domain_multisite_subsite_subfolder(): string {
if ( is_main_site() ) {
return $this->get_domain_multisite_option();
}
$url = get_site_url();
$url = wp_parse_url( $url );
if ( ! $url || ! isset( $url['host'] ) ) {
return '';
}
$domain = $url['host'];
// Append the multisite subfolder path.
if ( ! empty( $url['path'] ) && $url['path'] !== '/' ) {
$domain .= $url['path'];
}
return strtolower( $domain );
}
/**
* Gets multi-site active site count.
*
* @since 1.0.0
*
* @return int
*/
public function get_multisite_active_sites(): int {
global $wpdb;
$cache_key = 'stellarwp_uplink_multisite_active_sites';
/** @var int|null */
$active_sites = $this->container->has( $cache_key ) ? $this->container->get( $cache_key ) : null;
if ( null === $active_sites ) {
if ( ! is_multisite() ) {
$active_sites = 1;
} else {
$sql_count = "
SELECT
COUNT( `blog_id` )
FROM
`{$wpdb->blogs}`
WHERE
`public` = '1'
AND `archived` = '0'
AND `spam` = '0'
AND `deleted` = '0'
";
$active_sites = (int) $wpdb->get_var( $sql_count );
}
$this->container->bind( $cache_key, function() use ( $active_sites ) { return $active_sites; } );
}
/**
* Filters the active site count for the site.
*
* @since 1.0.0
*
* @param int $active_sites Number of active sites.
*/
$active_sites = apply_filters( 'stellarwp/uplink/' . Config::get_hook_prefix(). '/get_multisite_active_sites', $active_sites );
return (int) $active_sites;
}
/**
* Gets the PHP version.
*
* @since 1.0.0
*
* @return string
*/
public function get_php_version(): string {
$version = phpversion();
/**
* Filters the PHP version.
*
* @since 1.0.0
*
* @param string $version PHP version.
*/
$version = apply_filters( 'stellarwp/uplink/' . Config::get_hook_prefix(). '/get_php_version', $version );
return sanitize_text_field( $version );
}
/**
* Returns the domain of the single site installation
*
* Will try to read it from the $_SERVER['SERVER_NAME'] variable
* and fall back on the one contained in the siteurl option.
*
* @since 1.0.0
*
* @return string
*/
public function get_site_domain() {
/** @var string */
$site_url = get_option( 'siteurl', '' );
/** @var array<string> */
$site_url = wp_parse_url( $site_url );
if ( ! $site_url || ! isset( $site_url['host'] ) ) {
if ( isset( $_SERVER['SERVER_NAME'] ) ) {
return $_SERVER['SERVER_NAME'];
}
return '';
}
return strtolower( $site_url['host'] );
}
/**
* Gets the site language.
*
* @since 1.0.0
*
* @return string
*/
public function get_site_language(): string {
$locale = get_locale();
/**
* Filters the locale.
*
* @since 1.0.0
*
* @param string $locale Site language.
*/
$locale = apply_filters( 'stellarwp/uplink/' . Config::get_hook_prefix(). '/get_site_language', $locale );
return sanitize_text_field( $locale );
}
/**
* Build and get the stats
*
* @since 1.0.0
*
* @return array<string,mixed>
*/
public function get_stats(): array {
$stats = $this->build_stats();
/**
* Allow full stats data to be built and sent.
*
* @since 1.0.0
*
* @param boolean $use_full_stats Whether to send full stats
*/
$use_full_stats = apply_filters( 'stellarwp/uplink/' . Config::get_hook_prefix(). '/use_full_stats', false );
if ( $use_full_stats ) {
$stats = $this->build_full_stats( $stats );
}
/**
* Filter stats and allow plugins to add their own stats for tracking specific points of data.
*
* @since 1.0.0
*
* @param array<string,mixed> $stats Stats gathered by PUE Checker class.
* @param boolean $use_full_stats Whether to send full stats.
* @param Data $checker Data object.
*/
$stats = apply_filters( 'stellarwp/uplink/' . Config::get_hook_prefix(). '/get_stats', $stats, $use_full_stats, $this );
return $stats;
}
/**
* Gets the theme data.
*
* @since 1.0.0
*
* @return array<string>
*/
public function get_theme_info(): array {
$theme = wp_get_theme();
/** @var string */
$name = $theme->get( 'Name' );
/** @var string */
$version = $theme->get( 'Version' );
$info = [
'name' => sanitize_text_field( $name ),
'version' => sanitize_text_field( $version ),
'stylesheet' => sanitize_text_field( $theme->get_stylesheet() ),
'template' => sanitize_text_field( $theme->get_template() ),
];
/**
* Filters the theme info.
*
* @since 1.0.0
*
* @param array<string> $info Theme info.
*/
$info = apply_filters( 'stellarwp/uplink/' . Config::get_hook_prefix(). '/get_theme_info', $info );
return (array) $info;
}
/**
* Gets the timezone string.
*
* @since 1.0.0
*
* @return string
*/
public function get_timezone(): string {
$cache_key = 'stellarwp_uplink_timezone';
/** @var string|null */
$timezone = $this->container->has( $cache_key ) ? $this->container->get( $cache_key ) : null;
if ( null === $timezone ) {
$current_offset = get_option( 'gmt_offset', 0 );
if ( ! is_numeric( $current_offset ) ) {
$current_offset = 0;
}
/** @var string */
$tzstring = get_option( 'timezone_string', '' );
// Remove old Etc mappings. Fallback to gmt_offset.
if ( false !== strpos( $tzstring, 'Etc/GMT' ) ) {
$timezone = '';
}
// Create a UTC+- zone if no timezone string exists
if ( empty( $tzstring ) ) {
if ( 0 === $current_offset ) {
$timezone = 'UTC+0';
} elseif ( $current_offset < 0 ) {
$timezone = 'UTC' . $current_offset;
} else {
$timezone = 'UTC+' . $current_offset;
}
}
$this->container->bind( $cache_key, function() use ( $timezone ) { return $timezone; } );
}
/**
* Filters the timezone.
*
* @since 1.0.0
*
* @param string $timezone Site timezone.
*/
$timezone = apply_filters( 'stellarwp/uplink/' . Config::get_hook_prefix(). '/get_timezone', $timezone ?: '' );
return sanitize_text_field( $timezone );
}
/**
* Gets the site's post totals.
*
* @since 1.0.0
*
* @return array<int>
*/
public function get_totals(): array {
global $wpdb;
$cache_key = 'stellarwp_uplink_totals';
/** @var array<int>|null */
$totals = $this->container->has( $cache_key ) ? $this->container->get( $cache_key ) : null;
if ( null === $totals ) {
$totals = [
'all_post_types' => (int) $wpdb->get_var( "SELECT COUNT(1) FROM {$wpdb->posts}" ),
];
$this->container->bind( $cache_key, function() use ( $totals ) { return $totals; } );
}
/**
* Filters the site post totals.
*
* @since 1.0.0
*
* @param array<int> $totals Site post totals.
*/
$totals = apply_filters( 'stellarwp/uplink/' . Config::get_hook_prefix(). '/get_totals', $totals );
return (array) $totals;
}
/**
* Gets the user language.
*
* @since 1.0.0
*
* @return string
*/
public function get_user_language(): string {
$locale = get_user_locale();
/**
* Filters the locale.
*
* @since 1.0.0
*
* @param string $locale Site language.
*/
$locale = apply_filters( 'stellarwp/uplink/' . Config::get_hook_prefix(). '/get_user_language', $locale );
return sanitize_text_field( $locale );
}
/**
* Gets the WordPress version.
*
* @since 1.0.0
*
* @return string
*/
public function get_wp_version(): string {
global $wp_version;
$version = $wp_version;
/**
* Filters the WordPress version.
*
* @since 1.0.0
*
* @param string $wp_version WordPress version.
*/
$version = apply_filters( 'stellarwp/uplink/' . Config::get_hook_prefix(). '/get_wp_version', $version );
return sanitize_text_field( $version );
}
/**
* Gets the debug state.
*
* @since 1.0.0
*
* @return bool
*/
public function is_debug_enabled(): bool {
$debug_status = (bool) ( defined( 'WP_DEBUG' ) && WP_DEBUG );
/**
* Filters the Debug status.
*
* @since 1.0.0
*
* @param bool $debug_status Debug status.
*/
$debug_status = apply_filters( 'stellarwp/uplink/' . Config::get_hook_prefix(). '/is_debug_enabled', $debug_status );
return (bool) $debug_status;
}
/**
* Returns whether or not the site is public.
*
* @since 1.0.0
*
* @return bool
*/
public function is_public(): bool {
$cache_key = 'stellarwp_uplink_is_public';
/** @var bool|null */
$is_public = $this->container->has( $cache_key ) ? $this->container->get( $cache_key ) : null;
if ( null === $is_public ) {
$is_public = (bool) get_option('blog_public', false);
$this->container->bind( $cache_key, function() use ( $is_public ) { return $is_public; } );
}
/**
* Filters the DB version.
*
* @since 1.0.0
*
* @param bool $is_public Is the site public?
*/
$is_public = apply_filters( 'stellarwp/uplink/' . Config::get_hook_prefix(). '/get_db_version', $is_public );
return (bool) $is_public;
}
}

View File

@@ -0,0 +1,16 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Traits;
trait With_Debugging {
/**
* Determine if WP_DEBUG is enabled.
*
* @return bool
*/
protected function is_wp_debug(): bool {
return defined( 'WP_DEBUG' ) && WP_DEBUG;
}
}

View File

@@ -0,0 +1,77 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink;
use RuntimeException;
use KadenceWP\KadenceBlocks\StellarWP\ContainerContract\ContainerInterface;
class Uplink {
public const UPLINK_ASSETS_URI = 'uplink.assets.uri';
/**
* Initializes the service provider.
*
* @since 1.0.0
*
* @return void
*/
public static function init(): void {
if ( ! Config::has_container() ) {
throw new RuntimeException(
__( 'You must call StellarWP\Uplink\Config::set_container() before calling StellarWP\Uplink::init().', '%TEXTDOMAIN%' )
);
}
$container = Config::get_container();
$container->singleton( self::UPLINK_ASSETS_URI, dirname( plugin_dir_url( __FILE__ ) ) . '/assets' );
$container->bind( ContainerInterface::class, $container );
$container->singleton( View\Provider::class, View\Provider::class );
$container->singleton( API\Client::class, API\Client::class );
$container->singleton( API\V3\Provider::class, API\V3\Provider::class );
$container->singleton( Resources\Collection::class, Resources\Collection::class );
$container->singleton( Site\Data::class, Site\Data::class );
$container->singleton( Notice\Provider::class, Notice\Provider::class );
$container->singleton( Admin\Provider::class, Admin\Provider::class );
$container->singleton( Auth\Provider::class, Auth\Provider::class );
if ( static::is_enabled() ) {
$container->get( View\Provider::class )->register();
$container->get( API\V3\Provider::class )->register();
$container->get( Notice\Provider::class )->register();
$container->get( Admin\Provider::class )->register();
if ( $container->has( Config::TOKEN_OPTION_NAME ) ) {
$container->get( Auth\Provider::class )->register();
}
}
require_once __DIR__ . '/functions.php';
}
/**
* Returns whether licensing validation is disabled.
*
* @since 1.0.0
*
* @return bool
*/
public static function is_disabled() : bool {
$is_pue_disabled = defined( 'TRIBE_DISABLE_PUE' ) && TRIBE_DISABLE_PUE;
$is_licensing_disabled = defined( 'STELLARWP_LICENSING_DISABLED' ) && STELLARWP_LICENSING_DISABLED;
return $is_pue_disabled || $is_licensing_disabled;
}
/**
* Returns whether licensing validation is enabled.
*
* @since 1.0.0
*
* @return bool
*/
public static function is_enabled() : bool {
return ! static::is_disabled();
}
}

View File

@@ -0,0 +1,99 @@
<?php
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Utils;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Config;
class Checks {
/**
* Determines if the provided value should be regarded as 'true'.
*
* @since 1.0.0
*
* @param mixed $var
*
* @return bool
*/
public static function is_truthy( $var ) {
if ( is_bool( $var ) ) {
return $var;
}
/**
* Provides an opportunity to modify strings that will be
* deemed to evaluate to true.
*
* @param array $truthy_strings
*/
$truthy_strings = (array) apply_filters( 'stellarwp/uplink/' . Config::get_hook_prefix(). '/is_truthy_strings', [
'1',
'enable',
'enabled',
'on',
'y',
'yes',
'true',
] );
// Makes sure we are dealing with lowercase for testing
if ( is_string( $var ) ) {
$var = strtolower( $var );
}
// If $var is a string, it is only true if it is contained in the above array
if ( in_array( $var, $truthy_strings, true ) ) {
return true;
}
// All other strings will be treated as false
if ( is_string( $var ) ) {
return false;
}
// For other types (ints, floats etc) cast to bool
return (bool) $var;
}
/**
* String Starts With PHP80 polyfill.
*
* @param string $haystack The string to search in.
* @param string $needle The substring to search for in the haystack.
*
* @return bool Returns true if haystack begins with needle, false otherwise.
*/
public static function str_starts_with( string $haystack, string $needle ): bool {
if ( function_exists( 'str_starts_with' ) ) {
return str_starts_with( $haystack, $needle );
}
return 0 === strncmp( $haystack, $needle, strlen( $needle ) );
}
/**
* String Ends With PHP80 polyfill.
*
* @param string $haystack The string to search in.
* @param string $needle The substring to search for in the haystack.
*
* @return bool Returns true if haystack ends with needle, false otherwise.
*/
public static function str_ends_with(string $haystack, string $needle): bool {
if ( function_exists( 'str_ends_with' ) ) {
return str_ends_with( $haystack, $needle );
}
if ( '' === $needle || $needle === $haystack ) {
return true;
}
if ( '' === $haystack ) {
return false;
}
$needleLength = strlen( $needle );
return $needleLength <= strlen( $haystack ) && 0 === substr_compare( $haystack, $needle, - $needleLength );
}
}

View File

@@ -0,0 +1,37 @@
<?php
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\Utils;
class Sanitize {
/**
* Sanitizes a key.
*
* @since 1.2.2
*
* @param string $key
*
* @return string
*/
public static function key( $key ) {
return str_replace( [ '`', '"', "'" ], '', $key );
}
/**
* Sanitizes a title, replacing whitespace and a few other characters with hyphens.
*
* Limits the output to alphanumeric characters, underscore (_) and dash (-).
* Whitespace becomes a hyphen.
*
* @since 1.3.0
*
* @param string $title The title to be sanitized.
* @param string $context Optional. The operation for which the string is sanitized.
* When set to 'save', additional entities are converted to hyphens
* or stripped entirely. Default 'display'.
* @return string The sanitized title.
*/
public static function sanitize_title_with_hyphens( string $title, string $context = 'save' ): string {
return str_replace( '-', '_', sanitize_title_with_dashes( $title, '', $context ) );
}
}

View File

@@ -0,0 +1,25 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\View\Contracts;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\View\Exceptions\FileNotFoundException;
interface View {
/**
* Renders a view and returns it as a string to be echoed.
*
* @example If the server path is /app/views, and you wish to load /app/views/admin/notice.php,
* pass `admin/notice` as the view name.
*
* @param string $name The relative path/name of the view file without extension.
*
* @param mixed[] $args Arguments to be extracted and passed to the view.
*
* @throws FileNotFoundException If the view file cannot be found.
*
* @return string
*/
public function render( string $name, array $args = [] ): string;
}

View File

@@ -0,0 +1,9 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\View\Exceptions;
use Exception;
final class FileNotFoundException extends Exception {
}

View File

@@ -0,0 +1,21 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\View;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Contracts\Abstract_Provider;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\View\Contracts\View;
final class Provider extends Abstract_Provider {
/**
* Configure the View Renderer.
*/
public function register() {
$this->container->singleton(
WordPress_View::class,
new WordPress_View( __DIR__ . '/../../views' )
);
$this->container->bind( View::class, $this->container->get( WordPress_View::class ) );
}
}

View File

@@ -0,0 +1,97 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink\View;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\View\Exceptions\FileNotFoundException;
use Throwable;
/**
* Loads and renders PHP view files.
*/
final class WordPress_View implements Contracts\View {
/**
* The server path to the views folder.
*
* @var string
*
* @example /app/views/
*/
private $directory;
/**
* The file extension of view files.
*
* @var string
*
* @example .php
*/
private $extension;
/**
* @param string $directory The server path to the views folder.
* @param string $extension The file extension of view files.
*/
public function __construct( string $directory, string $extension = '.php' ) {
$this->directory = trailingslashit( realpath( $directory ) );
$this->extension = $extension;
}
/**
* Renders a view and returns it as a string to be echoed.
*
* @example If the server path is /app/views, and you wish to load /app/views/admin/notice.php,
* pass `admin/notice` as the view name.
*
* @param string $name The relative path/name of the view file without extension.
*
* @param mixed[] $args Arguments to be extracted and passed to the view.
*
* @throws FileNotFoundException If the view file cannot be found.
*
* @return string
*/
public function render( string $name, array $args = [] ): string {
$file = $this->get_path( $name );
try {
$level = ob_get_level();
ob_start();
extract( $args );
include $file;
return (string) ob_get_clean();
} catch ( Throwable $e ) {
while ( ob_get_level() > $level ) {
ob_end_clean();
}
throw $e;
}
}
/**
* Get the absolute server path to a view file.
*
* @param string $name The relative view path/name, e.g. `admin/notice`.
*
* @throws FileNotFoundException If the view file cannot be found.
*
* @return string The absolute path to the view file.
*/
private function get_path( string $name ): string {
$file = $this->directory . $name . $this->extension;
$path = realpath( $file );
if( $path === false ) {
throw new FileNotFoundException(
sprintf( __( 'View file "%s" not found or not readable.', '%TEXTDOMAIN%' ), $file )
);
}
return $path;
}
}

View File

@@ -0,0 +1,332 @@
<?php declare( strict_types=1 );
namespace KadenceWP\KadenceBlocks\StellarWP\Uplink;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\API\V3\Auth\Contracts\Token_Authorizer;
use KadenceWP\KadenceBlocks\StellarWP\ContainerContract\ContainerInterface;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Admin\License_Field;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\API\V3\Auth\Contracts\Auth_Url;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\API\Validation_Response;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\Admin\Disconnect_Controller;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\Auth_Url_Builder;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\Authorizer;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\License\License_Manager;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Auth\Token\Token_Factory;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Components\Admin\Authorize_Button_Controller;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources\Collection;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources\Plugin;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources\Resource;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Resources\Service;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Site\Data;
use Throwable;
/**
* Get the uplink container.
*
* @throws \RuntimeException
*
* @return ContainerInterface
*/
function get_container(): ContainerInterface {
return Config::get_container();
}
/**
* Displays the token authorization button, which allows admins to
* authorize their product through your origin server and clear the
* token locally by disconnecting.
*
* @param string $slug The Product slug to render the button for.
* @param string $domain An optional domain associated with a license key to pass along.
*/
function render_authorize_button( string $slug, string $domain = '' ): void {
try {
get_container()->get( Authorize_Button_Controller::class )
->render( [
'slug' => $slug,
'domain' => $domain,
] );
} catch ( Throwable $e ) {
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
error_log( "Unable to render authorize button: {$e->getMessage()} {$e->getFile()}:{$e->getLine()} {$e->getTraceAsString()}" );
}
}
}
/**
* Get the stored authorization token, automatically detects multisite.
*
* @param string $slug The plugin/service slug to use to determine if we use network/single site token storage.
*
* @throws \RuntimeException
*
* @return string|null
*/
function get_authorization_token( string $slug ): ?string {
$resource = get_resource( $slug );
if ( ! $resource ) {
return null;
}
return get_container()->get( Token_Factory::class )->make( $resource )->get();
}
/**
* Check if a license is authorized.
*
* @note This response may be cached.
*
* @param string $license The license key.
* @param string $slug The plugin/service slug.
* @param string $token The stored token.
* @param string $domain The user's license domain.
*
* @return bool
*/
function is_authorized( string $license, string $slug, string $token, string $domain ): bool {
try {
return get_container()
->get( Token_Authorizer::class )
->is_authorized( $license, $slug, $token, $domain );
} catch ( Throwable $e ) {
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
error_log( "An Authorization error occurred: {$e->getMessage()} {$e->getFile()}:{$e->getLine()} {$e->getTraceAsString()}" );
}
return false;
}
}
/**
* Manually check if a license is authorized by fetching required
* data automatically.
*
* @param string $slug The plugin/service slug.
*
* @return bool
*/
function is_authorized_by_resource( string $slug ): bool {
try {
$license = get_license_key( $slug );
$token = get_authorization_token( $slug );
$domain = get_license_domain();
if ( ! $license || ! $token || ! $domain ) {
return false;
}
return is_authorized( $license, $slug, $token, $domain );
} catch ( Throwable $e ) {
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
error_log( "An Authorization error occurred: {$e->getMessage()} {$e->getFile()}:{$e->getLine()} {$e->getTraceAsString()}" );
}
return false;
}
}
/**
* If the current user is allowed to perform token authorization.
*
* Without being filtered, this just runs a is_super_admin() check.
*
* @throws \RuntimeException
*
* @return bool
*/
function is_user_authorized(): bool {
return get_container()->get( Authorizer::class )->can_auth();
}
/**
* Build a brand's authorization URL, with the uplink_callback base64 query variable.
*
* @param string $slug The Product slug to render the button for.
* @param string $domain An optional domain associated with a license key to pass along.
*
* @return string
*/
function build_auth_url( string $slug, string $domain = '' ): string {
try {
return get_container()->get( Auth_Url_Builder::class )
->build( $slug, $domain );
} catch ( Throwable $e ) {
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
error_log( "Error building auth URL: {$e->getMessage()} {$e->getFile()}:{$e->getLine()} {$e->getTraceAsString()}" );
}
return '';
}
}
/**
* Get a resource (plugin/service) from the collection.
*
* @param string $slug The resource slug to find.
*
* @throws \RuntimeException
*
* @return Resource|Plugin|Service|null
*/
function get_resource( string $slug ) {
return get_container()->get( Collection::class )->offsetGet( $slug );
}
/**
* Compares the Uplink configuration to the current site this function is called on,
* e.g. a sub-site to determine if the product supports multisite licenses.
*
* Not to be confused with Config::allows_network_licenses().
*
* @param string|Resource|Plugin|Service $slug_or_resource The product/service slug or a Resource object.
*
* @throws \RuntimeException
*
* @return bool
*/
function allows_multisite_license( $slug_or_resource ): bool {
$resource = $slug_or_resource instanceof Resource ? $slug_or_resource : get_resource( $slug_or_resource );
if ( ! $resource ) {
return false;
}
return get_container()->get( License_Manager::class )->allows_multisite_license( $resource );
}
/**
* A multisite aware license validation check.
*
* @param string $slug The plugin/service slug to validate against.
* @param string $license An optional license key, otherwise we'll fetch it automatically.
*
* @throws \RuntimeException
*
* @return Validation_Response|null
*/
function validate_license( string $slug, string $license = '' ): ?Validation_Response {
$resource = get_resource( $slug );
if ( ! $resource ) {
return null;
}
$license = $license ?: get_license_key( $slug );
$network = allows_multisite_license( $resource );
return $resource->validate_license( $license, $network );
}
/**
* A multisite license aware way to get a resource's license key automatically
* from the network or local site level.
*
* @param string $slug The plugin/service slug.
*
* @throws \RuntimeException
*
* @return string
*/
function get_license_key( string $slug ): string {
$resource = get_resource( $slug );
if ( ! $resource ) {
return '';
}
$network = allows_multisite_license( $resource );
return $resource->get_license_key( $network ? 'network' : 'any' );
}
/**
* A multisite license aware way to set a resource's license key automatically
* from the network or local site level.
*
* @param string $slug The plugin/service slug.
* @param string $license The license key to store.
*
* @throws \RuntimeException
*
* @return bool
*/
function set_license_key( string $slug, string $license ): bool {
$resource = get_resource( $slug );
if ( ! $resource ) {
return false;
}
$network = allows_multisite_license( $resource );
$result = $resource->set_license_key( $license, $network ? 'network' : 'local' );
// Force update the key status.
$resource->validate_license( $license, $network );
return $result;
}
/**
* Get the current site's license domain without any hash suffix.
*
* @throws \RuntimeException
*
* @return string
*/
function get_original_domain(): string {
return get_container()->get( Data::class )->get_domain( true );
}
/**
* Get the current site's license domain, multisite friendly.
*
* @throws \RuntimeException
* @return string
*/
function get_license_domain(): string {
return get_container()->get( Data::class )->get_domain();
}
/**
* Get the disconnect token URL.
*
* @param string $slug The plugin/service slug.
*
* @throws \RuntimeException
*
* @return string
*/
function get_disconnect_url( string $slug ): string {
$resource = get_resource( $slug );
if ( ! $resource ) {
return '';
}
return get_container()->get( Disconnect_Controller::class )->get_url( $resource );
}
/**
* Get the License Field Object to render license key fields.
*
* @throws \RuntimeException
*
* @return License_Field
*/
function get_license_field(): License_Field {
return get_container()->get( License_Field::class );
}
/**
* Retrieve an Origin's auth url, if it exists.
*
* @param string $slug The product/service slug.
*
* @throws \RuntimeException
*
* @return string
*/
function get_auth_url( string $slug ): string {
return get_container()->get( Auth_Url::class )->get( $slug );
}

View File

@@ -0,0 +1,48 @@
<?php
/**
* @var Resource $resource The Resource object.
* @var bool $show_button Whether to show the submit button. Default true.
* @var bool $show_title Whether to show the title. Default true.
*/
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Admin\License_Field;
use KadenceWP\KadenceBlocks\StellarWP\Uplink\Config;
if ( empty( $plugin ) ) {
return;
}
$field = Config::get_container()->get( License_Field::class );
$group = $field->get_group_name( sanitize_title( $plugin->get_slug() ) );
$action_postfix = Config::get_hook_prefix_underscored();
$form_action = is_multisite() && is_network_admin() ? network_admin_url( 'settings.php' ) : 'options.php';
?>
<?php if ( $show_title ) : ?>
<h3><?php echo esc_html( $plugin->get_name() ); ?></h3>
<?php endif; ?>
<div class="stellarwp-uplink" data-js="stellarwp-uplink">
<div class="stellarwp-uplink__settings">
<?php do_action( 'stellarwp/uplink/' . Config::get_hook_prefix(). '/license_field_before_form', $plugin->get_slug() ) ?>
<form method="post" action="<?php echo esc_url( $form_action ) ?>">
<?php settings_fields( $group ); ?>
<?php do_action( 'stellarwp/uplink/' . Config::get_hook_prefix(). '/license_field_before_field', $plugin->get_slug() ) ?>
<?php if ( $show_title ) : ?>
<table class="form-table" role="presentation">
<?php endif; ?>
<div class="stellarwp-uplink__license-field">
<?php $field->do_settings_fields( $group, License_Field::get_section_name( $plugin ), $action_postfix, $show_title ); ?>
</div>
<?php if ( $show_title ) : ?>
</table>
<?php endif; ?>
<?php do_action( 'stellarwp/uplink/' . Config::get_hook_prefix(). '/license_field_after_field', $plugin->get_slug() ) ?>
<?php if ( $show_button ) : ?>
<?php submit_button( esc_html__( 'Save Changes', '%TEXTDOMAIN%' ) );?>
<?php endif; ?>
</form>
<?php do_action( 'stellarwp/uplink/' . Config::get_hook_prefix(). '/license_field_after_form', $plugin->get_slug() ) ?>
</div>
</div>

View File

@@ -0,0 +1,15 @@
.license-test-results {
margin-top: 10px;
}
.key-validity {
display: inline-block;
}
.valid-key {
color: green;
}
.invalid-key {
color: red;
}

View File

@@ -0,0 +1,73 @@
( function( $, obj ) {
obj.init = function() {
$( '.stellarwp-uplink-license-key-field' ).each( function() {
var $el = $( this );
var $field = $el.find( 'input[type="text"]' );
if ( '' === $field.val().trim() ) {
$el.find( '.license-test-results' ).hide();
}
obj.validateKey( $el );
} );
$( document ).on( 'change', '.stellarwp-uplink-license-key-field', function() {
const $el = $( this );
obj.validateKey( $el );
} );
};
obj.validateKey = function( $el ) {
const field = $el.find( 'input[type="text"]' )
const action = $el.data( 'action' );
const slug = $el.data( 'plugin-slug' );
let $validityMessage = $el.find( '.key-validity' );
if ( '' === field.val().trim() ) {
return;
}
$( $el ).find( '.license-test-results' ).show();
$( $el ).find( '.tooltip' ).hide();
$( $el ).find( '.ajax-loading-license' ).show();
$validityMessage.hide();
// Strip whitespace from key
let licenseKey = field.val().trim();
field.val( licenseKey );
const data = {
action: window[`stellarwp_config_${action}`]['action'],
slug: slug,
key: licenseKey,
_wpnonce: $($el).find('.wp-nonce').val()
};
$.post(ajaxurl, data, function (response) {
$validityMessage.show();
$validityMessage.html(response.message);
switch (response.status) {
case 1:
$validityMessage.addClass('valid-key').removeClass('invalid-key');
break;
case 2:
$validityMessage.addClass('valid-key service-msg');
break;
default:
$validityMessage.addClass('invalid-key').removeClass('valid-key');
break;
}
}).fail(function(error) {
$validityMessage.show();
$validityMessage.html(error.message);
}).always(function() {
$($el).find('.ajax-loading-license').hide();
});
};
$( function() {
obj.init();
} );
} )( jQuery, {} );

View File

@@ -0,0 +1,26 @@
<?php declare( strict_types=1 );
/**
* The authorize button view, allowing the user to authorize their install with
* the license server via the origin site.
*
* @see \KadenceWP\KadenceBlocks\StellarWP\Uplink\Components\Admin\Authorize_Button_Controller
*
* @var string $link_text The link text, changes based on whether the user is authorized to authorize :)
* @var string $url The location the link goes to, either the custom origin URL, or a link to the admin.
* @var string $target The link target.
* @var string $tag The HTML tag to use for the wrapper.
* @var string $classes The CSS classes for the hyperlink.
*/
defined( 'ABSPATH' ) || exit;
?>
<<?php echo esc_html( $tag ) ?> class="uplink-authorize-container">
<a href="<?php echo esc_url( $url ) ?>"
target="<?php echo $target ? esc_attr( $target ) : '' ?>"
<?php echo $classes ? sprintf( 'class="%s"', esc_attr( $classes ) ) : '' ?>
>
<?php echo esc_html( $link_text ) ?>
</a>
</<?php echo esc_html( $tag ) ?>>

View File

@@ -0,0 +1 @@
<?php declare( strict_types=1 );

View File

@@ -0,0 +1,17 @@
<?php declare( strict_types=1 );
/**
* Render a WordPress dashboard notice.
*
* @see \KadenceWP\KadenceBlocks\StellarWP\Uplink\Notice\Notice_Controller
*
* @var string $message The message to display.
* @var string $classes The CSS classes for the notice.
* @var array<string, mixed> $allowed_tags The allowed HTML tags for wp_kses().
* @var string[] $allowed_protocols The allowed protocols for wp_kses().
*/
defined( 'ABSPATH' ) || exit;
?>
<div class="<?php echo esc_attr( $classes ) ?>">
<p><?php echo wp_kses( $message, $allowed_tags, $allowed_protocols ) ?></p>
</div>

View File

@@ -0,0 +1 @@
<?php declare( strict_types=1 );