Initial commit xmarticaims

This commit is contained in:
2026-11-02 10:26:32 -06:00
commit e74236f5c1
9764 changed files with 2880647 additions and 0 deletions
+674
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>.
@@ -0,0 +1 @@
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{B as t,W as n,c as r,l as i,r as a}from"./button-BhAQo6Sy.js";var o=e(n(),1),s=o.createContext({register:()=>{},unregister:()=>{},subscribeMapChange:()=>()=>{},nextIndexRef:{current:0}});function c(){return o.useContext(s)}function l(e={}){let{guess:t,label:n,metadata:i,textRef:a,index:s}=e,{register:l,unregister:u,subscribeMapChange:d,nextIndexRef:f}=c(),p=o.useRef(-1),[m,h]=o.useState(s==null&&t?()=>{if(p.current===-1){let e=f.current;f.current+=1,p.current=e}return p.current}:-1),g=s??m,_=o.useRef(null),v=o.useCallback(e=>{let t=_.current;t&&u(t),_.current=e,e&&l(e,{metadata:i??null,index:s??null,label:n,textRef:a})},[s,l,u,i,n,a]);return r(()=>{if(s==null)return d(e=>{let t=_.current?e.get(_.current)?.index:null;t!=null&&h(t)})},[s,d]),{ref:v,index:g}}var u=a();function d(e){let{children:n,elementsRef:a,labelsRef:c,onMapChange:l}=e,d=i(l),[,v]=o.useState(!1),y=t(p).current,b=t(f).current,x=o.useRef(0),S=o.useRef(!0),C=o.useRef([]),w=o.useRef(null),T=i(()=>{S.current||(S.current=!0,v(e=>!e))}),E=i((e,t)=>{b.set(e,t),T()}),D=i(e=>{b.delete(e),T()}),O=i(e=>{let t=new Map;return a.current.length=0,c&&(c.current.length=0),e.forEach(e=>{t.set(e.element,{...e.registration.metadata??{},index:e.index}),a.current[e.index]=e.element,c&&(c.current[e.index]=e.registration.label===void 0?e.registration.textRef?.current?.textContent??e.element.textContent:e.registration.label)}),x.current=a.current.length,t});function k(e){if(w.current?.disconnect(),w.current=null,typeof MutationObserver!=`function`||e.length<2)return;let t=new MutationObserver(n=>{if(!g(n))return;let r=null;for(let n of e)if(n.isConnected){if(r&&_(r,n)>0){t.disconnect(),T();return}r=n}});w.current=t;let n=new Set;for(let t=1;t<e.length;t+=1){let r=h(e[t-1],e[t]);r&&n.add(r)}n.forEach(e=>t.observe(e,{childList:!0}))}let A=i(()=>{let[e,t]=m(b),n=O(e);k(t),C.current=e,S.current=!1,y.forEach(e=>e(n)),d(n)});r(()=>(S.current||O(C.current),()=>{a.current=[],c&&(c.current=[])}),[a,c,O]),r(()=>{S.current&&A()}),r(()=>()=>{w.current?.disconnect(),S.current=!0},[]);let j=i(e=>(y.add(e),()=>{y.delete(e)})),M=o.useMemo(()=>({register:E,unregister:D,subscribeMapChange:j,nextIndexRef:x}),[E,D,j,x]);return(0,u.jsx)(s.Provider,{value:M,children:n})}function f(){return new Map}function p(){return new Set}function m(e){let t=new Set,n=[],r=[];e.forEach((e,i)=>{if(!i.isConnected)return;let a=e.index,o={index:a??-1,element:i,registration:e};a===null?r.push(o):a>=0&&(t.add(a),n.push(o))});let i=0;return r.sort((e,t)=>_(e.element,t.element)),r.forEach(e=>{for(;t.has(i);)i+=1;e.index=i,n.push(e),i+=1}),t.size>0&&n.sort((e,t)=>e.index-t.index),[n,r.map(e=>e.element)]}function h(e,t){let n=e.parentElement;for(;n&&!n.contains(t);)n=n.parentElement;return n}function g(e){for(let t of e)for(let e=0;e<t.removedNodes.length;e+=1)if(t.removedNodes[e].isConnected)return!0;return!1}function _(e,t){return e.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1}export{l as n,d as t};
@@ -0,0 +1 @@
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{P as t,W as n}from"./button-BhAQo6Sy.js";var r=e(n(),1).forwardRef(function(e,n){let{className:r,render:i,orientation:a=`horizontal`,style:o,...s}=e;return t(`div`,e,{state:{orientation:a},ref:n,props:[{role:`separator`,"aria-orientation":a},s]})});export{r as t};
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
import{U as e}from"./button-BhAQo6Sy.js";var t=e(`arrow-left`,[[`path`,{d:`m12 19-7-7 7-7`,key:`1l729n`}],[`path`,{d:`M19 12H5`,key:`x3x0zl`}]]);export{t};
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
import{U as e}from"./button-BhAQo6Sy.js";var t=e(`cloud-upload`,[[`path`,{d:`M12 13v8`,key:`1l5pq0`}],[`path`,{d:`M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242`,key:`1pljnt`}],[`path`,{d:`m8 17 4-4 4 4`,key:`1quai1`}]]);export{t};
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
import{U as e}from"./button-BhAQo6Sy.js";var t=e(`file-code-corner`,[[`path`,{d:`M4 12.15V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.706.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2h-3.35`,key:`1wthlu`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`m5 16-3 3 3 3`,key:`331omg`}],[`path`,{d:`m9 22 3-3-3-3`,key:`lsp7cz`}]]);export{t};
@@ -0,0 +1 @@
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{A as t,W as n,j as r,n as i,r as a}from"./button-BhAQo6Sy.js";import{V as o}from"./api-Bb85n68L.js";import{t as s}from"./arrow-left-CQp0ScTZ.js";import{n as c}from"./switch-DMNAfdJq.js";import{t as l}from"./type-Df9tHIH_.js";import"./input-DbQb1wvc.js";var u=`useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict`,d=(e=21)=>{let t=``,n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+=u[n[e]&63];return t},f=e(n(),1),p=a();function m({source:e,title:n,description:a,icon:c,actions:u}){return(0,p.jsxs)(`header`,{className:`flex flex-col gap-5 border-b pb-5 lg:flex-row lg:items-center lg:justify-between`,children:[(0,p.jsxs)(`div`,{className:`flex min-w-0 items-start gap-3.5`,children:[(0,p.jsx)(o,{to:`/fonts/index`,className:r(i({variant:`outline`,size:`icon`}),`mt-0.5 shrink-0`),"aria-label":wp.i18n.__(`Back to font library`,`jooosi-fon`),children:(0,p.jsx)(s,{"aria-hidden":`true`})}),(0,p.jsx)(`span`,{className:`mt-0.5 hidden size-9 shrink-0 place-items-center rounded-xl border bg-card shadow-xs sm:grid`,children:c||(0,p.jsx)(l,{"aria-hidden":`true`,className:`size-4 text-muted-foreground`})}),(0,p.jsxs)(`div`,{className:`min-w-0`,children:[(0,p.jsx)(t,{variant:`primary-light`,size:`sm`,radius:`full`,children:e}),(0,p.jsx)(`h1`,{className:`mb-0 mt-2 text-2xl font-semibold tracking-[-0.025em] sm:text-[1.75rem] sm:leading-tight`,children:n}),(0,p.jsx)(`p`,{className:`mb-0 mt-1.5 max-w-2xl text-sm leading-6 text-muted-foreground`,children:a})]})]}),u&&(0,p.jsx)(`div`,{className:`flex shrink-0 flex-wrap gap-2 pl-[3.25rem] sm:pl-[6.5rem] lg:pl-0`,children:u})]})}function h({label:e,value:t,suffix:n,min:i,max:a,step:o=1,onChange:s,compact:c=!1,className:l}){let u=(0,f.useId)(),[d,m]=(0,f.useState)(String(t));return(0,f.useEffect)(()=>m(String(t)),[t]),(0,p.jsxs)(`div`,{className:r(c?`grid min-w-32 grid-cols-[1fr_auto] items-center gap-x-2 gap-y-1 text-xs font-medium`:`grid grid-cols-[5rem_minmax(5rem,1fr)_4.5rem] items-center gap-2 text-xs font-medium`,l),children:[(0,p.jsx)(`span`,{id:u,className:`text-muted-foreground`,children:e}),(0,p.jsx)(`input`,{type:`range`,min:i,max:a,step:o,value:t,onChange:e=>s(Number(e.target.value)),"aria-labelledby":u,className:r(`h-5 w-full cursor-pointer overflow-visible accent-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`,c&&`col-span-2 row-start-2`)}),(0,p.jsxs)(`span`,{className:r(`flex min-w-0 items-center rounded-md border bg-background focus-within:border-ring focus-within:ring-2 focus-within:ring-ring/50`,c&&`col-start-2 row-start-1 min-w-16`),children:[(0,p.jsx)(`input`,{type:`number`,min:i,max:a,step:o,value:d,onChange:e=>{let t=e.target.value;m(t);let n=Number(t);t!==``&&Number.isFinite(n)&&n>=i&&n<=a&&s(n)},onBlur:()=>{let e=Number(d);if(!Number.isFinite(e)){m(String(t));return}let n=Math.min(a,Math.max(i,e));m(String(n)),s(n)},onKeyDown:e=>{e.key===`Enter`&&e.currentTarget.blur(),e.key===`Escape`&&(m(String(t)),e.currentTarget.blur())},"aria-labelledby":u,className:`min-w-0 flex-1 appearance-none bg-transparent py-1 pl-1.5 text-right tabular-nums outline-none [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none`}),n&&(0,p.jsx)(`span`,{"aria-hidden":`true`,className:`pr-1.5 text-muted-foreground`,children:n})]})]})}function g(){return(0,p.jsxs)(`div`,{className:`space-y-5`,"aria-busy":`true`,"aria-label":wp.i18n.__(`Loading font editor`,`jooosi-fon`),children:[(0,p.jsxs)(`div`,{className:`flex items-start gap-3.5 border-b pb-5`,children:[(0,p.jsx)(c,{className:`size-9 shrink-0 rounded-lg`}),(0,p.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-2.5`,children:[(0,p.jsx)(c,{className:`h-5 w-28 rounded-full`}),(0,p.jsx)(c,{className:`h-8 w-64 max-w-full`}),(0,p.jsx)(c,{className:`h-4 w-[34rem] max-w-full`})]})]}),(0,p.jsxs)(`div`,{className:`overflow-hidden rounded-2xl border`,children:[(0,p.jsxs)(`div`,{className:`flex items-center justify-between gap-4 border-b p-4`,children:[(0,p.jsxs)(`div`,{className:`space-y-2`,children:[(0,p.jsx)(c,{className:`h-4 w-24`}),(0,p.jsx)(c,{className:`h-3 w-64 max-w-full`})]}),(0,p.jsx)(c,{className:`hidden h-9 w-72 sm:block`})]}),(0,p.jsx)(c,{className:`h-64 rounded-none sm:h-72`}),(0,p.jsx)(`div`,{className:`grid grid-cols-2 gap-px bg-border lg:grid-cols-4`,children:[0,1,2,3].map(e=>(0,p.jsx)(c,{className:`h-16 rounded-none bg-card`},e))})]}),(0,p.jsxs)(`div`,{className:`grid gap-5 xl:grid-cols-[minmax(0,1fr)_340px]`,children:[(0,p.jsx)(c,{className:`h-80 rounded-xl`}),(0,p.jsx)(c,{className:`h-80 rounded-xl`})]}),(0,p.jsx)(`span`,{className:`sr-only`,children:wp.i18n.__(`Loading font editor`,`jooosi-fon`)})]})}export{d as i,g as n,h as r,m as t};
File diff suppressed because one or more lines are too long
@@ -0,0 +1,53 @@
import { inspectFontFile, preloadFontInspector } from './font-inspector';
import type { FontFile } from '@/types/fonts';
interface FontInspectionInitRequest {
type: 'init';
preloadWoff2: boolean;
}
interface FontInspectionJobRequest {
type: 'inspect';
id: number;
file: FontFile;
}
type FontInspectionRequest = FontInspectionInitRequest | FontInspectionJobRequest;
interface FontInspectionResponse {
id: number;
result?: Awaited<ReturnType<typeof inspectFontFile>>;
error?: string;
}
const workerScope = globalThis as unknown as {
onmessage: ((event: MessageEvent<FontInspectionRequest>) => void) | null;
postMessage: (message: FontInspectionResponse | { type: 'ready' | 'init-error'; error?: string }) => void;
};
workerScope.onmessage = async ({ data }) => {
if (data.type === 'init') {
try {
if (data.preloadWoff2) {
await preloadFontInspector();
}
workerScope.postMessage({ type: 'ready' });
} catch (error) {
workerScope.postMessage({
type: 'init-error',
error: error instanceof Error ? error.message : String(error),
});
}
return;
}
try {
const result = await inspectFontFile(data.file);
workerScope.postMessage({ id: data.id, result });
} catch (error) {
workerScope.postMessage({
id: data.id,
error: error instanceof Error ? error.message : 'Unable to inspect this font.',
});
}
};
@@ -0,0 +1,4 @@
function e(e){switch(e){case`woff`:case`font/woff`:return`woff`;case`ttf`:case`font/ttf`:return`truetype`;case`otf`:case`font/otf`:return`opentype`;case`eot`:case`font/eot`:return`embedded-opentype`;default:return`woff2`}}function t(e){return e.replaceAll(`\\`,`\\\\`).replaceAll(`'`,`\\'`).replace(/[\n\r\f]/g,e=>`\\${e.codePointAt(0)?.toString(16)} `)}function n(e){let t=e.trim().toLowerCase();return/^(normal|italic|oblique(?:\s+-?\d+(?:\.\d+)?deg(?:\s+-?\d+(?:\.\d+)?deg)?)?)$/.test(t)?t:`normal`}function r(e){let t=String(e).trim().toLowerCase();if(t===`normal`||t===`bold`)return t;let n=t.split(/\s+/).map(Number);return n.length>0&&n.length<=2&&n.every(e=>Number.isFinite(e)&&e>=1&&e<=1e3)?t:null}function i(e){let t=String(e??``).trim().toLowerCase();if(!t)return null;if(/^(normal|ultra-condensed|extra-condensed|condensed|semi-condensed|semi-expanded|expanded|extra-expanded|ultra-expanded)$/.test(t))return t;let n=t.split(/\s+/),r=n.map(e=>Number(e.replace(`%`,``)));return r.length>0&&r.length<=2&&n.every(e=>/^\d+(?:\.\d+)?%$/.test(e))&&r.every(e=>Number.isFinite(e)&&e>0&&e<=1e3)?t:null}function a(e){let t=e?.trim().toLowerCase();return t&&[`auto`,`block`,`swap`,`fallback`,`optional`].includes(t)?t:`auto`}function o(e){let t=`U\\+[0-9A-F?]{1,6}(?:-[0-9A-F]{1,6})?`,n=RegExp(`^${t}(?:\\s*,\\s*${t})*$`,`i`);return e&&n.test(e.trim())?e.trim():null}function s(s,c,l=`auto`){return s.trim()?c.filter(e=>e.isEnabled!==!1).map(c=>{let u=[`font-family: '${t(s)}';`,`font-style: ${n(c.style)};`,`font-display: ${a(c.display||l)};`],d=r(c.weight);d&&u.push(`font-weight: ${d};`);let f=i(c.width);if(f&&u.push(`font-stretch: ${f};`),c.files.length>0){let n=c.files.map(n=>`url('${t(n.attachment_url)}') format('${e(n.extension)}')`);u.push(`src: ${n.join(`, `)};`)}let p=o(c.unicodeRange);return p&&u.push(`unicode-range: ${p};`),`@font-face {\n ${u.join(`
`)}\n}`}).join(`
`):``}function c(e){return`--jf--family-${e.replace(/[^a-zA-Z0-9\-_]+/g,`-`).toLowerCase()}`}export{c as n,s as t};
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
import{r as e}from"./button-BhAQo6Sy.js";var t=e();function n(){return(0,t.jsxs)(`svg`,{viewBox:`0 0 16 16`,className:`size-5`,"aria-hidden":`true`,children:[(0,t.jsx)(`path`,{fill:`#f29900`,d:`M13.5 2H8L1 13h5.5z`}),(0,t.jsx)(`path`,{fill:`#1a73e8`,d:`M8 2h5v11H8z`}),(0,t.jsx)(`circle`,{fill:`#ea4335`,cx:`3.25`,cy:`4.25`,r:`2.25`}),(0,t.jsx)(`path`,{fill:`#0d652d`,d:`M13.33 10 13 13a3 3 0 0 1 0-6l.33 3z`}),(0,t.jsx)(`path`,{fill:`#174ea6`,d:`M10.5 4.5A2.5 2.5 0 0 1 13 2l.45 2.5L13 7a2.5 2.5 0 0 1-2.5-2.5z`}),(0,t.jsx)(`path`,{fill:`#1a73e8`,d:`M13 2a2.5 2.5 0 0 1 0 5`}),(0,t.jsx)(`path`,{fill:`#34a853`,d:`M13 7a3 3 0 0 1 0 6`})]})}export{n as t};
@@ -0,0 +1 @@
import{R as e,S as t}from"./button-BhAQo6Sy.js";var n=`ArrowUp`,r=`ArrowDown`,i=`ArrowLeft`,a=`ArrowRight`,o=`Home`,s=new Set([n,r,i,a,o,`End`]),c=[`Shift`,`Control`,`Alt`,`Meta`];function l(e){return t(e)&&e.tagName===`INPUT`}function u(e){return!!(l(e)&&e.selectionStart!=null||t(e)&&e.tagName===`TEXTAREA`)}function d(e,t,n,r){if(!e||!t||!t.scrollTo)return;let i=e.scrollLeft,a=e.scrollTop,o=e.clientWidth<e.scrollWidth,s=e.clientHeight<e.scrollHeight;if(o&&r!==`vertical`){let r=f(e,t,`left`),a=p(e),o=p(t);n===`ltr`&&(r+t.offsetWidth+o.scrollMarginRight>e.scrollLeft+e.clientWidth-a.scrollPaddingRight?i=r+t.offsetWidth+o.scrollMarginRight-e.clientWidth+a.scrollPaddingRight:r-o.scrollMarginLeft<e.scrollLeft+a.scrollPaddingLeft&&(i=r-o.scrollMarginLeft-a.scrollPaddingLeft)),n===`rtl`&&(r-o.scrollMarginLeft<e.scrollLeft+a.scrollPaddingLeft?i=r-o.scrollMarginLeft-a.scrollPaddingLeft:r+t.offsetWidth+o.scrollMarginRight>e.scrollLeft+e.clientWidth-a.scrollPaddingRight&&(i=r+t.offsetWidth+o.scrollMarginRight-e.clientWidth+a.scrollPaddingRight))}if(s&&r!==`horizontal`){let n=f(e,t,`top`),r=p(e),i=p(t);n-i.scrollMarginTop<e.scrollTop+r.scrollPaddingTop?a=n-i.scrollMarginTop-r.scrollPaddingTop:n+t.offsetHeight+i.scrollMarginBottom>e.scrollTop+e.clientHeight-r.scrollPaddingBottom&&(a=n+t.offsetHeight+i.scrollMarginBottom-e.clientHeight+r.scrollPaddingBottom)}e.scrollTo({left:i,top:a,behavior:`auto`})}function f(e,t,n){let r=n===`left`?`offsetLeft`:`offsetTop`,i=0;for(;t.offsetParent&&(i+=t[r],t.offsetParent!==e);)t=t.offsetParent;return i}function p(e){let t=getComputedStyle(e);return{scrollMarginTop:parseFloat(t.scrollMarginTop)||0,scrollMarginRight:parseFloat(t.scrollMarginRight)||0,scrollMarginBottom:parseFloat(t.scrollMarginBottom)||0,scrollMarginLeft:parseFloat(t.scrollMarginLeft)||0,scrollPaddingTop:parseFloat(t.scrollPaddingTop)||0,scrollPaddingRight:parseFloat(t.scrollPaddingRight)||0,scrollPaddingBottom:parseFloat(t.scrollPaddingBottom)||0,scrollPaddingLeft:parseFloat(t.scrollPaddingLeft)||0}}function m(t){return e(19)?t:t?`true`:void 0}export{n as a,c,a as i,u as l,r as n,s as o,i as r,o as s,m as t,d as u};
@@ -0,0 +1 @@
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{B as t,E as n,L as r,P as i,W as a,c as o,d as s,j as c,l,r as u,x as d}from"./button-BhAQo6Sy.js";import{M as f,a as p,c as m,i as h,o as g,r as _,s as v,x as y,y as b}from"./api-Bb85n68L.js";var x=e(a(),1);function S(e){return e?.ownerDocument||document}function C(e){let t=e.activeElement;for(;t?.shadowRoot?.activeElement!=null;)t=t.shadowRoot.activeElement;return t}function w(e,t){if(!e||!t)return!1;let r=t.getRootNode?.();if(e.contains(t))return!0;if(r&&n(r)){let n=t;for(;n;){if(e===n)return!0;n=n.parentNode||n.host}}return!1}function T(e){return`composedPath`in e?e.composedPath()[0]:e.target}function E(e,t){return t<0||t>=e.length}function D(e,t){return k(e.current,{disabledIndices:t})}function O(e,t){return k(e.current,{decrement:!0,startingIndex:e.current.length,disabledIndices:t})}function k(e,{startingIndex:t=-1,decrement:n=!1,disabledIndices:r,amount:i=1}={}){let a=t;do a+=n?-i:i;while(a>=0&&a<=e.length-1&&A(e,a,r));return a}function A(e,t,n){if(typeof n==`function`?n(t):n?.includes(t)??!1)return!0;let r=e[t];return r?!M(r)||r.matches(`:disabled`)?!0:!n&&(r.hasAttribute(`disabled`)||r.getAttribute(`aria-disabled`)===`true`):!1}function j(e){return e.visibility===`hidden`||e.visibility===`collapse`}function M(e,t=e?s(e):null){return!e||!e.isConnected||!t||j(t)?!1:typeof e.checkVisibility==`function`?e.checkVisibility():t.display!==`none`&&t.display!==`contents`}var N=x.createContext(void 0);function P(){return x.useContext(N)?.direction??`ltr`}function F(e={}){let{id:n,implicit:i=!1,controlRef:a}=e,{controlId:s,registerControlId:c}=h(),u=b(n),f=i?s:void 0,p=t(()=>Symbol()),m=x.useRef(!1),g=x.useRef(n!=null),_=l(()=>{!m.current||c===r||(m.current=!1,c(p.current,void 0))});return o(()=>{if(c===r)return;let e;if(i){let t=a?.current;e=d(t)&&t.closest(`label`)!=null?n??null:f??u}else if(n!=null)g.current=!0,e=n;else if(g.current)e=u;else{_();return}if(e===void 0){_();return}m.current=!0,c(p.current,e)},[n,a,f,c,i,u,p,_]),x.useEffect(()=>_,[_]),s??u}var I=x.forwardRef(function(e,t){let{render:n,className:r,id:a,name:s,value:c,disabled:u=!1,onValueChange:d,defaultValue:b,autoFocus:w=!1,style:T,...E}=e,{state:D,name:O,disabled:k,setTouched:A,setDirty:j,validityData:M,setFocused:N,setFilled:P,validationMode:I,validation:L}=g(),{clearErrors:R}=p(),z=k||u,B=O??s,V={...D,disabled:z},{labelId:H}=h(),U=F({id:a});o(()=>{let e=c!=null;L.inputRef.current?.value||e&&c!==``?P(!0):e&&c===``&&P(!1)},[L.inputRef,P,c]);let W=x.useRef(null);o(()=>{w&&W.current===C(S(W.current))&&N(!0)},[w,N]);let[G]=m({controlled:c,default:b,name:`FieldControl`,state:`value`}),K=c!==void 0,q=K?G:void 0,J=l(()=>L.inputRef.current?.value);return _(L.inputRef,U,q,J,!z,s),i(`input`,e,{ref:[t,W],state:V,props:[{id:U,disabled:z,name:B,ref:L.inputRef,"aria-labelledby":H,autoFocus:w,...K?{value:q}:{defaultValue:b},onChange(e){let t=e.currentTarget.value;d?.(t,y(f,e.nativeEvent)),j(t!==(M.initialValue??``)),P(t!==``),e.nativeEvent.defaultPrevented||(R(B),L.change(t))},onFocus(){N(!0)},onBlur(e){A(!0),N(!1),I===`onBlur`&&L.commit(e.currentTarget.value)},onKeyDown(e){e.currentTarget.tagName===`INPUT`&&e.key===`Enter`&&(A(!0),L.commit(e.currentTarget.value))}},E,e=>L.getValidationProps(z,e)],stateAttributesMapping:v})}),L=u(),R=x.forwardRef(function(e,t){return(0,L.jsx)(I,{ref:t,...e})});function z({className:e,type:t,...n}){return(0,L.jsx)(R,{type:t,"data-slot":`input`,className:c(`h-8 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40`,e),...n})}export{O as a,E as c,w as d,T as f,k as i,A as l,F as n,D as o,S as p,P as r,M as s,z as t,C as u};
@@ -0,0 +1 @@
function e(e){return e==null||e.hasAttribute(`disabled`)||e.getAttribute(`aria-disabled`)===`true`}export{e as t};
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
import{j as e,n as t,r as n}from"./button-BhAQo6Sy.js";import{V as r}from"./api-Bb85n68L.js";import{t as i}from"./arrow-left-CQp0ScTZ.js";var a=n();function o({title:n,description:o,eyebrow:s,backTo:c,actions:l}){return(0,a.jsxs)(`header`,{className:`relative overflow-hidden rounded-2xl border bg-card shadow-xs`,children:[(0,a.jsx)(`div`,{className:`pointer-events-none absolute -right-20 -top-32 size-72 rounded-full bg-primary/6 blur-3xl`,"aria-hidden":`true`}),(0,a.jsxs)(`div`,{className:`relative flex flex-col gap-5 p-5 sm:p-6 lg:flex-row lg:items-center lg:justify-between`,children:[(0,a.jsxs)(`div`,{className:`flex min-w-0 items-start gap-3.5`,children:[c&&(0,a.jsx)(r,{to:c,"aria-label":wp.i18n.__(`Go back`,`jooosi-fon`),className:e(t({variant:`ghost`,size:`icon`}),`mt-0.5 shrink-0 border bg-background shadow-xs`),children:(0,a.jsx)(i,{"aria-hidden":`true`})}),(0,a.jsxs)(`div`,{className:`min-w-0`,children:[s&&(0,a.jsxs)(`p`,{className:`mb-2 flex items-center gap-2 text-xs font-semibold uppercase tracking-[0.14em] text-primary`,children:[(0,a.jsx)(`span`,{className:`size-1.5 rounded-full bg-primary`,"aria-hidden":`true`}),s]}),(0,a.jsx)(`h1`,{className:`m-0 text-2xl font-semibold tracking-[-0.025em] text-foreground sm:text-[2rem] sm:leading-tight`,children:n}),(0,a.jsx)(`p`,{className:`mb-0 mt-2 max-w-3xl text-sm leading-6 text-muted-foreground`,children:o})]})]}),l&&(0,a.jsx)(`div`,{className:`flex shrink-0 flex-wrap gap-2 lg:justify-end`,children:l})]})]})}export{o as t};
@@ -0,0 +1 @@
import{U as e}from"./button-BhAQo6Sy.js";var t=e(`refresh-cw`,[[`path`,{d:`M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8`,key:`v9h5vc`}],[`path`,{d:`M21 3v5h-5`,key:`1q7to0`}],[`path`,{d:`M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16`,key:`3uifl3`}],[`path`,{d:`M8 16H3v5`,key:`1cv678`}]]);export{t};
@@ -0,0 +1 @@
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),s=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},c=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},l=(n,r,o)=>(o=n==null?{}:e(i(n)),c(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n));export{s as n,l as r,o as t};
@@ -0,0 +1 @@
import{j as e,r as t}from"./button-BhAQo6Sy.js";import{t as n}from"./Separator-D9XfIgMe.js";var r=t();function i({className:t,orientation:i=`horizontal`,...a}){return(0,r.jsx)(n,{"data-slot":`separator`,orientation:i,className:e(`shrink-0 bg-border data-horizontal:h-px data-horizontal:w-full data-vertical:w-px data-vertical:self-stretch`,t),...a})}export{i as t};
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
import{U as e}from"./button-BhAQo6Sy.js";var t=e(`shield-check`,[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`,key:`oel41y`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]);export{t};
@@ -0,0 +1 @@
import{U as e}from"./button-BhAQo6Sy.js";var t=e(`sparkles`,[[`path`,{d:`M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z`,key:`1s2grr`}],[`path`,{d:`M20 2v4`,key:`1rf3ol`}],[`path`,{d:`M22 4h-4`,key:`gwowj6`}],[`circle`,{cx:`4`,cy:`20`,r:`2`,key:`6kqj1y`}]]);export{t};
@@ -0,0 +1 @@
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{U as t,W as n,c as r,j as i,r as a}from"./button-BhAQo6Sy.js";import{y as o}from"./api-Bb85n68L.js";var s=t(`loader-circle`,[[`path`,{d:`M21 12a9 9 0 1 1-6.219-8.56`,key:`13zald`}]]),c=e(n(),1);function l(e,t,n,i=!0,a){let[s,l]=c.useState(),d=o(a?`${a}-label`:void 0),f=e??t??s;return r(()=>{let r=e||t||!i?void 0:u(n.current,d);s!==r&&l(r)}),f}function u(e,t){let n=d(e);if(n)return!n.id&&t&&(n.id=t),n.id||void 0}function d(e){if(!e)return;let t=e.parentElement;if(t&&t.tagName===`LABEL`)return t;let n=e.id;if(n){let t=e.nextElementSibling;if(t&&t.htmlFor===n)return t}let r=e.labels;return r&&r[0]}var f=a();function p({className:e,...t}){return(0,f.jsx)(s,{"data-slot":`spinner`,role:`status`,"aria-label":`Loading`,className:i(`size-4 animate-spin`,e),...t})}export{l as n,p as t};
@@ -0,0 +1 @@
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{I as t,P as n,U as r,V as i,W as a,a as o,c as s,i as c,j as l,r as u,z as d}from"./button-BhAQo6Sy.js";import{M as f,a as ee,c as p,h as te,i as ne,l as re,m as ie,o as m,r as h,s as g,x as _,y as ae}from"./api-Bb85n68L.js";import{n as oe}from"./spinner-B0ROFxgI.js";import{n as se}from"./input-DbQb1wvc.js";var v=r(`trash-2`,[[`path`,{d:`M10 11v6`,key:`nco0om`}],[`path`,{d:`M14 11v6`,key:`outv1u`}],[`path`,{d:`M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6`,key:`miytrc`}],[`path`,{d:`M3 6h18`,key:`d0wm0j`}],[`path`,{d:`M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2`,key:`e791ji`}]]),y=u();function b({className:e,...t}){return(0,y.jsx)(`div`,{"data-slot":`skeleton`,className:l(`animate-pulse rounded-md bg-muted`,e),...t})}var x=e(a(),1),S=x.createContext(void 0);function C(){let e=x.useContext(S);if(e===void 0)throw Error(i(63));return e}var w={...g,checked(e){return e?{"data-checked":``}:{"data-unchecked":``}}},T=x.forwardRef(function(e,r){let{checked:i,className:a,defaultChecked:l,"aria-labelledby":u,form:g,id:v,inputRef:b,name:C,nativeButton:T=!1,onCheckedChange:E,readOnly:D=!1,required:O=!1,disabled:ce=!1,render:le,uncheckedValue:k,value:A,style:ue,...j}=e,{clearErrors:M}=ee(),{state:N,setTouched:P,setDirty:F,validityData:I,setFilled:L,setFocused:R,validationMode:z,disabled:B,name:V,validation:H}=m(),{labelId:U}=ne(),W=B||ce,G=V??C,K=x.useRef(null),de=d(K,b,H.inputRef),q=x.useRef(null),J=ae(),Y=se({id:v,implicit:!1,controlRef:q}),X=T?void 0:Y,[Z,fe]=p({controlled:i,default:!!l,name:`Switch`,state:`checked`});h(q,J,Z,void 0,!W,C),s(()=>{K.current&&L(K.current.checked)},[L]),re(Z,()=>{M(G),F(Z!==I.initialValue),L(Z),H.change(Z)});let{getButtonProps:pe,buttonRef:me}=c({disabled:W,native:T}),he=oe(u,U,K,!T,X),ge={id:T?Y:J,role:`switch`,"aria-checked":Z,"aria-readonly":D||void 0,"aria-required":O||void 0,"aria-labelledby":he,onFocus(){W||R(!0)},onBlur(){let e=K.current;!e||W||(P(!0),R(!1),z===`onBlur`&&H.commit(e.checked))},onClick(e){if(D||W)return;e.preventDefault();let t=K.current;t&&o(t,e)}},_e={...H.getValidationProps(W),checked:Z,disabled:W,form:g,id:X,name:G,required:O,style:G?te:ie,tabIndex:-1,type:`checkbox`,"aria-hidden":!0,ref:de,onChange(e){if(e.nativeEvent.defaultPrevented)return;if(D){e.preventDefault();return}let t=e.currentTarget.checked,n=_(f,e.nativeEvent);E?.(t,n),!n.isCanceled&&fe(t)},onClick(e){e.stopPropagation()},onFocus(){q.current?.focus()},...A===void 0?t:{value:A}},Q=x.useMemo(()=>({...N,checked:Z,disabled:W,readOnly:D,required:O}),[N,Z,W,D,O]),$=n(`span`,e,{state:Q,ref:[r,q,me],props:[ge,j,pe,e=>H.getValidationProps(W,e)],stateAttributesMapping:w});return(0,y.jsxs)(S.Provider,{value:Q,children:[$,!Z&&G&&k!==void 0&&(0,y.jsx)(`input`,{type:`hidden`,form:g,name:G,value:k,disabled:W}),(0,y.jsx)(`input`,{..._e,suppressHydrationWarning:!0})]})}),E=x.forwardRef(function(e,t){let{render:r,className:i,style:a,...o}=e,s=C();return n(`span`,e,{state:s,ref:t,stateAttributesMapping:w,props:o})});function D({className:e,size:t=`default`,...n}){return(0,y.jsx)(T,{"data-slot":`switch`,"data-size":t,className:l(`peer group/switch relative inline-flex shrink-0 items-center rounded-full border border-transparent transition-all outline-none after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-[size=default]:h-[18.4px] data-[size=default]:w-[32px] data-[size=sm]:h-[14px] data-[size=sm]:w-[24px] dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:bg-primary data-unchecked:bg-input dark:data-unchecked:bg-input/80 data-disabled:cursor-not-allowed data-disabled:opacity-50`,e),...n,children:(0,y.jsx)(E,{"data-slot":`switch-thumb`,className:`pointer-events-none block rounded-full bg-background ring-0 transition-transform group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 group-data-[size=default]/switch:data-checked:translate-x-[calc(100%-2px)] group-data-[size=sm]/switch:data-checked:translate-x-[calc(100%-2px)] dark:data-checked:bg-primary-foreground group-data-[size=default]/switch:data-unchecked:translate-x-0 group-data-[size=sm]/switch:data-unchecked:translate-x-0 dark:data-unchecked:bg-foreground`})})}export{b as n,v as r,D as t};
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
import{U as e}from"./button-BhAQo6Sy.js";var t=e(`type`,[[`path`,{d:`M12 4v16`,key:`1654pz`}],[`path`,{d:`M4 7V5a1 1 0 0 1 1-1h14a1 1 0 0 1 1 1v2`,key:`e0r10z`}],[`path`,{d:`M9 20h6`,key:`s66wpe`}]]);export{t};
@@ -0,0 +1 @@
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{U as t,W as n,j as r,r as i}from"./button-BhAQo6Sy.js";import{J as a}from"./api-Bb85n68L.js";import"./switch-DMNAfdJq.js";import{t as o}from"./input-DbQb1wvc.js";var s=t(`save`,[[`path`,{d:`M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z`,key:`1c8476`}],[`path`,{d:`M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7`,key:`1ydtos`}],[`path`,{d:`M7 3v4a1 1 0 0 0 1 1h7`,key:`t51u73`}]]),c=i();function l({label:e,hint:t,error:n,children:i,className:a}){return(0,c.jsxs)(`label`,{className:r(`grid gap-1.5 text-sm font-medium text-foreground`,a),children:[(0,c.jsx)(`span`,{children:e}),i,(n||t)&&(0,c.jsx)(`span`,{className:r(`text-xs font-normal text-muted-foreground`,n&&`text-destructive`),children:n||t})]})}function u(e){return(0,c.jsx)(o,{...e})}function d({className:e,...t}){return(0,c.jsx)(`select`,{className:r(`h-8 w-full rounded-lg border border-input bg-background px-2.5 text-sm text-foreground outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50`,e),...t})}var f=e(n(),1);function p(e){let t=(0,f.useRef)(!1),n=a(({currentLocation:n,nextLocation:r})=>e&&!t.current&&n.pathname!==r.pathname);return(0,f.useEffect)(()=>{let t=t=>{e&&t.preventDefault()};return window.addEventListener(`beforeunload`,t),()=>window.removeEventListener(`beforeunload`,t)},[e]),(0,f.useEffect)(()=>{n.state===`blocked`&&(window.confirm(wp.i18n.__(`You have unsaved changes. Leave this page?`,`jooosi-fon`))?n.proceed():n.reset())},[n]),(0,f.useCallback)(()=>{t.current=!0},[])}export{s as a,u as i,l as n,d as r,p as t};
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,427 @@
{
"_CompositeList-Dv5F3X1a.js": {
"file": "assets/CompositeList-Dv5F3X1a.js",
"name": "CompositeList",
"imports": [
"_rolldown-runtime-hePW80VL.js",
"_button-BhAQo6Sy.js"
]
},
"_Separator-D9XfIgMe.js": {
"file": "assets/Separator-D9XfIgMe.js",
"name": "Separator",
"imports": [
"_rolldown-runtime-hePW80VL.js",
"_button-BhAQo6Sy.js"
]
},
"_api-Bb85n68L.js": {
"file": "assets/api-Bb85n68L.js",
"name": "api",
"imports": [
"_rolldown-runtime-hePW80VL.js",
"_button-BhAQo6Sy.js"
]
},
"_arrow-left-CQp0ScTZ.js": {
"file": "assets/arrow-left-CQp0ScTZ.js",
"name": "arrow-left",
"imports": [
"_button-BhAQo6Sy.js"
]
},
"_button-BhAQo6Sy.js": {
"file": "assets/button-BhAQo6Sy.js",
"name": "button",
"imports": [
"_rolldown-runtime-hePW80VL.js"
]
},
"_checkbox-BvMiUPpO.js": {
"file": "assets/checkbox-BvMiUPpO.js",
"name": "checkbox",
"imports": [
"_rolldown-runtime-hePW80VL.js",
"_button-BhAQo6Sy.js",
"_api-Bb85n68L.js",
"_spinner-B0ROFxgI.js"
]
},
"_cloud-upload-C1d9L0C_.js": {
"file": "assets/cloud-upload-C1d9L0C_.js",
"name": "cloud-upload",
"imports": [
"_button-BhAQo6Sy.js"
]
},
"_file-code-corner-DcXF_mTi.js": {
"file": "assets/file-code-corner-DcXF_mTi.js",
"name": "file-code-corner",
"imports": [
"_button-BhAQo6Sy.js"
]
},
"_font-editor-layout-DqX_DfJ-.js": {
"file": "assets/font-editor-layout-DqX_DfJ-.js",
"name": "font-editor-layout",
"imports": [
"_rolldown-runtime-hePW80VL.js",
"_button-BhAQo6Sy.js",
"_api-Bb85n68L.js",
"_arrow-left-CQp0ScTZ.js",
"_switch-DMNAfdJq.js",
"_type-Df9tHIH_.js",
"_input-DbQb1wvc.js"
]
},
"_font-preview-Sn0GCLRT.js": {
"file": "assets/font-preview-Sn0GCLRT.js",
"name": "font-preview"
},
"_frame-Bg0IxU65.js": {
"file": "assets/frame-Bg0IxU65.js",
"name": "frame",
"imports": [
"_button-BhAQo6Sy.js"
]
},
"_getPseudoElementBounds-VHBO4Fpp.js": {
"file": "assets/getPseudoElementBounds-VHBO4Fpp.js",
"name": "getPseudoElementBounds",
"imports": [
"_rolldown-runtime-hePW80VL.js",
"_button-BhAQo6Sy.js",
"_api-Bb85n68L.js",
"_usePositioner-BR1Prb1t.js",
"_useAnchoredPopupScrollLock-ufKQIYDq.js",
"_input-DbQb1wvc.js"
]
},
"_google-fonts-icon-BCkwWN32.js": {
"file": "assets/google-fonts-icon-BCkwWN32.js",
"name": "google-fonts-icon",
"imports": [
"_button-BhAQo6Sy.js"
]
},
"_inertValue-DD-hQv2D.js": {
"file": "assets/inertValue-DD-hQv2D.js",
"name": "inertValue",
"imports": [
"_button-BhAQo6Sy.js"
]
},
"_input-DbQb1wvc.js": {
"file": "assets/input-DbQb1wvc.js",
"name": "input",
"imports": [
"_rolldown-runtime-hePW80VL.js",
"_button-BhAQo6Sy.js",
"_api-Bb85n68L.js"
]
},
"_isElementDisabled-KSuuBj8D.js": {
"file": "assets/isElementDisabled-KSuuBj8D.js",
"name": "isElementDisabled"
},
"_page-header-DHR4N007.js": {
"file": "assets/page-header-DHR4N007.js",
"name": "page-header",
"imports": [
"_button-BhAQo6Sy.js",
"_api-Bb85n68L.js",
"_arrow-left-CQp0ScTZ.js"
]
},
"_refresh-cw-0zQVax2T.js": {
"file": "assets/refresh-cw-0zQVax2T.js",
"name": "refresh-cw",
"imports": [
"_button-BhAQo6Sy.js"
]
},
"_rolldown-runtime-hePW80VL.js": {
"file": "assets/rolldown-runtime-hePW80VL.js",
"name": "rolldown-runtime"
},
"_separator-IZXL6QXg.js": {
"file": "assets/separator-IZXL6QXg.js",
"name": "separator",
"imports": [
"_button-BhAQo6Sy.js",
"_Separator-D9XfIgMe.js"
]
},
"_shield-check-D5H7T_9T.js": {
"file": "assets/shield-check-D5H7T_9T.js",
"name": "shield-check",
"imports": [
"_button-BhAQo6Sy.js"
]
},
"_sparkles-Sg_bA45R.js": {
"file": "assets/sparkles-Sg_bA45R.js",
"name": "sparkles",
"imports": [
"_button-BhAQo6Sy.js"
]
},
"_spinner-B0ROFxgI.js": {
"file": "assets/spinner-B0ROFxgI.js",
"name": "spinner",
"imports": [
"_rolldown-runtime-hePW80VL.js",
"_button-BhAQo6Sy.js",
"_api-Bb85n68L.js"
]
},
"_switch-DMNAfdJq.js": {
"file": "assets/switch-DMNAfdJq.js",
"name": "switch",
"imports": [
"_rolldown-runtime-hePW80VL.js",
"_button-BhAQo6Sy.js",
"_api-Bb85n68L.js",
"_spinner-B0ROFxgI.js",
"_input-DbQb1wvc.js"
]
},
"_tooltip-BJCKJ7vw.js": {
"file": "assets/tooltip-BJCKJ7vw.js",
"name": "tooltip",
"imports": [
"_rolldown-runtime-hePW80VL.js",
"_button-BhAQo6Sy.js",
"_api-Bb85n68L.js",
"_usePositioner-BR1Prb1t.js",
"_input-DbQb1wvc.js"
]
},
"_type-Df9tHIH_.js": {
"file": "assets/type-Df9tHIH_.js",
"name": "type",
"imports": [
"_button-BhAQo6Sy.js"
]
},
"_use-unsaved-changes-CBW9Uy54.js": {
"file": "assets/use-unsaved-changes-CBW9Uy54.js",
"name": "use-unsaved-changes",
"imports": [
"_rolldown-runtime-hePW80VL.js",
"_button-BhAQo6Sy.js",
"_api-Bb85n68L.js",
"_switch-DMNAfdJq.js",
"_input-DbQb1wvc.js"
]
},
"_useAnchoredPopupScrollLock-ufKQIYDq.js": {
"file": "assets/useAnchoredPopupScrollLock-ufKQIYDq.js",
"name": "useAnchoredPopupScrollLock",
"imports": [
"_rolldown-runtime-hePW80VL.js",
"_button-BhAQo6Sy.js",
"_api-Bb85n68L.js",
"_usePositioner-BR1Prb1t.js",
"_input-DbQb1wvc.js"
]
},
"_usePositioner-BR1Prb1t.js": {
"file": "assets/usePositioner-BR1Prb1t.js",
"name": "usePositioner",
"imports": [
"_rolldown-runtime-hePW80VL.js",
"_button-BhAQo6Sy.js",
"_api-Bb85n68L.js",
"_input-DbQb1wvc.js"
]
},
"node_modules/.pnpm/opentype.js@2.0.0/node_modules/opentype.js/dist/opentype.js": {
"file": "assets/opentype-6XcYdTgz.js",
"name": "opentype",
"src": "node_modules/.pnpm/opentype.js@2.0.0/node_modules/opentype.js/dist/opentype.js",
"isDynamicEntry": true,
"imports": [
"_rolldown-runtime-hePW80VL.js"
]
},
"node_modules/.pnpm/woff2-encoder@3.0.0-beta.1/node_modules/woff2-encoder/dist/decompress.mjs": {
"file": "assets/decompress-BFqEkQYo.js",
"name": "decompress",
"src": "node_modules/.pnpm/woff2-encoder@3.0.0-beta.1/node_modules/woff2-encoder/dist/decompress.mjs",
"isDynamicEntry": true
},
"resources/main.tsx": {
"file": "assets/app-Di4tDCA1.js",
"name": "app",
"src": "resources/main.tsx",
"isEntry": true,
"imports": [
"_rolldown-runtime-hePW80VL.js",
"_button-BhAQo6Sy.js",
"_api-Bb85n68L.js",
"_usePositioner-BR1Prb1t.js",
"_useAnchoredPopupScrollLock-ufKQIYDq.js",
"_sparkles-Sg_bA45R.js",
"_tooltip-BJCKJ7vw.js",
"_input-DbQb1wvc.js",
"_getPseudoElementBounds-VHBO4Fpp.js",
"_inertValue-DD-hQv2D.js",
"_CompositeList-Dv5F3X1a.js",
"_Separator-D9XfIgMe.js"
],
"dynamicImports": [
"resources/pages/fonts-page.tsx",
"resources/pages/custom-font-editor-page.tsx",
"resources/pages/google-font-editor-page.tsx",
"resources/pages/settings-page.tsx",
"resources/pages/migrations-page.tsx",
"resources/pages/about-page.tsx"
],
"css": [
"assets/app-BiDlEhMF.css"
]
},
"resources/pages/about-page.tsx": {
"file": "assets/about-page-BOF-0jOE.js",
"name": "about-page",
"src": "resources/pages/about-page.tsx",
"isDynamicEntry": true,
"imports": [
"_rolldown-runtime-hePW80VL.js",
"_button-BhAQo6Sy.js",
"_file-code-corner-DcXF_mTi.js",
"_shield-check-D5H7T_9T.js",
"_sparkles-Sg_bA45R.js",
"resources/main.tsx",
"_frame-Bg0IxU65.js",
"_separator-IZXL6QXg.js"
]
},
"resources/pages/custom-font-editor-page.tsx": {
"file": "assets/custom-font-editor-page-CLa_Hmv3.js",
"name": "custom-font-editor-page",
"src": "resources/pages/custom-font-editor-page.tsx",
"isDynamicEntry": true,
"imports": [
"_rolldown-runtime-hePW80VL.js",
"_button-BhAQo6Sy.js",
"_api-Bb85n68L.js",
"_usePositioner-BR1Prb1t.js",
"_cloud-upload-C1d9L0C_.js",
"_spinner-B0ROFxgI.js",
"_use-unsaved-changes-CBW9Uy54.js",
"_switch-DMNAfdJq.js",
"_type-Df9tHIH_.js",
"_tooltip-BJCKJ7vw.js",
"_input-DbQb1wvc.js",
"resources/main.tsx",
"_frame-Bg0IxU65.js",
"_font-editor-layout-DqX_DfJ-.js",
"_font-preview-Sn0GCLRT.js"
],
"dynamicImports": [
"node_modules/.pnpm/opentype.js@2.0.0/node_modules/opentype.js/dist/opentype.js",
"node_modules/.pnpm/woff2-encoder@3.0.0-beta.1/node_modules/woff2-encoder/dist/decompress.mjs"
]
},
"resources/pages/fonts-page.tsx": {
"file": "assets/fonts-page-TiwU4Pq5.js",
"name": "fonts-page",
"src": "resources/pages/fonts-page.tsx",
"isDynamicEntry": true,
"imports": [
"_rolldown-runtime-hePW80VL.js",
"_button-BhAQo6Sy.js",
"_api-Bb85n68L.js",
"_checkbox-BvMiUPpO.js",
"_usePositioner-BR1Prb1t.js",
"_spinner-B0ROFxgI.js",
"_refresh-cw-0zQVax2T.js",
"_useAnchoredPopupScrollLock-ufKQIYDq.js",
"_shield-check-D5H7T_9T.js",
"_sparkles-Sg_bA45R.js",
"_switch-DMNAfdJq.js",
"_tooltip-BJCKJ7vw.js",
"_input-DbQb1wvc.js",
"_getPseudoElementBounds-VHBO4Fpp.js",
"_inertValue-DD-hQv2D.js",
"_CompositeList-Dv5F3X1a.js",
"_isElementDisabled-KSuuBj8D.js",
"_frame-Bg0IxU65.js",
"_separator-IZXL6QXg.js",
"_font-preview-Sn0GCLRT.js",
"_google-fonts-icon-BCkwWN32.js"
]
},
"resources/pages/google-font-editor-page.tsx": {
"file": "assets/google-font-editor-page-B0uFdvqx.js",
"name": "google-font-editor-page",
"src": "resources/pages/google-font-editor-page.tsx",
"isDynamicEntry": true,
"imports": [
"_rolldown-runtime-hePW80VL.js",
"_button-BhAQo6Sy.js",
"_api-Bb85n68L.js",
"_checkbox-BvMiUPpO.js",
"_usePositioner-BR1Prb1t.js",
"_spinner-B0ROFxgI.js",
"_refresh-cw-0zQVax2T.js",
"_use-unsaved-changes-CBW9Uy54.js",
"_useAnchoredPopupScrollLock-ufKQIYDq.js",
"_switch-DMNAfdJq.js",
"_input-DbQb1wvc.js",
"_inertValue-DD-hQv2D.js",
"resources/main.tsx",
"_frame-Bg0IxU65.js",
"_separator-IZXL6QXg.js",
"_font-editor-layout-DqX_DfJ-.js",
"_google-fonts-icon-BCkwWN32.js"
]
},
"resources/pages/migrations-page.tsx": {
"file": "assets/migrations-page-Cy-SJqlg.js",
"name": "migrations-page",
"src": "resources/pages/migrations-page.tsx",
"isDynamicEntry": true,
"imports": [
"_rolldown-runtime-hePW80VL.js",
"_button-BhAQo6Sy.js",
"_api-Bb85n68L.js",
"_checkbox-BvMiUPpO.js",
"_cloud-upload-C1d9L0C_.js",
"_spinner-B0ROFxgI.js",
"_sparkles-Sg_bA45R.js",
"_type-Df9tHIH_.js",
"resources/main.tsx",
"_frame-Bg0IxU65.js",
"_separator-IZXL6QXg.js",
"_page-header-DHR4N007.js"
]
},
"resources/pages/settings-page.tsx": {
"file": "assets/settings-page-sC5J1KHE.js",
"name": "settings-page",
"src": "resources/pages/settings-page.tsx",
"isDynamicEntry": true,
"imports": [
"_rolldown-runtime-hePW80VL.js",
"_button-BhAQo6Sy.js",
"_api-Bb85n68L.js",
"_file-code-corner-DcXF_mTi.js",
"_spinner-B0ROFxgI.js",
"_refresh-cw-0zQVax2T.js",
"_use-unsaved-changes-CBW9Uy54.js",
"_shield-check-D5H7T_9T.js",
"_switch-DMNAfdJq.js",
"_input-DbQb1wvc.js",
"_inertValue-DD-hQv2D.js",
"_CompositeList-Dv5F3X1a.js",
"_isElementDisabled-KSuuBj8D.js",
"resources/main.tsx",
"_frame-Bg0IxU65.js",
"_separator-IZXL6QXg.js",
"_page-header-DHR4N007.js"
]
}
}
@@ -0,0 +1,71 @@
{
"name": "jooosi\/fon",
"description": "Self-hosted Google Fonts, Adobe Fonts, and custom font management for WordPress.",
"type": "wordpress-plugin",
"license": "GPL-3.0-or-later",
"repositories": {
"edd-sl-sdk": {
"type": "vcs",
"url": "https:\/\/github.com\/awesomemotive\/edd-sl-sdk"
}
},
"autoload": {
"psr-4": {
"JooosiFon\\": "src\/"
},
"files": [
"constant.php"
]
},
"config": {
"preferred-install": "dist",
"sort-packages": true,
"optimize-autoloader": true
},
"minimum-stability": "dev",
"prefer-stable": true,
"scripts": {
"complete-check": [
"@check-ecs",
"@phpstan",
"@test-api",
"@test-cache",
"@test-license",
"@test-migrations",
"@test-upgrades",
"phpunit"
],
"phpstan": "vendor\/bin\/phpstan analyse --ansi --error-format symplify",
"rector": "vendor\/bin\/rector process --ansi",
"check-ecs": "vendor\/bin\/ecs check --ansi",
"fix-ecs": "vendor\/bin\/ecs check --fix --ansi",
"test-api": "@php tests\/api-support.php",
"test-cache": [
"@php tests\/cache-renderer.php",
"@php tests\/cache-build.php"
],
"test-license": [
"@php tests\/licensing-manager.php normal",
"@php tests\/licensing-manager.php late"
],
"test-migrations": [
"@php tests\/migration-sources.php",
"@php tests\/database-migrations.php",
"@php tests\/font-table.php"
],
"test-upgrades": "@php tests\/legacy-rebrand-upgrade.php"
},
"require-dev": {
"rector\/rector": "^0.17.1",
"symplify\/easy-coding-standard": "^11.3"
},
"require": {
"php": ">=7.4",
"hidehalo\/nanoid-php": "^1.1",
"nabasa\/vp-wp": "^0.3.0",
"sabberworm\/php-css-parser": "^8.8",
"symfony\/finder": "^5.4",
"symfony\/property-access": "^5.4",
"symfony\/stopwatch": "^5.4"
}
}
@@ -0,0 +1,97 @@
<?php
/*
* This file is part of the Jooosi Fon package.
*
* (c) Joshua Gugun Siagian <suabahasa@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare (strict_types=1);
namespace JooosiFonDeps;
/**
* Plugin constants.
*
* @since 2.0.0
*/
class JOOOSI_FON
{
/**
* @var string
*/
public const FILE = __DIR__ . '/jooosi-fon.php';
/**
* @var string
*/
public const VERSION = '1.1.4';
/**
* @var string
*/
public const WP_OPTION = 'jooosi_fon';
/**
* Existing installations used this prefix for persisted options and the
* original admin-page slug.
*
* @todo Remove this legacy option prefix completely in Jooosi Fon 3.0.0.
*
* @var string
*/
public const LEGACY_WP_OPTION = 'yabe_webfont';
/**
* @var string
*/
public const DB_TABLE_PREFIX = 'jooosi_fon';
/**
* The text domain should use the literal string 'jooosi-fon' as the text domain.
* This constant is used for reference only and should not be used as the actual text domain.
*
* @var string
*/
public const TEXT_DOMAIN = 'jooosi-fon';
/**
* @var array
*/
public const EDD_STORE = ['store_url' => 'https://jooo.si', 'item_id' => 18];
/**
* @var string
*/
public const REST_NAMESPACE = 'jooosi-fon/v1';
/**
* @var string
*/
public const PLUGIN_URI = 'https://fon.jooo.si';
/**
* @var
*/
public const USER_AGENTS = [
'WOFF2' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:43.0) Gecko/20100101 Firefox/43.0',
'WOFF' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:38.0) Gecko/20100101 Firefox/38.0',
'TTF' => 'Mozilla/5.0 (Unknown; Linux x86_64) AppleWebKit/538.1 (KHTML, like Gecko) Safari/538.1 Daum/4.1',
// 'CURRENT' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/115.0',
'CURRENT' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:139.0) Gecko/20100101 Firefox/139.0',
];
}
/**
* Plugin constants.
*
* @since 2.0.0
*/
\class_alias('JooosiFonDeps\JOOOSI_FON', 'JOOOSI_FON', \false);
/**
* The former global constants class is retained for 2.x integrations.
*
* @todo Remove this legacy class alias completely in Jooosi Fon 3.0.0.
*/
if (!\class_exists('JooosiFonDeps\YABE_WEBFONT', \false)) {
\class_alias(\JooosiFonDeps\JOOOSI_FON::class, 'JooosiFonDeps\YABE_WEBFONT');
}
/**
* The developer documentation exposed this utility class before the rebrand.
*
* @todo Remove this legacy class alias completely in Jooosi Fon 3.0.0.
*/
if (!\class_exists('JooosiFonDeps\Yabe\Webfont\Utils\Font', \false)) {
\class_alias(\JooosiFon\Utils\Font::class, 'JooosiFonDeps\Yabe\Webfont\Utils\Font');
}
File diff suppressed because one or more lines are too long
@@ -0,0 +1,31 @@
<?php
/**
* @wordpress-plugin
* Plugin Name: Jooosi Fon
* Plugin URI: https://fon.jooo.si
* Description: Easy self-host Google Fonts, Adobe Fonts support, or upload custom fonts in WordPress that are integrated into the most popular themes and page builders.
* Version: 1.1.4
* Requires at least: 6.0
* Requires PHP: 7.4
* Author: Jooosi
* Author URI: https://jooo.si
* Donate link: https://ko-fi.com/Q5Q75XSF7
* Text Domain: jooosi-fon
* Domain Path: /languages
* License: GPL-3.0-or-later
*
* @package JooosiFon
*/
declare (strict_types=1);
namespace JooosiFonDeps;
\defined('ABSPATH') || exit;
if (\file_exists(__DIR__ . '/vendor/autoload.php')) {
if (\file_exists(__DIR__ . '/vendor/scoper-autoload.php')) {
require_once __DIR__ . '/vendor/scoper-autoload.php';
} else {
require_once __DIR__ . '/vendor/autoload.php';
}
\JooosiFon\Plugin::get_instance()->boot();
}
@@ -0,0 +1,9 @@
<svg viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg">
<g fill="currentColor">
<path d="m255.487 348.511-38.054 21.97-15.574 124.592c-.536 4.286.794 8.596 3.653 11.834s6.97 5.093 11.289 5.093h75.578c4.32 0 8.43-1.855 11.289-5.093s4.189-7.548 3.653-11.834l-21.591-172.724c-8.206 10.444-18.406 19.327-30.243 26.162z"></path>
<path d="m270.097 158.141v-143.082c0-5.219-2.702-10.066-7.142-12.81-4.44-2.743-9.982-2.994-14.651-.659l-27.05 13.525c-25.759 12.879-41.761 38.771-41.761 67.57v83.59c0 16.328 5.224 31.449 14.064 43.817l29.912-17.27c11.989-15.749 28.037-27.701 46.628-34.681z"></path>
<path d="m236.976 268.498c-13.719-5.811-23.992-18.2-26.868-33.186l-145.939 84.259c-4.52 2.609-7.367 7.373-7.523 12.59-.157 5.217 2.399 10.143 6.755 13.018l25.238 16.664c12.671 8.366 27.115 12.574 41.598 12.574 12.988 0 26.008-3.386 37.799-10.194l72.391-41.795c14.14-8.164 24.624-20.249 30.914-34.088z"></path>
<path d="m417.584 233.375-72.391-41.795c-17.475-10.09-37.835-12.769-57.325-7.547-3.598.964-7.085 2.18-10.446 3.625 13.427 7.871 22.47 22.446 22.47 39.103 0 13.661-6.087 25.919-15.68 34.232l146.636 84.66c2.327 1.344 4.927 2.018 7.529 2.018 2.452 0 4.906-.598 7.135-1.798 4.596-2.473 7.583-7.149 7.896-12.359l1.813-30.189c1.726-28.747-12.696-55.551-37.637-69.95z"></path>
<circle cx="254.59" cy="226.761" r="15.184"></circle>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.4 KiB

@@ -0,0 +1,28 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Migrations;
use JooosiFon\Database\FontTable;
use JooosiFon\Database\Migration\AbstractMigration;
/**
* Create the Jooosi Fon font library table.
*/
final class Version20221121114557 extends AbstractMigration
{
public function getDescription(): string
{
return 'Create the Jooosi Fon fonts table.';
}
public function up(): void
{
FontTable::create();
}
public function down(): void
{
/** @var wpdb $wpdb */
global $wpdb;
$sql = "DROP TABLE IF EXISTS `{$wpdb->prefix}jooosi_fon_fonts`";
$wpdb->query($sql);
}
}
@@ -0,0 +1,42 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Migrations;
use JooosiFon\Database\FontTable;
use JooosiFon\Database\Migration\AbstractMigration;
use wpdb;
/**
* Rename the font library table for the Jooosi Fon rebrand.
*
* @todo Remove this legacy rebrand migration completely in Jooosi Fon 3.0.0.
*/
final class Version20260817000000 extends AbstractMigration
{
public function getDescription(): string
{
return 'Rename the legacy fonts table to Jooosi Fon.';
}
public function up(): void
{
FontTable::migrateLegacy();
}
public function down(): void
{
/** @var wpdb $wpdb */
global $wpdb;
$legacyTable = $wpdb->prefix . 'yabe_webfont_fonts';
$table = $wpdb->prefix . 'jooosi_fon_fonts';
if ($this->table_exists($table) && !$this->table_exists($legacyTable)) {
if ($wpdb->query("RENAME TABLE `{$table}` TO `{$legacyTable}`") === \false) {
throw new \RuntimeException($wpdb->last_error ?: 'Unable to restore the legacy Jooosi Fon fonts table.');
}
}
}
private function table_exists(string $table): bool
{
/** @var wpdb $wpdb */
global $wpdb;
return $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->esc_like($table))) === $table;
}
}
@@ -0,0 +1,53 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Migrations;
use JooosiFon\Database\FontTable;
use JooosiFon\Database\Migration\AbstractMigration;
/**
* Make font payload storage and the API's common filters scale safely.
*/
final class Version20260818000000 extends AbstractMigration
{
public function getDescription(): string
{
return 'Expand font payload columns and add API query indexes.';
}
public function up(): void
{
global $wpdb;
// Repair an incomplete rebrand before altering or querying the table.
FontTable::migrateLegacy();
$table = $wpdb->prefix . 'jooosi_fon_fonts';
$statements = ["ALTER TABLE `{$table}` MODIFY `metadata` MEDIUMTEXT NULL, MODIFY `font_faces` MEDIUMTEXT NULL"];
$indexes = ['jooosi_fon_deleted_status' => '`deleted_at`, `status`', 'jooosi_fon_type_deleted' => '`type`, `deleted_at`', 'jooosi_fon_slug' => '`slug`(191)'];
foreach ($indexes as $index => $columns) {
if (!$this->indexExists($table, $index)) {
$statements[] = "ALTER TABLE `{$table}` ADD INDEX `{$index}` ({$columns})";
}
}
foreach ($statements as $statement) {
if ($wpdb->query($statement) === \false) {
throw new \RuntimeException($wpdb->last_error ?: 'Unable to optimize the Jooosi Fon fonts table.');
}
}
}
public function down(): void
{
global $wpdb;
$table = $wpdb->prefix . 'jooosi_fon_fonts';
foreach (['jooosi_fon_deleted_status', 'jooosi_fon_type_deleted', 'jooosi_fon_slug'] as $index) {
if ($this->indexExists($table, $index)) {
$wpdb->query("ALTER TABLE `{$table}` DROP INDEX `{$index}`");
}
}
}
private function indexExists(string $table, string $index): bool
{
global $wpdb;
return (bool) $wpdb->get_var($wpdb->prepare('SELECT 1 FROM information_schema.statistics
WHERE table_schema = DATABASE() AND table_name = %s AND index_name = %s
LIMIT 1', $table, $index));
}
}
@@ -0,0 +1,23 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Migrations;
use JooosiFon\Database\Migration\AbstractMigration;
/**
* Repair installations where the rebrand migration history was recorded but
* the Jooosi Fon font table was never created or restored.
*/
final class Version20260902000000 extends AbstractMigration
{
public function getDescription(): string
{
return 'Repair a missing Jooosi Fon fonts table after the rebrand.';
}
public function up(): void
{
// Reapply the idempotent schema optimization when an earlier history
// row says it ran even though the table itself was lost.
(new \JooosiFon\Migrations\Version20260818000000())->up();
}
}
+651
View File
@@ -0,0 +1,651 @@
=== Jooosi Fon - Use Custom Fonts, Google Fonts or Adobe Fonts ===
Contributors: suasgn, suabahasa
Donate link: https://ko-fi.com/Q5Q75XSF7
Tags: custom fonts, google fonts, adobe fonts, gdpr, dsgvo
Requires at least: 6.0
Tested up to: 7.1
Stable tag: 1.1.4
Requires PHP: 7.4
License: GPLv3
License URI: https://www.gnu.org/licenses/gpl-3.0.html
Easy self-host Google Fonts, Adobe Fonts support, or upload custom fonts in WordPress. Integrated into the most popular themes and page builders.
== Description ==
### Jooosi Fon: the #1 Self-hosted Google Fonts and Custom Fonts Manager for WordPress
Jooosi Fon is a GDPR-friendly font WordPress plugin made for designers and developers that is advanced, easy to use, and intuitive to give you complete control over your fonts and typography in WordPress.
### FEATURES
Jooosi Fon is packed full of features designed to streamline your workflow. Some of our favorites are:
* **GDPR / DSGVO friendly**: You can import/self-host Google Fonts files from your server through your WordPress admin page. Fewer reasons to worry about GDPR / DSGVO compliance.
* **Google Fonts and Adobe Fonts ready**: Start using any available fonts on Google Fonts and Adobe Fonts.
* **Custom Fonts**: A dedicated custom fonts manager for WordPress. The central place to manage all your fonts and typography.
* **Easy to use**: Add custom fonts to your WordPress site with a simple and intuitive interface. No coding knowledge is needed. You can upload the font files using the WordPress media uploader. No FTP is required.
* **Fine-tuning**: Complete control over your fonts and typography. On 90% of use cases, the default one is good to go.
* **Lightweight and blazingly fast**: The font management system uses WordPress REST API and a modern JavaScript framework for an instant, responsive user experience. The front page cache ensures fast loading and reduces database queries.
* **Variable Fonts support**: The format allows a single font file to contain multiple stylistic variations.
* **Multisite support**: The plugin is compatible with WordPress Multisite (Activate the plugin on the site level).
### SEAMLESS INTEGRATION
The font must be available for use across different platforms. Jooosi Fon is famous for seamlessly integrating with the most popular visual/page builders:
* [Builderius](https://builderius.io/?referral=afdfca82c8)
* [Classic Editor](https://wordpress.org/plugins/classic-editor/)
* [Elementor](https://be.elementor.com/visit/?bta=209150&brand=elementor)
* [GeneratePress](https://generatepress.com/?ref=7954)
* [Gutenberg Blocks and Site Editor](https://wordpress.org/gutenberg/?ref=jooosi)
* [Kadence WP](https://kadencewp.com/?ref=jooosi)
* [Pinegrow](https://pinegrow.com/wordpress?ref=jooosi)
* [Beaver Builder](https://www.wpbeaverbuilder.com/) **[Pro]**
* [Blocksy](https://creativethemes.com/blocksy) **[Pro]**
* [Breakdance](https://breakdance.com/ref/165/) **[Pro]**
* [Bricks](https://bricksbuilder.io/?ref=jooosi) **[Pro]**
* [Cwicly](https://cwicly.com/?ref=suabahasa) **[Pro]**
* [Divi](https://www.elegantthemes.com/affiliates/idevaffiliate.php?id=47622) **[Pro]**
* [Etch](https://etchwp.com?aff=bce0d1ab) **[Pro]**
* [FunnelKit/SlingBlocks](https://wordpress.org/plugins/slingblocks/) **[Pro]**
* [Greenshift](https://shop.greenshiftwp.com/?from=3679) **[Pro]**
* [Oxygen](https://oxygenbuilder.com/ref/12/) **[Pro]**
* [Slider Revolution](https://www.sliderrevolution.com/) **[Pro]**
* [Spectra](https://wpspectra.com/) **[Pro]**
* [YellowPencil](https://yellowpencil.waspthemes.com/) **[Pro]**
* [Zion Builder](https://zionbuilder.io/?ref=jooosi) **[Pro]**
Visit [our website](https://fon.jooo.si) for more information.
= Love Jooosi Fon? =
- Purchase the [Pro version](https://fon.jooo.si)
- Join our [Facebook Group](https://www.facebook.com/groups/1142662969627943)
- Or rate us on [WordPress](https://wordpress.org/support/plugin/yabe-webfont/reviews/?filter=5/#new-post)
= Credits =
- Image by [Freepik](https://www.flaticon.com/free-icon/windmill_5137991?related_id=5137991) on Flaticon
[youtube https://www.youtube.com/watch?v=uMj0x0ucnOw]
[youtube https://www.youtube.com/watch?v=A0JZzEVIUzQ]
== Changelog ==
= 1.1.4 - 2026-09-19 =
**Fixed**
* Bricks 2.x integration when font favorites are not initialized.
= 1.1.3 - 2026-09-02 =
**Fixed**
* Repair a missing font library table and add a manual Yabe Webfont migration action in Settings.
**Changed**
* Test compatibility with WordPress 7.1.
= 1.1.2 - 2026-09-02 =
**Fixed**
* Fix the Yabe Webfont to Jooosi Fon upgrade migration and make legacy data cleanup optional.
= 1.1.1 - 2026-08-26 =
**Fixed**
* Prevent scoped release builds from generating broken proxies for WordPress functions declared by test stubs.
= 1.1.0 - 2026-08-26 =
**Added**
* Added migration tool to import data from Custom Fonts by Brainstorm Force
* Added migration tool to import data from Custom Adobe Fonts
* Added migration tool to import data from Elementor Pro Custom Fonts
* Added migration tool to import data from Fonts Plugin
* Added migration tool to import data from Use Any Font
**Changed**
* Rebrand the Yabe Webfont plugin as Jooosi Fon and move product links to [fon.jooo.si](https://fon.jooo.si).
* Refresh the plugin's admin page
* Custom Fonts bulk upload now automatically detects the font family and variant from the uploaded file name
* Use `--jf--family-{font-slug}` for generated CSS custom properties while retaining `--ywf--family-{font-slug}` as a backward-compatible alias.
* Replace the Rosua EDD license updater with Easy Digital Downloads' official Software Licensing SDK while preserving existing license activations.
* Move legacy font uploads and generated cache files from `uploads/yabe-webfont` to `uploads/jooosi-fon` during the 2.x rebrand upgrade.
* Mark the temporary 2.x rebrand migrations and compatibility shims for complete removal in Jooosi Fon 3.0.0.
= 1.0.114 - 2026-07-28 =
**Fixed**
* Prevent header warnings when LifterLMS sends headers after Jooosi Fon frontend output.
**Changed**
* Use WordPress APIs to enqueue cached CSS, font preloads, and inline scripts.
= 1.0.100 - 2026-03-17 =
**Changed**
* Improve WordPress.org changelog formatting and keep release notes in sync across releases.
= 1.0.98 - 2026-02-05 =
**Added**
* [Etch](https://etchwp.com?aff=bce0d1ab) integration **[Pro]**. Type "ywf" on the Etch's CSS editor to see the font list.
**Changed**
* Test compatibility with WordPress 6.9
= 1.0.90 - 2025-11-10 =
**Added**
* Added opt-out settings to control Google Fonts disabling in page builders (Bricks, Elementor, Oxygen, Breakdance, Slider Revolution, FunnelKit) while maintaining GDPR compliance by default
* [Elementor] Added compatibility with Elementor v4 Atomic Widgets editor
= 1.0.78 - 2025-06-25 =
**Changed**
* [Breakdance] Ensure compatibility with Breakdance 2.5.0 and later
**Fixed**
* Multiple subsets for variable fonts are not loaded properly
= 1.0.75 - 2025-06-11 =
**Changed**
* Ensure compatibility with Bricks 2.0-beta and later
**Fixed**
* Duplicate import of Google Fonts variable font files
= 1.0.74 - 2025-06-11 =
**Added**
* Google Fonts data are now loaded through the local machine.
= 1.0.71 - 2025-03-30 =
**Changed**
* Remove the "[Jooosi Fon]" prefix/label from the font selection list [ticket#172]
* [Known issue] Compatibility issue with some browsers that doesn't allow to input custom font weight when adding/editing a font on the Jooosi Fon dashboard page [ticket#179]
* Update dependencies
= 1.0.70 - 2024-12-05 =
**Changed**
* Test compatibility with WordPress 6.7
* Update dependencies
= 1.0.69 - 2024-09-04 =
**Changed**
* Google Fonts' variable font subset is now loaded properly
= 1.0.67 - 2024-07-18 =
**Changed**
* Test compatibility with WordPress 6.6
* [Beaver Builder] Fallback font is now always defined
= 1.0.66 - 2024-04-30 =
**Changed**
* Plugin license activation process
= 1.0.65 - 2024-04-12 =
**Changed**
* Test compatibility with WordPress 6.4
= 1.0.64 - 2024-03-05 =
**Changed**
* Sort the font list by the font name in the visual builder's font picker.
* Freshen up the plugin's admin page UI.
= 1.0.63 - 2024-01-31 =
**Changed**
* Apply weight and width axes automatically for variable font (ttf/woff2) only if no existing file is found in the current variant.
= 1.0.62 - 2024-01-16 =
**Changed**
* Ensure compatibility with all Adobe Fonts embed approach
= 1.0.60 - 2023-12-15 =
**Changed**
* [Cwicly] Ensure compatibility with the latest Cwicly version.
= 1.0.59 - 2023-11-09 =
**Changed**
* Test compatibility with WordPress 6.4
= 1.0.58 - 2023-11-08 =
**Added**
* [Slider Revolution](https://www.sliderrevolution.com/) integration **[Pro]**
* [YellowPencil](https://yellowpencil.waspthemes.com/) integration **[Pro]**
= 1.0.57 - 2023-10-23 =
**Added**
* Added migration tool to import data from Dplugins Font Hero
* Added migration tool to import data from Bricks' Custom Fonts
= 1.0.54 - 2023-09-13 =
**Changed**
* [Builderius] Ensure compatibility with the latest Builderius version.
= 1.0.53 - 2023-09-12 =
**Changed**
* [Pinegrow] Pinegrow now available on the Free version.
= 1.0.51 - 2023-08-18 =
**Changed**
* [Gutenberg] Ensure compatibility with the latest Gutenberg version.
= 1.0.50 - 2023-08-17 =
**Added**
* Added option to disable Google Fonts API that loaded manually by the theme or plugin
**Changed**
* Ensure compatibility with WordPress 6.3 and later.
* [Builderius] Builderius now available on the Free version.
* [Gutenberg] Ensure compatibility with Twenty Twenty-Two theme.
= 1.0.49 - 2023-08-04 =
**Changed**
* The preload font files are now limited to `woff2` file format only.
= 1.0.48 - 2023-07-12 =
**Changed**
* Ensure the uploaded font files are now stored in the `wp-content/uploads/yabe-webfont` folder.
= 1.0.47 - 2023-06-30 =
**Added**
* Search Google Fonts by categories with syntax `:category name`. For example, `:handwriting` will return all fonts with the `handwriting` category and `:sans Open` will return all fonts with the `sans` category and the word `Open` in the font name.
* Search Google Fonts with extended syntax. Check out the [documentation](https://fusejs.io/examples.html#extended-search) for more information.
**Changed**
* Uploaded font files are now stored in the `wp-content/uploads/yabe-webfont` folder instead of the `wp-content/uploads/yyyy/mm` folder.
= 1.0.46 - 2023-06-28 =
**Changed**
* [GeneratePress] Ensure compatibility with GeneratePress
= 1.0.45 - 2023-06-27 =
**Fixed**
* Plugin not properly deployed
= 1.0.41 - 2023-06-23 =
**Added**
* [Blocksy](https://creativethemes.com/blocksy) integration **[Pro]**
= 1.0.40 - 2023-06-21 =
**Changed**
* [Bricks] Ensure compatibility with Bricks
= 1.0.39 - 2023-06-21 =
**Fixed**
* Plugin not properly deployed for PHP 7.4
= 1.0.37 - 2023-06-20 =
**Changed**
* [Pinegrow] Ensure compatibility with Pinegrow 1.0.11
* [Pinegrow] Remove version number from the font URL to avoid duplicate .css file link in the page source code.
**Fixed**
* Plugin i18n doesn't use string literal for the text domain.
= 1.0.34 - 2023-06-17 =
**Added**
* [Pinegrow](https://pinegrow.com/wordpress?ref=jooosi) integration **[Pro]**
= 1.0.32 - 2023-06-15 =
**Added**
* Jooosi Fon Lite is now available on [WordPress.org](https://wordpress.org/plugins/jooosi-fon/).
= 1.0.29 - 2023-06-07 =
**Changed**
* Move the Front page's CSS to higher priority to ensure the benefit from the preload feature is working properly.
= 1.0.28 - 2023-06-01 =
**Changed**
* [Breakdance] Ensure compatibility with Breakdance 1.2.1
= 1.0.27 - 2023-05-31 =
**Added**
* You no longer need to manually enter the license key, as it is now embedded in the plugin `.zip` file.
= 1.0.25 - 2023-05-31 =
**Fixed**
* [GeneratePress] Google Fonts not disabled properly
= 1.0.24 - 2023-05-30 =
**Added**
* The website has been redesigned, and the documentation is now available at [fon.jooo.si](https://fon.jooo.si)
* [FunnelKit/SlingBlocks](https://wordpress.org/plugins/slingblocks/) integration **[Pro]**
* [GeneratePress] GenerateBlocks 1.8.0 and later integration
**Changed**
* Performance optimization
* [Beaver Builder] Disable built-in Google Fonts programmatically
* [Breakdance] Ensure compatibility with Breakdance 1.3.0 and later
* [Cwicly] Register the font using the new font system introduced in Cwicly [1.2.9.5](https://discourse.cwicly.com/t/1-2-9-5/2563)
**Fixed**
* [Zion Builder] Font list not showing on the visual editor
= 1.0.23 - 2023-05-02 =
**Added**
* Export and import
**Changed**
* [Builderius] Ensure compatibility with Builderius 0.11.0 and later
= 1.0.22 - 2023-04-27 =
**Fixed**
* [Breakdance] CSS file loaded twice
= 1.0.21 - 2023-04-27 =
**Added**
* [Builderius](https://builderius.io/?referral=afdfca82c8) integration **[Pro]**
= 1.0.20 - 2023-04-26 =
**Added**
* [Spectra](https://wpspectra.com/) integration
* Search Google Fonts by category with the `:` prefix. For example, `:sans-serif` will search for all fonts in the sans-serif category
* CSS custom properties (variables) with pattern `--ywf--family-{font-slug}` for each family
* Allow to define fallback font
* [Breakdance] Fallback font support
* [Bricks] Fallback font support
* [Gutenberg] Fallback font support
= 1.0.19 - 2023-04-15 =
**Changed**
* The font files URL now is a relative path, ensure working between environments
**Fixed**
* [Gutenberg] Site Editor compatibility
= 1.0.18 - 2023-04-12 =
**Added**
* Adobe Fonts integration
**Changed**
* Database query optimization
= 1.0.17 - 2023-03-29 =
**Changed**
* [Bricks] Ensure compatibility with Bricks 1.7.1 and later
= 1.0.16 - 2023-03-14 =
**Changed**
* Regenerate the font file URL with the new attachment URL
* [Bricks] Font items on the Bricks editor are now grouped under the `Jooosi Fon` category
**Fixed**
* Import Google Fonts form is not resetting properly after a successful import
= 1.0.15 - 2023-03-12 =
**Added**
* Hide font files from Media Library
= 1.0.14 - 2023-03-11 =
**Changed**
* IIS server compatibility
= 1.0.13 - 2023-03-11 =
**Changed**
* Font' variants sort order
* IIS server compatibility
= 1.0.12 - 2023-03-11 =
**Added**
* Bulk file upload and auto-organize the font files to the matching variants
**Changed**
* Bulk select variants on the Google Fonts import page
**Fixed**
* The setting doesn't save properly on the plugin settings page
= 1.0.11 - 2023-03-06 =
**Added**
* [Kadence WP](https://kadencewp.com/?ref=jooosi) integration
= 1.0.10 - 2023-03-02 =
**Changed**
* Fix compatibility with the Blisk browser
= 1.0.9 - 2023-02-22 =
**Changed**
* [GeneratePress] Register fonts on the Theme Customize page
= 1.0.8 - 2023-02-22 =
**Added**
* [Divi](https://www.elegantthemes.com/affiliates/idevaffiliate.php?id=47622) integration **[Pro]**
= 1.0.7 - 2023-02-13 =
**Fixed**
* [Oxygen] Gutenberg editor compatibility
= 1.0.6 - 2023-02-10 =
**Added**
* Option of cache loading method, `file` or `inline`
**Changed**
* Preload the font files
= 1.0.5 - 2023-02-09 =
**Changed**
* Sync the cache generation
* Add submenu to all page builders integration
* [Bricks] Force disable the built-in Google Fonts and override the `Bricks > Settings > Performance: Disable Google Fonts` setting
* [Elementor] Force disable the built-in Google Fonts and override the `Elementor > Settings > Advanced: Google Fonts` setting
* [Gutenberg] Support non block-based theme
* [Oxygen] Force disable the built-in Google Fonts and override the `Oxygen > Settings > Bloat Eliminator: Disable Google Fonts` setting
**Fixed**
* Issue with the plugin upgrade for the upcoming version
* Revert the admin notices style to WordPress default
= 1.0.4 - 2023-01-30 =
**Added**
* [Greenshift](https://shop.greenshiftwp.com/?from=3679) integration **[Pro]**
**Changed**
* Better variable fonts support for Google Fonts
* Delete all fonts file associated with the deleted font
* [Oxygen] Disable Elegant Custom Fonts plugin
**Fixed**
* Scheduled cache generation not cleared properly on manual action
= 1.0.3 - 2023-01-27 =
**Added**
* [Breakdance](https://breakdance.com/ref/165/) integration **[Pro]**
**Fixed**
* [Gutenberg] Font CSS not loaded on the FSE editor
= 1.0.2 - 2023-01-25 =
**Changed**
* Tweak the plugin interface
* Support width axes for variable fonts
**Fixed**
* [Zion Builder] Font family list not showing up on the builder editor
= 1.0.1 - 2023-01-23 =
**Changed**
* Lower the minimum PHP version to 7.4
= 1.0.0 - 2023-01-23 =
**Added**
* Plugin rebuilt from scratch
* New plugin interface
* Custom fonts management
* Editable imported Google Fonts
* [Beaver Builder](https://www.wpbeaverbuilder.com/) integration **[Pro]**
* [Bricks](https://bricksbuilder.io/?ref=jooosi) integration **[Pro]**
* [Cwicly](https://cwicly.com/?ref=suabahasa) integration **[Pro]**
* [Classic Editor](https://wordpress.org/plugins/classic-editor/) integration
* [Elementor](https://be.elementor.com/visit/?bta=209150&brand=elementor) integration
* [GeneratePress](https://generatepress.com/?ref=7954) integration
* [Gutenberg](https://wordpress.org/gutenberg/?ref=jooosi) integration
* [Oxygen](https://oxygenbuilder.com/ref/12/) integration **[Pro]**
* [Zion Builder](https://zionbuilder.io/?ref=jooosi) integration **[Pro]**
**Changed**
* Plugin admin menu moved to `Appearance -> Jooosi Fon`
**Fixed**
* Some Google Fonts with variable fonts are not loaded properly
= 0.0.0 - 2022-11-10 =
**Added**
* Initial release.
[See changelog for all versions.](https://github.com/jooosi-project/jooosi-fon/blob/master/CHANGELOG.md)
@@ -0,0 +1,111 @@
<?php
/*
* This file is part of the Jooosi Fon package.
*
* (c) Joshua Gugun Siagian <suabahasa@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare (strict_types=1);
namespace JooosiFon\Admin;
use JooosiFonDeps\JOOOSI_FON;
use JooosiFon\Plugin;
use JooosiFon\Utils\Common;
use JooosiFon\Utils\Config;
use JooosiFon\Utils\Upload;
use JooosiFonDeps\Nabasa\VitePlus\Assets;
use WP_Query;
class AdminPage
{
public function __construct()
{
add_action('admin_init', fn() => $this->redirect_legacy_page());
add_filter('wp_check_filetype_and_ext', static fn($data, $file, $filename, $mimes) => Upload::disable_real_mime_check($data, $file, $filename, $mimes), 10, 4);
add_filter('upload_mimes', static fn($mime_types) => Upload::upload_mimes($mime_types), 1000001);
add_filter('upload_dir', fn($uploads) => $this->upload_dir($uploads), 1000001);
add_action('admin_menu', fn() => $this->add_admin_menu());
if (Config::get('misc.hide_media_library', \false)) {
add_filter('ajax_query_attachments_args', fn(array $query) => $this->ajax_query_attachments_args($query), 1000001);
add_action('load-upload.php', function () {
add_action('pre_get_posts', fn(WP_Query $wpQuery) => $this->load_upload_pre_get_posts($wpQuery), 1000001);
});
}
}
public static function get_page_url(): string
{
return add_query_arg(['page' => JOOOSI_FON::WP_OPTION], admin_url('admin.php'));
}
public static function redirect_to_page(): void
{
Common::redirect(self::get_page_url());
}
public static function add_redirect_submenu_page($root_slug)
{
add_submenu_page($root_slug, __('Jooosi Fon', 'jooosi-fon'), __('Jooosi Fon', 'jooosi-fon'), 'manage_options', 'jooosi-fon-builder-redirect', static fn() => self::redirect_to_page());
}
public function add_admin_menu()
{
$hook = add_menu_page(__('Jooosi Fon', 'jooosi-fon'), __('Jooosi Fon', 'jooosi-fon'), 'manage_options', JOOOSI_FON::WP_OPTION, fn() => $this->render(), 'data:image/svg+xml;base64,' . base64_encode(file_get_contents(dirname(JOOOSI_FON::FILE) . '/jooosi-fon.svg')), 100);
add_action('load-' . $hook, fn() => $this->init_hooks());
}
private function render()
{
add_filter('admin_footer_text', static fn($text) => 'Thank you for using <b>Jooosi Fon</b>! Join us on the <a href="https://www.facebook.com/groups/1142662969627943" target="_blank" rel="noopener noreferrer">Facebook Group</a>.', 1000001);
add_filter('update_footer', static fn($text) => $text . ' | Jooosi Fon ' . JOOOSI_FON::VERSION, 1000001);
echo '<div id="jooosi-fon-app" class=""></div>';
}
/**
* Keep old bookmarks and integration links working during the 2.x rebrand.
*
* @todo Remove this legacy admin-page redirect completely in Jooosi Fon 3.0.0.
*/
private function redirect_legacy_page(): void
{
if (!current_user_can('manage_options') || !isset($_GET['page']) || wp_unslash($_GET['page']) !== JOOOSI_FON::LEGACY_WP_OPTION) {
return;
}
Common::redirect(self::get_page_url(), \true);
}
private function init_hooks()
{
add_action('admin_head', static fn() => remove_action('admin_notices', 'update_nag', 3), 1);
add_action('admin_enqueue_scripts', fn() => $this->enqueue_scripts());
}
private function enqueue_scripts()
{
wp_enqueue_media();
$handle = JOOOSI_FON::WP_OPTION . ':app';
$assets = new Assets(dirname(JOOOSI_FON::FILE) . '/assets/dist', 'jooosi-fon');
$assets->enqueue('resources/main.tsx', ['handle' => $handle, 'dependencies' => ['wp-i18n'], 'in_footer' => \true]);
wp_set_script_translations($handle, 'jooosi-fon');
wp_localize_script($handle, 'jooosiFon', ['_version' => JOOOSI_FON::VERSION, '_wpnonce' => wp_create_nonce(JOOOSI_FON::WP_OPTION), 'option_namespace' => JOOOSI_FON::WP_OPTION, 'text_domain' => 'jooosi-fon', 'web_history' => self::get_page_url(), 'rest_api' => ['nonce' => wp_create_nonce('wp_rest'), 'root' => esc_url_raw(rest_url()), 'namespace' => JOOOSI_FON::REST_NAMESPACE, 'url' => esc_url_raw(rest_url(JOOOSI_FON::REST_NAMESPACE))], 'assets' => ['url' => $assets->url()], 'lite_edition' => !Plugin::is_pro_edition()]);
}
private function ajax_query_attachments_args(array $query): array
{
if ($query['post_type'] !== 'attachment') {
return $query;
}
if (!isset($_SERVER['HTTP_REFERER']) || strpos($_SERVER['HTTP_REFERER'], 'page=' . JOOOSI_FON::WP_OPTION) === \false) {
$all_mimes = get_allowed_mime_types();
$query['post_mime_type'] = $all_mimes;
}
return $query;
}
private function load_upload_pre_get_posts(WP_Query $wpQuery): void
{
if (!isset($_SERVER['HTTP_REFERER']) || strpos($_SERVER['HTTP_REFERER'], 'page=' . JOOOSI_FON::WP_OPTION) === \false) {
$all_mimes = get_allowed_mime_types();
$wpQuery->set('post_mime_type', $all_mimes);
}
}
private function upload_dir($uploads)
{
if (!isset($_POST['jooosi_fon_font_upload'])) {
return $uploads;
}
return Upload::font_upload_dir($uploads);
}
}
@@ -0,0 +1,31 @@
<?php
/*
* This file is part of the Jooosi Fon package.
*
* (c) Joshua Gugun Siagian <suabahasa@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare (strict_types=1);
namespace JooosiFon\Api;
use JooosiFonDeps\JOOOSI_FON;
use WP_REST_Request;
class AbstractApi
{
/**
* @var string
*/
public const API_NAMESPACE = JOOOSI_FON::REST_NAMESPACE;
/**
* The API is currently an administrator-only surface used by the plugin's
* wp-admin application. Keep both checks explicit so custom authentication
* integrations cannot accidentally bypass the CSRF boundary.
*/
protected function permission_callback(WP_REST_Request $request): bool
{
return wp_verify_nonce($request->get_header('X-WP-Nonce'), 'wp_rest') && current_user_can('manage_options');
}
}
@@ -0,0 +1,26 @@
<?php
/*
* This file is part of the Jooosi Fon package.
*
* (c) Joshua Gugun Siagian <suabahasa@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare (strict_types=1);
namespace JooosiFon\Api;
interface ApiInterface
{
/**
* Get the API endpoint prefix.
*/
public function get_prefix(): string;
/**
* Register custom REST API endpoints as described in the [WordPress REST API Handbook](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/).
*
* @see https://developer.wordpress.org/reference/functions/register_rest_route/
*/
public function register_custom_endpoints(): void;
}
@@ -0,0 +1,894 @@
<?php
/*
* This file is part of the Jooosi Fon package.
*
* (c) Joshua Gugun Siagian <suabahasa@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare (strict_types=1);
namespace JooosiFon\Api;
use JooosiFonDeps\JOOOSI_FON;
use JooosiFon\Api\Support\FontCodec;
use JooosiFon\Api\Support\FontEvents;
use JooosiFon\Api\Support\FontRepository;
use JooosiFon\Api\Support\GoogleFontFileSelector;
use JooosiFon\Api\Support\GoogleFontsClient;
use JooosiFon\Api\Support\MediaImportService;
use JooosiFon\Api\Support\RequestValidator;
use JooosiFon\Builder\Integration;
use JooosiFon\Core\Cache;
use JooosiFon\Utils\Common;
use JooosiFon\Utils\Config;
use JooosiFon\Utils\Upload;
use JooosiFonDeps\Sabberworm\CSS\Parser;
use stdClass;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;
use wpdb;
/**
* @todo Remove all legacy Yabe Webfont filter shims completely in Jooosi Fon 3.0.0.
*/
class Font extends \JooosiFon\Api\AbstractApi implements \JooosiFon\Api\ApiInterface
{
public function __construct()
{
}
public function get_prefix(): string
{
return 'fonts';
}
public function register_custom_endpoints(): void
{
$id_args = ['id' => ['required' => \true, 'sanitize_callback' => 'absint', 'validate_callback' => [RequestValidator::class, 'positiveInteger']]];
$custom_font_args = ['title' => ['required' => \true, 'sanitize_callback' => 'sanitize_text_field', 'validate_callback' => [RequestValidator::class, 'nonEmptyString']], 'family' => ['required' => \true, 'sanitize_callback' => 'sanitize_text_field', 'validate_callback' => [RequestValidator::class, 'nonEmptyString']], 'status' => ['required' => \true, 'sanitize_callback' => 'rest_sanitize_boolean', 'validate_callback' => [RequestValidator::class, 'boolean']], 'metadata' => ['required' => \true, 'validate_callback' => [RequestValidator::class, 'arrayValue']], 'font_faces' => ['required' => \true, 'sanitize_callback' => [RequestValidator::class, 'sanitizeFontFaces'], 'validate_callback' => [RequestValidator::class, 'fontFaces']]];
$google_font_args = ['title' => $custom_font_args['title'], 'status' => $custom_font_args['status'], 'metadata' => ['required' => \true, 'validate_callback' => [RequestValidator::class, 'googleMetadata']]];
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/index', ['methods' => WP_REST_Server::READABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->index($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest), 'args' => ['page' => ['default' => 1, 'sanitize_callback' => 'absint', 'validate_callback' => [RequestValidator::class, 'positiveInteger']], 'per_page' => ['default' => 20, 'sanitize_callback' => 'absint', 'validate_callback' => [RequestValidator::class, 'pageSize']], 'search' => ['default' => '', 'sanitize_callback' => 'sanitize_text_field'], 'soft_deleted' => ['default' => \false, 'sanitize_callback' => 'rest_sanitize_boolean', 'validate_callback' => [RequestValidator::class, 'boolean']]]]);
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/custom/store', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->custom_store($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest), 'args' => $custom_font_args]);
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/update-status/(?P<id>\d+)', ['methods' => WP_REST_Server::EDITABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->update_status($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest), 'args' => array_merge($id_args, ['status' => ['required' => \true, 'sanitize_callback' => 'rest_sanitize_boolean', 'validate_callback' => [RequestValidator::class, 'boolean']]])]);
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/delete/(?P<id>\d+)', ['methods' => 'POST, DELETE', 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->destroy($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest), 'args' => $id_args]);
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/restore/(?P<id>\d+)', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->restore($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest), 'args' => $id_args]);
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/export', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->export($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest), 'args' => ['items' => ['required' => \true, 'validate_callback' => [RequestValidator::class, 'positiveIntegerList'], 'sanitize_callback' => static fn($items): array => array_values(array_unique(array_map('absint', $items)))]]]);
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/import', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->import($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest), 'args' => ['site_url' => ['required' => \true, 'sanitize_callback' => 'esc_url_raw', 'validate_callback' => 'wp_http_validate_url'], 'version' => ['required' => \true, 'sanitize_callback' => 'sanitize_text_field', 'validate_callback' => [RequestValidator::class, 'nonEmptyString']], 'is_bundled' => ['required' => \true, 'sanitize_callback' => 'rest_sanitize_boolean', 'validate_callback' => [RequestValidator::class, 'boolean']], 'item' => ['required' => \true, 'validate_callback' => [RequestValidator::class, 'importItem']]]]);
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/detail/(?P<id>\d+)', ['methods' => WP_REST_Server::READABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->detail($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest), 'args' => $id_args]);
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/custom/update/(?P<id>\d+)', ['methods' => WP_REST_Server::EDITABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->custom_update($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest), 'args' => array_merge($id_args, $custom_font_args)]);
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/google-fonts/store', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->google_fonts_store($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest), 'args' => $google_font_args]);
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/google-fonts/update/(?P<id>\d+)', ['methods' => WP_REST_Server::EDITABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->google_fonts_update($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest), 'args' => array_merge($id_args, $google_font_args)]);
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/google-fonts/metadata', ['methods' => WP_REST_Server::READABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->google_fonts_metadata($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest), 'args' => ['force' => ['default' => \false, 'sanitize_callback' => 'rest_sanitize_boolean', 'validate_callback' => [RequestValidator::class, 'boolean']]]]);
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/google-fonts/webfonts/(?P<slug>[a-zA-Z0-9_\-+\.]+)', ['methods' => WP_REST_Server::READABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->google_fonts_webfonts($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest), 'args' => ['slug' => ['required' => \true, 'sanitize_callback' => 'sanitize_key', 'validate_callback' => [RequestValidator::class, 'nonEmptyString']], 'subsets' => ['default' => '', 'sanitize_callback' => 'sanitize_text_field', 'validate_callback' => [RequestValidator::class, 'subsets']]]]);
}
private function index(WP_REST_Request $wprestRequest): WP_REST_Response
{
/** @var wpdb $wpdb */
global $wpdb;
$soft_deleted = rest_sanitize_boolean($wprestRequest->get_param('soft_deleted'));
$page = max(1, (int) $wprestRequest->get_param('page'));
$per_page = min(100, max(1, (int) $wprestRequest->get_param('per_page')));
$offset = $page * $per_page - $per_page;
$search = trim((string) $wprestRequest->get_param('search'));
$search = $search !== '' ? $search : null;
$items = [];
$where_clause = [];
if ($search) {
$escaped_search = '%' . $wpdb->esc_like($search) . '%';
$where_clause[] = $wpdb->prepare("( title LIKE '%1\$s' OR family LIKE '%1\$s' )", $escaped_search);
}
$where_clause[] = $soft_deleted ? 'deleted_at IS NOT NULL' : 'deleted_at IS NULL';
$where_clause = 'WHERE ' . implode(' AND ', $where_clause);
$sql = "\n SELECT * FROM {$wpdb->prefix}jooosi_fon_fonts\n {$where_clause}\n ORDER BY id DESC\n LIMIT %d OFFSET %d\n ";
$sql = $wpdb->prepare($sql, $per_page, $offset);
$result = $wpdb->get_results($sql);
foreach ($result as $row) {
$metadata = FontCodec::decode((string) $row->metadata);
$font_faces = FontCodec::decode((string) $row->font_faces);
$items[] = ['id' => $row->id, 'type' => $row->type, 'title' => $row->title, 'slug' => $row->slug, 'family' => $row->family, 'metadata' => $metadata, 'font_faces' => Upload::refresh_font_faces_attachment_url($font_faces), 'status' => (bool) $row->status, 'created_at' => strtotime($row->created_at), 'updated_at' => strtotime($row->updated_at), 'deleted_at' => $row->deleted_at ? strtotime($row->deleted_at) : null];
}
$totals = $wpdb->get_row("\n SELECT\n SUM(CASE WHEN deleted_at IS NULL THEN 1 ELSE 0 END) AS total_exists,\n SUM(CASE WHEN status = 1 AND deleted_at IS NULL THEN 1 ELSE 0 END) AS total_active,\n SUM(CASE WHEN type = 'adobe-fonts' AND deleted_at IS NULL THEN 1 ELSE 0 END) AS total_adobe_fonts,\n SUM(CASE WHEN deleted_at IS NOT NULL THEN 1 ELSE 0 END) AS total_deleted\n FROM {$wpdb->prefix}jooosi_fon_fonts\n ");
$total_exists = (int) ($totals->total_exists ?? 0);
$total_active = (int) ($totals->total_active ?? 0);
$total_adobe_fonts = (int) ($totals->total_adobe_fonts ?? 0);
$total_deleted = (int) ($totals->total_deleted ?? 0);
$total_filtered = (int) $wpdb->get_var("\n SELECT COUNT(*) FROM {$wpdb->prefix}jooosi_fon_fonts\n {$where_clause}\n ");
$total_pages = (int) ceil($total_filtered / $per_page);
$from = $items !== [] ? ($page - 1) * $per_page + 1 : null;
$to = $items !== [] ? $from + count($items) - 1 : null;
return new WP_REST_Response(['data' => $items, 'meta' => ['page' => $page, 'per_page' => $per_page, 'search' => $search, 'total_pages' => $total_pages, 'from' => $from, 'to' => $to, 'total_filtered' => $total_filtered, 'total_deleted' => $total_deleted, 'total_exists' => $total_exists, 'infrastructure' => ['google_fonts' => $this->get_google_fonts_catalog_stats(), 'active_fonts' => ['total' => $total_active], 'adobe_fonts' => ['active' => trim((string) Config::get('adobe_fonts.project_id', '')) !== '', 'total' => $total_adobe_fonts], 'integrations' => ['total' => Integration::get_registered_count()]]]], 200, ['X-WP-Total' => $total_filtered, 'X-WP-TotalPages' => $total_pages]);
}
/**
* @return array{total: int, cache_updated_at: int|null}
*/
private function get_google_fonts_catalog_stats(): array
{
$cache_path = Cache::get_cache_path('webfonts.json');
$has_cache = file_exists($cache_path) && is_readable($cache_path);
$source_path = $has_cache ? $cache_path : dirname(JOOOSI_FON::FILE) . '/google-fonts.json';
$source_updated_at = is_readable($source_path) ? filemtime($source_path) : \false;
$source_updated_at = is_int($source_updated_at) ? $source_updated_at : null;
$cache_updated_at = $has_cache ? $source_updated_at : null;
$transient_key = 'jooosi_fon_google_fonts_catalog_stats';
$cached = get_transient($transient_key);
if (is_array($cached) && ($cached['source_path'] ?? null) === $source_path && ($cached['source_updated_at'] ?? null) === $source_updated_at) {
return ['total' => (int) ($cached['total'] ?? 0), 'cache_updated_at' => $cache_updated_at];
}
$total = 0;
if (is_readable($source_path)) {
try {
$catalog = json_decode(file_get_contents($source_path), \true, 512, \JSON_THROW_ON_ERROR);
$total = is_array($catalog) ? count($catalog) : 0;
} catch (\JsonException $e) {
$total = 0;
}
}
set_transient($transient_key, ['source_path' => $source_path, 'source_updated_at' => $source_updated_at, 'total' => $total], \DAY_IN_SECONDS);
return ['total' => $total, 'cache_updated_at' => $cache_updated_at];
}
private function detail(WP_REST_Request $wprestRequest): WP_REST_Response
{
/** @var wpdb $wpdb */
global $wpdb;
$url_params = $wprestRequest->get_url_params();
$id = (int) $url_params['id'];
$sql = "\n SELECT * FROM {$wpdb->prefix}jooosi_fon_fonts\n WHERE id = %d\n ";
$sql = $wpdb->prepare($sql, $id);
$row = $wpdb->get_row($sql);
if (!$row) {
return new WP_REST_Response(['message' => 'Font not found'], 404, []);
}
$metadata = FontCodec::decode((string) $row->metadata);
$font_faces = FontCodec::decode((string) $row->font_faces);
$payload = ['id' => $row->id, 'type' => $row->type, 'title' => $row->title, 'slug' => $row->slug, 'family' => $row->family, 'metadata' => $metadata, 'font_faces' => Upload::refresh_font_faces_attachment_url($font_faces), 'status' => (bool) $row->status, 'created_at' => strtotime($row->created_at), 'updated_at' => strtotime($row->updated_at), 'deleted_at' => $row->deleted_at ? strtotime($row->deleted_at) : null];
if (is_object($payload['metadata']) && property_exists($payload['metadata'], 'google_fonts')) {
$payload['metadata']->google_fonts->font_files = Upload::refresh_google_fonts_attachment_url($payload['metadata']->google_fonts->font_files);
}
return new WP_REST_Response($payload, 200, []);
}
private function custom_store(WP_REST_Request $wprestRequest): WP_REST_Response
{
try {
$repository = new FontRepository();
$id = $repository->insert(['type' => 'custom', 'title' => (string) $wprestRequest->get_param('title'), 'slug' => Common::random_slug(10), 'family' => (string) $wprestRequest->get_param('family'), 'status' => rest_sanitize_boolean($wprestRequest->get_param('status')), 'metadata' => FontCodec::encode((array) $wprestRequest->get_param('metadata')), 'font_faces' => FontCodec::encode((array) $wprestRequest->get_param('font_faces'))], ['%s', '%s', '%s', '%s', '%d', '%s', '%s']);
} catch (\Throwable $throwable) {
return $this->operation_error($throwable, __('Unable to create the font.', 'jooosi-fon'));
}
FontEvents::dispatch('custom_store', $id);
return new WP_REST_Response(['id' => $id], 200, []);
}
private function update_status(WP_REST_Request $wprestRequest): WP_REST_Response
{
$id = (int) $wprestRequest->get_param('id');
$status = rest_sanitize_boolean($wprestRequest->get_param('status'));
$repository = new FontRepository();
if (!$repository->find($id)) {
return new WP_REST_Response(['message' => __('Font not found', 'jooosi-fon')], 404, []);
}
try {
$repository->update($id, ['status' => $status], ['%d']);
} catch (\Throwable $throwable) {
return $this->operation_error($throwable, __('Unable to update the font status.', 'jooosi-fon'));
}
FontEvents::dispatch('update_status', $id);
return new WP_REST_Response(['id' => $id, 'status' => $status], 200, []);
}
private function destroy(WP_REST_Request $wprestRequest): WP_REST_Response
{
$id = (int) $wprestRequest->get_param('id');
$repository = new FontRepository();
$item = $repository->find($id);
if (!$item) {
return new WP_REST_Response(['message' => __('Font not found', 'jooosi-fon')], 404, []);
}
try {
if ($item->deleted_at) {
$fontFaces = FontCodec::decode((string) $item->font_faces);
$attachmentIds = MediaImportService::attachmentIds($fontFaces);
$repository->delete($id);
MediaImportService::deleteAttachments($attachmentIds);
} else {
$repository->update($id, ['deleted_at' => current_time('mysql')], ['%s']);
}
} catch (\Throwable $throwable) {
return $this->operation_error($throwable, __('Unable to delete the font.', 'jooosi-fon'));
}
FontEvents::dispatch('destroy', $item);
return new WP_REST_Response(null, 200, []);
}
private function restore(WP_REST_Request $wprestRequest): WP_REST_Response
{
$id = (int) $wprestRequest->get_param('id');
$repository = new FontRepository();
if (!$repository->find($id)) {
return new WP_REST_Response(['message' => __('Font not found', 'jooosi-fon')], 404, []);
}
try {
$repository->update($id, ['deleted_at' => null], ['%s']);
} catch (\Throwable $throwable) {
return $this->operation_error($throwable, __('Unable to restore the font.', 'jooosi-fon'));
}
FontEvents::dispatch('restore', $id);
return new WP_REST_Response(['id' => $id], 200, []);
}
private function custom_update(WP_REST_Request $wprestRequest): WP_REST_Response
{
$id = (int) $wprestRequest->get_param('id');
$repository = new FontRepository();
$existing = $repository->findOfType($id, 'custom');
if (!$existing) {
return new WP_REST_Response(['message' => __('Font not found', 'jooosi-fon')], 404, []);
}
$fontFaces = (array) $wprestRequest->get_param('font_faces');
try {
$oldAttachmentIds = MediaImportService::attachmentIds(FontCodec::decode((string) $existing->font_faces));
$newAttachmentIds = MediaImportService::attachmentIds($fontFaces);
$repository->update($id, ['title' => (string) $wprestRequest->get_param('title'), 'family' => (string) $wprestRequest->get_param('family'), 'status' => rest_sanitize_boolean($wprestRequest->get_param('status')), 'metadata' => FontCodec::encode((array) $wprestRequest->get_param('metadata')), 'font_faces' => FontCodec::encode($fontFaces)], ['%s', '%s', '%d', '%s', '%s']);
MediaImportService::deleteAttachments(array_diff($oldAttachmentIds, $newAttachmentIds));
} catch (\Throwable $throwable) {
return $this->operation_error($throwable, __('Unable to update the font.', 'jooosi-fon'));
}
FontEvents::dispatch('custom_update', $id);
return new WP_REST_Response(['id' => $id], 200, []);
}
private function google_fonts_store(WP_REST_Request $wprestRequest): WP_REST_Response
{
$payload = $wprestRequest->get_json_params();
$media = new MediaImportService();
$type = 'google-fonts';
$title = sanitize_text_field($payload['title']);
$slug = Common::random_slug(10);
$status = (bool) $payload['status'];
$metadata = $payload['metadata'];
$family = $metadata['google_fonts']['font_data']['family'];
$font_faces = [];
add_filter('wp_check_filetype_and_ext', static fn($data, $file, $filename, $mimes) => Upload::disable_real_mime_check($data, $file, $filename, $mimes), 10, 4);
add_filter('upload_mimes', static fn($mime_types) => Upload::upload_mimes($mime_types, \true), 1000001);
$m_font_faces = $metadata['google_fonts']['font_faces'];
$m_font_files = $metadata['google_fonts']['font_files'];
foreach ($m_font_faces as $k => $m_face) {
if (!$m_face['isEnabled']) {
continue;
}
if ($metadata['google_fonts']['variable']) {
if ($m_face['weight'] !== 0) {
continue;
}
$all_filtered_m_font_files = GoogleFontFileSelector::variableFiles($m_font_files, $m_face, $metadata['google_fonts']['subsets'], $metadata['google_fonts']['formats']);
foreach ($all_filtered_m_font_files as $filtered_m_font_file) {
$wght = array_filter($metadata['google_fonts']['font_data']['axes'], static fn($a) => $a['tag'] === 'wght');
$wdth = array_filter($metadata['google_fonts']['font_data']['axes'], static fn($a) => $a['tag'] === 'wdth');
$slnt = array_filter($metadata['google_fonts']['font_data']['axes'], static fn($a) => $a['tag'] === 'slnt');
$wdth = array_values($wdth);
$wght = array_values($wght);
$slnt = array_values($slnt);
$font_face = ['id' => Common::random_slug(10), 'weight' => $wght !== [] ? sprintf('%s %s', $wght[0]['min'], $wght[0]['max']) : '400', 'width' => $wdth !== [] ? sprintf('%s%% %s%%', $wdth[0]['min'], $wdth[0]['max']) : '100%', 'style' => $slnt !== [] ? sprintf('oblique %sdeg %sdeg', $slnt[0]['max'] * -1, $slnt[0]['min'] * -1) : $m_face['style'], 'display' => $m_face['display'], 'selector' => $m_face['selector'], 'comment' => $m_face['comment'], 'preload' => $m_face['preload']];
$file_name = sanitize_title_with_dashes(sprintf(
'google-fonts-%s-%s-%s-var-%s-%s',
$metadata['google_fonts']['font_data']['slug'],
// family
$metadata['google_fonts']['font_data']['version'] ?? 'latest',
implode('_', $filtered_m_font_file['subsets']),
Common::random_slug(5),
time()
)) . '.' . $filtered_m_font_file['format'];
try {
$file = $media->remote($filtered_m_font_file['url'], $file_name, $filtered_m_font_file['format'], ['fonts.gstatic.com']);
} catch (\Throwable $throwable) {
$media->rollback();
return $this->operation_error($throwable, __('Unable to download the Google font files.', 'jooosi-fon'));
}
$metadata['google_fonts']['font_files'] = array_map(static fn($f) => $f['uid'] === $filtered_m_font_file['uid'] ? array_merge($f, ['file' => $file]) : $f, $metadata['google_fonts']['font_files']);
$metadata['google_fonts']['font_faces'][$k]['attached_font_files'][] = $filtered_m_font_file['uid'];
$font_face['files'] = [$file];
$font_face['unicodeRange'] = $filtered_m_font_file['unicodeRange'] ?? '';
$font_faces[] = $font_face;
}
} else {
if ($m_face['weight'] === 0) {
continue;
}
$font_face = ['id' => Common::random_slug(10), 'weight' => $m_face['weight'], 'width' => $m_face['width'] ?: '100%', 'style' => $m_face['style'], 'display' => $m_face['display'], 'selector' => $m_face['selector'], 'comment' => $m_face['comment'], 'unicodeRange' => '', 'preload' => $m_face['preload']];
$files = [];
$filtered_m_font_files = array_filter($m_font_files, static fn($f) => $f['weight'] === $m_face['weight'] && $f['style'] === $m_face['style'] && array_diff($metadata['google_fonts']['subsets'], $f['subsets']) === array_diff($f['subsets'], $metadata['google_fonts']['subsets']) && in_array($f['format'], $metadata['google_fonts']['formats'], \true));
$format_precedence = ['woff2' => 1, 'woff' => 2, 'ttf' => 3, 'otf' => 4, 'eot' => 5];
usort($filtered_m_font_files, static fn($a, $b) => $format_precedence[$a['format']] <=> $format_precedence[$b['format']]);
foreach ($filtered_m_font_files as $filtered_m_font_file) {
$file_name = sanitize_title_with_dashes(sprintf(
'google-fonts-%s-%s-%s-%s-%s-%s',
$metadata['google_fonts']['font_data']['slug'],
// family
$metadata['google_fonts']['font_data']['version'] ?? 'latest',
implode('-', $metadata['google_fonts']['subsets']),
$filtered_m_font_file['weight'],
$filtered_m_font_file['style'],
time()
)) . '.' . $filtered_m_font_file['format'];
try {
$file = $media->remote($filtered_m_font_file['url'], $file_name, $filtered_m_font_file['format'], ['fonts.gstatic.com']);
} catch (\Throwable $throwable) {
$media->rollback();
return $this->operation_error($throwable, __('Unable to download the Google font files.', 'jooosi-fon'));
}
$metadata['google_fonts']['font_files'] = array_map(static fn($f) => $f['uid'] === $filtered_m_font_file['uid'] ? array_merge($f, ['file' => $file]) : $f, $metadata['google_fonts']['font_files']);
$metadata['google_fonts']['font_faces'][$k]['attached_font_files'][] = $filtered_m_font_file['uid'];
$files[] = $file;
}
$font_face['files'] = $files;
$font_faces[] = $font_face;
}
}
try {
$repository = new FontRepository();
$id = $repository->insert(['type' => $type, 'title' => $title, 'slug' => $slug, 'family' => $family, 'status' => $status, 'metadata' => FontCodec::encode($metadata), 'font_faces' => FontCodec::encode($font_faces)], ['%s', '%s', '%s', '%s', '%d', '%s', '%s']);
$media->commit();
} catch (\Throwable $throwable) {
$media->rollback();
return $this->operation_error($throwable, __('Unable to create the Google font.', 'jooosi-fon'));
}
FontEvents::dispatch('google_fonts_store', $id);
return new WP_REST_Response(['id' => $id], 200, []);
}
private function google_fonts_update(WP_REST_Request $wprestRequest): WP_REST_Response
{
$payload = $wprestRequest->get_json_params();
$id = (int) $wprestRequest->get_param('id');
$repository = new FontRepository();
$existing = $repository->findOfType($id, 'google-fonts');
if (!$existing) {
return new WP_REST_Response(['message' => __('Font not found', 'jooosi-fon')], 404, []);
}
$title = sanitize_text_field($payload['title']);
$status = (bool) $payload['status'];
$metadata = $payload['metadata'];
$font_faces = [];
add_filter('wp_check_filetype_and_ext', static fn($data, $file, $filename, $mimes) => Upload::disable_real_mime_check($data, $file, $filename, $mimes), 10, 4);
add_filter('upload_mimes', static fn($mime_types) => Upload::upload_mimes($mime_types, \true), 1000001);
$media = new MediaImportService();
try {
$oldAttachmentIds = MediaImportService::attachmentIds(FontCodec::decode((string) $existing->font_faces));
$this->google_fonts_update_filter($metadata, $font_faces, $media);
$newAttachmentIds = MediaImportService::attachmentIds($font_faces);
$repository->update($id, ['title' => $title, 'status' => $status, 'metadata' => FontCodec::encode($metadata), 'font_faces' => FontCodec::encode($font_faces)], ['%s', '%d', '%s', '%s']);
$media->commit();
MediaImportService::deleteAttachments(array_diff($oldAttachmentIds, $newAttachmentIds));
} catch (\Throwable $throwable) {
$media->rollback();
return $this->operation_error($throwable, __('Unable to update the Google font.', 'jooosi-fon'));
}
FontEvents::dispatch('google_fonts_update', $id);
return new WP_REST_Response(['id' => $id], 200, []);
}
private function export(WP_REST_Request $wprestRequest): WP_REST_Response
{
/** @var wpdb $wpdb */
global $wpdb;
$params = $wprestRequest->get_json_params();
$items = $params['items'];
if (!is_array($items) || $items === []) {
return new WP_REST_Response(['message' => 'No items to export'], 400, []);
}
$is_bundled = Config::get('misc.export_bundle_binary', \false);
$placeholder = implode(',', array_fill(0, count($items), '%d'));
$sql = "\n SELECT * FROM {$wpdb->prefix}jooosi_fon_fonts\n WHERE id IN ({$placeholder})\n ";
$sql = $wpdb->prepare($sql, $items);
$rows = $wpdb->get_results($sql);
$items = [];
$bundledBytes = 0;
foreach ($rows as $row) {
$font_faces = FontCodec::decode((string) $row->font_faces);
$metadata = FontCodec::decode((string) $row->metadata);
if ($row->type === 'adobe-fonts') {
continue;
} elseif ($row->type === 'custom') {
foreach ($font_faces as $i => $font_face) {
foreach ($font_face->files as $j => $file) {
// bundle binary and encode it to base64 if enabled
if ($is_bundled) {
$file_path = get_attached_file($file->attachment_id);
if ($file_path) {
$fileSize = filesize($file_path);
if (!is_int($fileSize) || $fileSize < 1) {
return new WP_REST_Response(['message' => __('A font attachment is missing or unreadable.', 'jooosi-fon')], 409);
}
$bundledBytes += $fileSize;
if ($bundledBytes > 50 * \MB_IN_BYTES) {
return new WP_REST_Response(['message' => __('The bundled export exceeds the 50 MB limit. Export fewer fonts or disable bundled binaries.', 'jooosi-fon')], 413);
}
$binary = file_get_contents($file_path);
if (!is_string($binary)) {
return new WP_REST_Response(['message' => __('A font attachment could not be read.', 'jooosi-fon')], 409);
}
$font_faces[$i]->files[$j]->binary = base64_encode($binary);
} else {
return new WP_REST_Response(['message' => __('A font attachment is missing or unreadable.', 'jooosi-fon')], 409);
}
unset($font_faces[$i]->files[$j]->attachment_url);
} else {
$attachment_url = wp_get_attachment_url($file->attachment_id);
if ($attachment_url) {
$parsed = parse_url($attachment_url);
$font_faces[$i]->files[$j]->attachment_url = $parsed['path'];
}
}
unset($font_faces[$i]->files[$j]->attachment_id);
}
}
} elseif ($row->type === 'google-fonts') {
// minimize metadata
$font_faces = [];
if (property_exists($metadata, 'google_fonts')) {
foreach ($metadata->google_fonts->font_files as $i => $font_file) {
if (property_exists($font_file, 'file')) {
unset($metadata->google_fonts->font_files[$i]->file);
}
}
foreach ($metadata->google_fonts->font_faces as $i => $font_face) {
if (property_exists($font_face, 'attached_font_files')) {
unset($metadata->google_fonts->font_faces[$i]->attached_font_files);
}
}
}
}
$item = ['type' => $row->type, 'title' => $row->title, 'slug' => $row->slug, 'family' => $row->family];
$item['font_faces'] = base64_encode(json_encode($font_faces, \JSON_THROW_ON_ERROR));
$item['metadata'] = base64_encode(json_encode($metadata, \JSON_THROW_ON_ERROR));
$items[] = $item;
}
$data = ['module_id' => JOOOSI_FON::WP_OPTION, 'version' => JOOOSI_FON::VERSION, 'export_time' => time(), 'site_url' => site_url(), 'is_bundled' => $is_bundled, 'items' => $items];
return new WP_REST_Response(['data' => $data], 200);
}
private function import(WP_REST_Request $wprestRequest): WP_REST_Response
{
$params = $wprestRequest->get_json_params();
$site_url = $params['site_url'];
$is_bundled = rest_sanitize_boolean($params['is_bundled']);
$item = $params['item'];
$type = $item['type'];
$title = sanitize_text_field($item['title']);
$slug = Common::random_slug(10);
$family = sanitize_text_field($item['family']);
$status = \true;
try {
$encodedFontFaces = base64_decode($item['font_faces'], \true);
$encodedMetadata = base64_decode($item['metadata'], \true);
if (!is_string($encodedFontFaces) || !is_string($encodedMetadata)) {
throw new \UnexpectedValueException('The import payload is not valid base64.');
}
$font_faces = json_decode($encodedFontFaces, \false, 512, \JSON_THROW_ON_ERROR);
$metadata = json_decode($encodedMetadata, \false, 512, \JSON_THROW_ON_ERROR);
} catch (\Throwable $throwable) {
return $this->operation_error($throwable, __('The font import payload is invalid.', 'jooosi-fon'), 400);
}
add_filter('wp_check_filetype_and_ext', static fn($data, $file, $filename, $mimes) => Upload::disable_real_mime_check($data, $file, $filename, $mimes), 10, 4);
add_filter('upload_mimes', static fn($mime_types) => Upload::upload_mimes($mime_types, \true), 1000001);
$media = new MediaImportService();
if ($item['type'] === 'adobe-fonts') {
return new WP_REST_Response(['message' => 'Adobe Fonts is not importable'], 400, []);
} elseif ($item['type'] === 'google-fonts') {
$font_faces = json_decode($encodedFontFaces, \true, 512, \JSON_THROW_ON_ERROR);
$metadata = json_decode($encodedMetadata, \true, 512, \JSON_THROW_ON_ERROR);
try {
$this->google_fonts_update_filter($metadata, $font_faces, $media);
} catch (\Throwable $throwable) {
$media->rollback();
return $this->operation_error($throwable, __('Unable to download the Google font files.', 'jooosi-fon'));
}
} elseif ($item['type'] === 'custom') {
try {
$sourceHost = (string) wp_parse_url($site_url, \PHP_URL_HOST);
foreach ($font_faces as $i => $font_face) {
foreach ($font_face->files as $j => $file) {
// if not first-hand
$font_faces[$i]->files[$j]->name = preg_replace('#\-[\_\-a-zA-Z0-9]{5}\-\d{10}$#', '', $file->name);
// if explicit using a Google Fonts file
$font_faces[$i]->files[$j]->name = preg_replace('#\-\d{10}\-(woff2|woff|ttf)$#', '', $file->name);
$file_name = sanitize_title_with_dashes(sprintf('%s-%s-%s', $font_faces[$i]->files[$j]->name, Common::random_slug(5), time())) . '.' . $file->extension;
if ($is_bundled) {
$binary = base64_decode((string) ($file->binary ?? ''), \true);
if (!is_string($binary) || strlen($binary) > 20 * \MB_IN_BYTES) {
throw new \UnexpectedValueException('The bundled font file is invalid or exceeds 20 MB.');
}
$attachment = $media->binary($binary, $file_name, (string) $file->extension);
unset($font_faces[$i]->files[$j]->binary);
} else {
$attachmentPath = (string) ($file->attachment_url ?? '');
if ($attachmentPath === '' || $attachmentPath[0] !== '/' || wp_parse_url($attachmentPath, \PHP_URL_HOST) !== null) {
throw new \UnexpectedValueException('The imported attachment path is invalid.');
}
$attachment = $media->remote(untrailingslashit($site_url) . $attachmentPath, $file_name, (string) $file->extension, [$sourceHost]);
}
foreach ($attachment as $key => $value) {
$font_faces[$i]->files[$j]->{$key} = $value;
}
}
}
} catch (\Throwable $throwable) {
$media->rollback();
return $this->operation_error($throwable, __('Unable to import the custom font files.', 'jooosi-fon'));
}
} else {
return new WP_REST_Response(['message' => 'Invalid item type'], 400, []);
}
try {
$repository = new FontRepository();
$id = $repository->insert(['type' => $type, 'title' => $title, 'slug' => $slug, 'family' => $family, 'status' => $status, 'metadata' => FontCodec::encode($metadata), 'font_faces' => FontCodec::encode($font_faces)], ['%s', '%s', '%s', '%s', '%d', '%s', '%s']);
$media->commit();
} catch (\Throwable $throwable) {
$media->rollback();
return $this->operation_error($throwable, __('Unable to create the imported font.', 'jooosi-fon'));
}
FontEvents::dispatch('import', $id);
return new WP_REST_Response(['id' => $id], 200, []);
}
private function google_fonts_update_filter(&$metadata, &$font_faces, MediaImportService $media): void
{
$m_font_faces = $metadata['google_fonts']['font_faces'];
$m_font_files = $metadata['google_fonts']['font_files'];
foreach ($m_font_faces as $k => $m_face) {
$metadata['google_fonts']['font_faces'][$k]['attached_font_files'] = [];
if (!$m_face['isEnabled']) {
continue;
}
if ($metadata['google_fonts']['variable']) {
if ($m_face['weight'] !== 0) {
continue;
}
$all_filtered_m_font_files = GoogleFontFileSelector::variableFiles($m_font_files, $m_face, $metadata['google_fonts']['subsets'], $metadata['google_fonts']['formats']);
foreach ($all_filtered_m_font_files as $filtered_m_font_file) {
$wght = array_filter($metadata['google_fonts']['font_data']['axes'], static fn($a) => $a['tag'] === 'wght');
$wdth = array_filter($metadata['google_fonts']['font_data']['axes'], static fn($a) => $a['tag'] === 'wdth');
$slnt = array_filter($metadata['google_fonts']['font_data']['axes'], static fn($a) => $a['tag'] === 'slnt');
$wdth = array_values($wdth);
$wght = array_values($wght);
$slnt = array_values($slnt);
$font_face = ['id' => Common::random_slug(10), 'weight' => $wght !== [] ? sprintf('%s %s', $wght[0]['min'], $wght[0]['max']) : '400', 'width' => $wdth !== [] ? sprintf('%s%% %s%%', $wdth[0]['min'], $wdth[0]['max']) : '100%', 'style' => $slnt !== [] ? sprintf('oblique %sdeg %sdeg', $slnt[0]['max'] * -1, $slnt[0]['min'] * -1) : $m_face['style'], 'display' => $m_face['display'], 'selector' => $m_face['selector'], 'comment' => $m_face['comment'], 'preload' => $m_face['preload']];
if (array_key_exists('file', $filtered_m_font_file)) {
$file = $filtered_m_font_file['file'];
} else {
$file_name = sanitize_title_with_dashes(sprintf(
'google-fonts-%s-%s-%s-var-%s-%s',
$metadata['google_fonts']['font_data']['slug'],
// family
$metadata['google_fonts']['font_data']['version'] ?? 'latest',
implode('_', $filtered_m_font_file['subsets']),
Common::random_slug(5),
time()
)) . '.' . $filtered_m_font_file['format'];
$file = $media->remote($filtered_m_font_file['url'], $file_name, $filtered_m_font_file['format'], ['fonts.gstatic.com']);
$metadata['google_fonts']['font_files'] = array_map(static fn($f) => $f['uid'] === $filtered_m_font_file['uid'] ? array_merge($f, ['file' => $file]) : $f, $metadata['google_fonts']['font_files']);
}
$metadata['google_fonts']['font_faces'][$k]['attached_font_files'][] = $filtered_m_font_file['uid'];
$font_face['files'] = [$file];
$font_face['unicodeRange'] = $filtered_m_font_file['unicodeRange'] ?? '';
$font_faces[] = $font_face;
}
} else {
if ($m_face['weight'] === 0) {
continue;
}
$font_face = ['id' => Common::random_slug(10), 'weight' => $m_face['weight'], 'width' => $m_face['width'] ?: '100%', 'style' => $m_face['style'], 'display' => $m_face['display'], 'selector' => $m_face['selector'], 'comment' => $m_face['comment'], 'unicodeRange' => '', 'preload' => $m_face['preload']];
$files = [];
$filtered_m_font_files = array_filter($m_font_files, static fn($f) => $f['weight'] === $m_face['weight'] && $f['style'] === $m_face['style'] && array_diff($metadata['google_fonts']['subsets'], $f['subsets']) === array_diff($f['subsets'], $metadata['google_fonts']['subsets']) && in_array($f['format'], $metadata['google_fonts']['formats'], \true));
$format_precedence = ['woff2' => 1, 'woff' => 2, 'ttf' => 3, 'otf' => 4, 'eot' => 5];
usort($filtered_m_font_files, static fn($a, $b) => $format_precedence[$a['format']] <=> $format_precedence[$b['format']]);
foreach ($filtered_m_font_files as $filtered_m_font_file) {
if (array_key_exists('file', $filtered_m_font_file)) {
$file = $filtered_m_font_file['file'];
} else {
$file_name = sanitize_title_with_dashes(sprintf(
'google-fonts-%s-%s-%s-%s-%s-%s',
$metadata['google_fonts']['font_data']['slug'],
// family
$metadata['google_fonts']['font_data']['version'] ?? 'latest',
implode('-', $metadata['google_fonts']['subsets']),
$filtered_m_font_file['weight'],
$filtered_m_font_file['style'],
time()
)) . '.' . $filtered_m_font_file['format'];
$file = $media->remote($filtered_m_font_file['url'], $file_name, $filtered_m_font_file['format'], ['fonts.gstatic.com']);
$metadata['google_fonts']['font_files'] = array_map(static fn($f) => $f['uid'] === $filtered_m_font_file['uid'] ? array_merge($f, ['file' => $file]) : $f, $metadata['google_fonts']['font_files']);
}
$metadata['google_fonts']['font_faces'][$k]['attached_font_files'][] = $filtered_m_font_file['uid'];
$files[] = $file;
}
$font_face['files'] = $files;
$font_faces[] = $font_face;
}
}
}
private function update_google_fonts_metadata()
{
$file_path = Cache::get_cache_path('webfonts.json');
// The bundled and cached catalogs remain available while the canonical repository is being migrated.
$cdn_url = apply_filters('f!jooosi/fon/font:google_fonts.metadata.file_url', 'https://cdn.jsdelivr.net/gh/jooosi-project/jooosi-fon@master/google-fonts.json');
$cdn_url = apply_filters_deprecated('f!yabe/webfont/font:google_fonts.metadata.file_url', [$cdn_url], '2.1.0', 'f!jooosi/fon/font:google_fonts.metadata.file_url');
if (!wp_http_validate_url($cdn_url)) {
throw new \Exception(__('The metadata URL is not safe', 'jooosi-fon'));
}
$temp_file = download_url($cdn_url, 30);
if (is_wp_error($temp_file)) {
throw new \Exception(__('Failed to download metadata file', 'jooosi-fon'));
}
$staging_file = $file_path . '.tmp-' . wp_generate_uuid4();
try {
$contents = file_get_contents($temp_file);
if (!is_string($contents)) {
throw new \RuntimeException('The downloaded metadata file is not readable.');
}
json_decode($contents, \true, 512, \JSON_THROW_ON_ERROR);
Common::save_file($contents, $staging_file);
if (!@rename($staging_file, $file_path)) {
throw new \RuntimeException('The metadata cache could not be replaced atomically.');
}
delete_transient('jooosi_fon_google_fonts_catalog_stats');
} finally {
if (is_string($temp_file) && file_exists($temp_file)) {
unlink($temp_file);
}
if (file_exists($staging_file)) {
unlink($staging_file);
}
}
}
private function google_fonts_metadata(WP_REST_Request $wprestRequest): WP_REST_Response
{
$file_path = Cache::get_cache_path('webfonts.json');
$query = $wprestRequest->get_query_params();
$force_update = filter_var($query['force'] ?? \false, \FILTER_VALIDATE_BOOLEAN);
$force_cdn = apply_filters('f!jooosi/fon/font:google_fonts.metadata.force_cdn', \false);
$force_cdn = apply_filters_deprecated('f!yabe/webfont/font:google_fonts.metadata.force_cdn', [$force_cdn], '2.1.0', 'f!jooosi/fon/font:google_fonts.metadata.force_cdn');
if ($force_update || $force_cdn) {
try {
$this->update_google_fonts_metadata();
} catch (\Exception $e) {
return new WP_REST_Response(['message' => $e->getMessage()], 500, []);
}
$metadata = json_decode(file_get_contents($file_path), null, 512, \JSON_THROW_ON_ERROR);
return new WP_REST_Response(['fonts' => $metadata], 200, []);
}
if (!file_exists($file_path)) {
$payload = file_get_contents(dirname(JOOOSI_FON::FILE) . '/google-fonts.json');
Common::save_file($payload, $file_path);
}
$enable_update = apply_filters('f!jooosi/fon/font:google_fonts.metadata.enable_update', \true);
$enable_update = apply_filters_deprecated('f!yabe/webfont/font:google_fonts.metadata.enable_update', [$enable_update], '2.1.0', 'f!jooosi/fon/font:google_fonts.metadata.enable_update');
if ($enable_update !== \false) {
if (filemtime($file_path) < strtotime('-1 day')) {
try {
$this->update_google_fonts_metadata();
} catch (\Exception $e) {
// Keep serving the cached catalog when an automatic refresh is unavailable.
}
}
}
$metadata = json_decode(file_get_contents($file_path), null, 512, \JSON_THROW_ON_ERROR);
return new WP_REST_Response(['fonts' => $metadata], 200, []);
}
private function google_fonts_webfonts(WP_REST_Request $wprestRequest): WP_REST_Response
{
$url_params = $wprestRequest->get_url_params();
$query = $wprestRequest->get_query_params();
$slug = $url_params['slug'] ?? '';
if (trim($slug) === '') {
return new WP_REST_Response(['message' => __('Slug is required', 'jooosi-fon')], 400, []);
}
// retrieve metadata
$file_path = Cache::get_cache_path('webfonts.json');
if (!file_exists($file_path)) {
$payload = file_get_contents(dirname(JOOOSI_FON::FILE) . '/google-fonts.json');
Common::save_file($payload, $file_path);
}
$enable_update = apply_filters('f!jooosi/fon/font:google_fonts.metadata.enable_update', \true);
$enable_update = apply_filters_deprecated('f!yabe/webfont/font:google_fonts.metadata.enable_update', [$enable_update], '2.1.0', 'f!jooosi/fon/font:google_fonts.metadata.enable_update');
if ($enable_update !== \false) {
if (filemtime($file_path) < strtotime('-1 day')) {
try {
$this->update_google_fonts_metadata();
} catch (\Exception $e) {
// Keep serving the cached catalog when an automatic refresh is unavailable.
}
}
}
$metadata = json_decode(file_get_contents($file_path), null, 512, \JSON_THROW_ON_ERROR);
// search for the font by slug
$font = array_filter($metadata, static fn($font) => $font->slug === $slug);
if (empty($font)) {
return new WP_REST_Response(['message' => __('Font not found', 'jooosi-fon')], 404, []);
}
$font = array_values($font)[0];
// get the first element of the array
$subsets = $query['subsets'] ?? '';
if (!$subsets) {
$subsets = in_array('latin', $font->subsets, \true) ? ['latin'] : [$font->subsets[0]];
} else {
$querySubsets = explode(',', $subsets);
$subsets = array_intersect($font->subsets, $querySubsets);
}
$subsets = array_unique($subsets);
sort($subsets);
if ($subsets === []) {
return new WP_REST_Response(['message' => __('None of the requested subsets are available for this font.', 'jooosi-fon')], 400, []);
}
$cache_key = 'jooosi_fon_google_fonts_files_' . md5($slug . ':' . implode(',', $subsets));
$cachedFontFiles = get_transient($cache_key);
if ($cachedFontFiles !== \false) {
return new WP_REST_Response(['font' => $font, 'files' => array_values($cachedFontFiles)], 200, []);
}
$variantKeys = $font->variants;
$fontFormats = ['woff2', 'woff', 'ttf'];
try {
foreach ($variantKeys as $variantKey) {
foreach ($fontFormats as $fontFormat) {
$fontUrl = $this->fetch_google_font_file($font, $fontFormat, $variantKey, $subsets);
$newFontFile = new stdClass();
$newFontFile->format = $fontFormat;
$newFontFile->weight = intval($variantKey);
switch (preg_replace('/\d/', '', (string) $variantKey)) {
case 'i':
$newFontFile->style = 'italic';
break;
case 'o':
$newFontFile->style = 'oblique';
break;
default:
$newFontFile->style = 'normal';
}
$newFontFile->subsets = $subsets;
$newFontFile->url = $fontUrl;
$font->files[] = $newFontFile;
}
}
if (!empty($font->axes)) {
$italics = [];
if (count(array_filter($variantKeys, static fn(string $variantKey) => preg_replace('/\d/', '', $variantKey) === '')) > 0) {
array_push($italics, 0);
}
if (count(array_filter($variantKeys, static fn(string $variantKey) => preg_replace('/\d/', '', $variantKey) === 'i')) > 0) {
array_push($italics, 1);
}
foreach ($italics as $italic) {
switch ($italic) {
case 0:
$style = 'normal';
break;
case 1:
$style = 'italic';
break;
default:
$style = 'normal';
}
$filteredFontFilesVariable = array_filter($font->files, function ($fontFile) use ($style, $subsets) {
return $fontFile->format === 'woff2' && $fontFile->weight === 0 && $fontFile->style === $style && array_intersect($fontFile->subsets, $subsets) !== [];
});
if (count($filteredFontFilesVariable) < count($subsets)) {
$fetchedVariableFonts = $this->fetch_google_font_variable_file($font, $italic, $font->axes);
foreach ($fetchedVariableFonts as $fetchedVariableFont) {
$existFilteredFontFilesVariable = array_filter($filteredFontFilesVariable, function ($fontFile) use ($fetchedVariableFont, $style) {
return $fontFile->format === 'woff2' && $fontFile->weight === 0 && $fontFile->style === $style && in_array($fetchedVariableFont['subset'], $fontFile->subsets, \true);
});
if (empty($existFilteredFontFilesVariable)) {
$newFontFile = new stdClass();
$newFontFile->format = 'woff2';
$newFontFile->weight = 0;
$newFontFile->style = $style;
$newFontFile->subsets = [$fetchedVariableFont['subset']];
$newFontFile->url = $fetchedVariableFont['url'];
$newFontFile->unicodeRange = $fetchedVariableFont['unicodeRange'];
$font->files[] = $newFontFile;
}
}
}
}
}
} catch (\Throwable $throwable) {
return $this->operation_error($throwable, __('Unable to fetch the Google font stylesheets.', 'jooosi-fon'), 502);
}
$filteredFontFiles = array_filter($font->files, static function ($fontFile) use ($subsets) {
$fontFileSubsets = array_unique($fontFile->subsets);
sort($fontFileSubsets);
$variableNumberedSubsets = \false;
if ($fontFile->weight === 0) {
foreach ($fontFile->subsets as $ffSubset) {
if (preg_match('/\d/', $ffSubset)) {
$variableNumberedSubsets = \true;
break;
}
}
}
return $fontFileSubsets === $subsets || $variableNumberedSubsets || $fontFile->weight === 0 && array_intersect($fontFileSubsets, $subsets) !== [];
});
// Cache the result for 1 day
set_transient($cache_key, $filteredFontFiles, \DAY_IN_SECONDS);
unset($font->files);
return new WP_REST_Response(['font' => $font, 'files' => array_values($filteredFontFiles)], 200, []);
}
private function fetch_google_font_file($font, string $format, string $variant, array $subsets): string
{
switch ($format) {
case 'woff2':
$userAgent = JOOOSI_FON::USER_AGENTS['WOFF2'];
break;
case 'woff':
$userAgent = JOOOSI_FON::USER_AGENTS['WOFF'];
break;
case 'ttf':
$userAgent = JOOOSI_FON::USER_AGENTS['TTF'];
break;
default:
$userAgent = apply_filters('f!jooosi/fon/font:google_fonts.fetch.user_agent.default', JOOOSI_FON::USER_AGENTS['CURRENT']);
$userAgent = apply_filters_deprecated('f!yabe/webfont/font:google_fonts.fetch.user_agent.default', [$userAgent], '2.1.0', 'f!jooosi/fon/font:google_fonts.fetch.user_agent.default');
}
$family = str_replace(' ', '+', $font->family);
$url = sprintf('https://fonts.googleapis.com/css?family=%s:%s&subset=%s', $family, $variant, implode(',', $subsets));
$body = (new GoogleFontsClient())->fetchCss($url, $userAgent);
$cssDocument = (new Parser($body))->parse();
$contents = $cssDocument->getContents();
if ($contents === [] || $contents[0]->getRules('src') === []) {
throw new \RuntimeException(__('Google Fonts returned an invalid stylesheet', 'jooosi-fon'));
}
$fontUrl = $contents[0]->getRules('src')[0]->getValue()->getListComponents()[0]->getURL()->getString();
return $fontUrl;
}
private function negative_case(string $string): string
{
$arr = str_split($string);
foreach ($arr as $key => $char) {
$arr[$key] = ctype_upper($char) ? strtolower($char) : strtoupper($char);
}
return implode('', $arr);
}
private function operation_error(\Throwable $throwable, string $message, int $status = 500): WP_REST_Response
{
do_action('a!jooosi/fon/api:error', $throwable, $message, $status);
if (defined('WP_DEBUG') && \WP_DEBUG) {
$message = sprintf('%s %s', $message, $throwable->getMessage());
}
return new WP_REST_Response(['message' => $message], $status);
}
/**
* @see https://developers.google.com/fonts/docs/css2#api_url_specification
*/
private function fetch_google_font_variable_file($font, int $italic, array $axes): array
{
$axis_tag_list = [];
$axis_tuple_list = [];
$family = str_replace(' ', '+', $font->family);
// convert axes to array
$axes = array_map(static fn($axis) => ['tag' => $axis->tag, 'min' => $axis->min ?? null, 'max' => $axis->max ?? null, 'defaultValue' => $axis->defaultValue ?? null], $axes);
// add ital axis
$axes[] = ['tag' => 'ital', 'defaultValue' => $italic];
// sort axes by "tag" alphabetically (e.g. a,b,c,A,B,C)
usort($axes, fn(array $a, array $b) => strcmp((string) $this->negative_case($a['tag']), (string) $this->negative_case($b['tag'])));
foreach ($axes as $a) {
$axis_tag_list[] = $a['tag'];
if (array_key_exists('min', $a) && array_key_exists('max', $a)) {
$axis_tuple_list[] = sprintf('%s..%s', $a['min'], $a['max']);
} else {
$axis_tuple_list[] = sprintf('%s', $a['defaultValue']);
}
}
$url = sprintf('https://fonts.googleapis.com/css2?family=%s:%s@%s', $family, implode(',', $axis_tag_list), implode(',', $axis_tuple_list));
$parsedFiles = [];
$userAgent = apply_filters('f!jooosi/fon/font:google_fonts.fetch.user_agent.default', JOOOSI_FON::USER_AGENTS['CURRENT']);
$userAgent = apply_filters_deprecated('f!yabe/webfont/font:google_fonts.fetch.user_agent.default', [$userAgent], '2.1.0', 'f!jooosi/fon/font:google_fonts.fetch.user_agent.default');
$body = (new GoogleFontsClient())->fetchCss($url, $userAgent);
// parse the css
$cssDocument = (new Parser($body))->parse();
// match all comment /* comment */
preg_match_all('/\/\*(.*?)\*\//s', $body, $parsedComments);
$comments = array_map(static fn(string $comment) => trim($comment), $parsedComments[1]);
$cssContents = $cssDocument->getContents();
for ($i = 0; $i < count($cssContents); $i++) {
if (!isset($comments[$i]) || $cssContents[$i]->getRules('src') === [] || $cssContents[$i]->getRules('unicode-range') === []) {
continue;
}
$subset = $comments[$i];
$url = $cssContents[$i]->getRules('src')[0]->getValue()->getListComponents()[0]->getURL()->getString();
$unicodeRangeRuleSet = $cssContents[$i]->getRules('unicode-range')[0]->getValue();
$unicodeRange = $unicodeRangeRuleSet instanceof \JooosiFonDeps\Sabberworm\CSS\Value\RuleValueList ? implode(', ', $unicodeRangeRuleSet->getListComponents()) : $unicodeRangeRuleSet;
$parsedFiles[] = ['subset' => $subset, 'url' => $url, 'unicodeRange' => $unicodeRange];
}
return $parsedFiles;
}
}
@@ -0,0 +1,122 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Api\Migrations;
use JooosiFon\Api\AbstractApi;
use JooosiFon\Api\ApiInterface;
use JooosiFon\Api\Migrations\Support\SourceFontNormalizer;
use JooosiFon\Api\Support\FontCodec;
use JooosiFon\Api\Support\FontEvents;
use JooosiFon\Api\Support\FontRepository;
use JooosiFon\Api\Support\MediaImportService;
use JooosiFon\Api\Support\RequestValidator;
use JooosiFon\Utils\Common;
use JooosiFon\Utils\Upload;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;
final class BrainstormForceCustomFonts extends AbstractApi implements ApiInterface
{
public function get_prefix(): string
{
return 'migrations/brainstorm-force-custom-fonts';
}
public function register_custom_endpoints(): void
{
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/import-fonts', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(WP_REST_Request $request): WP_REST_Response => $this->import_fonts($request), 'permission_callback' => fn(WP_REST_Request $request): bool => $this->permission_callback($request)]);
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/clean-up', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(WP_REST_Request $request): WP_REST_Response => $this->clean_up($request), 'permission_callback' => fn(WP_REST_Request $request): bool => $this->permission_callback($request), 'args' => ['confirm' => ['required' => \true, 'sanitize_callback' => 'rest_sanitize_boolean', 'validate_callback' => [RequestValidator::class, 'confirmed']]]]);
}
public function import_fonts(WP_REST_Request $request): WP_REST_Response
{
if (!defined('BSF_CUSTOM_FONTS_POST_TYPE')) {
return new WP_REST_Response(['message' => __('Custom Fonts by Brainstorm Force is not activated.', 'jooosi-fon')], 404);
}
$fontIds = get_posts(['post_type' => \BSF_CUSTOM_FONTS_POST_TYPE, 'post_status' => 'publish', 'posts_per_page' => -1, 'fields' => 'ids', 'no_found_rows' => \true]);
$preload = filter_var(get_option('bcf_preloading_fonts', \false), \FILTER_VALIDATE_BOOLEAN);
add_filter('wp_check_filetype_and_ext', static fn($data, $file, $filename, $mimes) => Upload::disable_real_mime_check($data, $file, $filename, $mimes), 10, 4);
add_filter('upload_mimes', static fn($mimeTypes) => Upload::upload_mimes($mimeTypes, \true), 1000001);
$repository = new FontRepository();
$media = new MediaImportService();
$records = [];
$insertedIds = [];
$skipped = 0;
try {
foreach ($fontIds as $fontId) {
$fontId = absint($fontId);
$migrationSlug = 'migration-brainstorm-force-' . $fontId;
if ($fontId < 1 || $repository->findBySlug($migrationSlug)) {
continue;
}
$post = get_post($fontId);
$source = get_post_meta($fontId, 'fonts-data', \true);
if (!$post || !is_array($source)) {
++$skipped;
continue;
}
$family = sanitize_text_field($post->post_title);
if ($family === '') {
++$skipped;
continue;
}
$normalized = SourceFontNormalizer::brainstormForce($source);
$skipped += $normalized['skipped'];
$fontFaces = [];
foreach ($normalized['faces'] as $sourceFace) {
$files = [];
foreach ($sourceFace['files'] as $sourceFile) {
$fileName = sanitize_title_with_dashes(sprintf('%s-%s-%s-%s-%s', $post->post_title, $sourceFace['weight'], $sourceFace['style'], Common::random_slug(5), time())) . '.' . $sourceFile['extension'];
$files[] = $media->remote($sourceFile['location'], $fileName, $sourceFile['extension']);
}
if ($files === []) {
continue;
}
$fontFaces[] = ['id' => Common::random_slug(10), 'weight' => $sourceFace['weight'], 'width' => $sourceFace['width'], 'style' => $sourceFace['style'], 'display' => '', 'selector' => '', 'comment' => '', 'unicodeRange' => '', 'preload' => \false, 'files' => $files];
}
if ($fontFaces === []) {
++$skipped;
continue;
}
$selector = $normalized['fallback'] === '' ? '' : '| ' . sanitize_text_field($normalized['fallback']);
$records[] = ['type' => 'custom', 'title' => $family, 'slug' => $migrationSlug, 'family' => $family, 'status' => \true, 'metadata' => FontCodec::encode(['preload' => $preload, 'selector' => $selector, 'display' => $normalized['display']]), 'font_faces' => FontCodec::encode($fontFaces)];
}
if ($skipped > 0) {
$media->rollback();
return new WP_REST_Response(['message' => __('Some Brainstorm Force font records had no supported, readable files. Nothing was imported so the source records remain safe.', 'jooosi-fon'), 'skipped' => $skipped], 422);
}
$insertedIds = $repository->transaction(static function (FontRepository $repository) use ($records): array {
$ids = [];
foreach ($records as $record) {
$ids[] = $repository->insert($record, ['%s', '%s', '%s', '%s', '%d', '%s', '%s']);
}
return $ids;
});
} catch (\Throwable $throwable) {
$media->rollback();
return new WP_REST_Response(['message' => __('The Brainstorm Force Custom Fonts migration failed; newly created Jooosi Fon records were rolled back.', 'jooosi-fon')], 500);
}
$media->commit();
FontEvents::dispatch('migration', ['source' => 'brainstorm-force-custom-fonts', 'ids' => $insertedIds], \true);
return new WP_REST_Response(['message' => __('Brainstorm Force Custom Fonts imported. Source records were preserved.', 'jooosi-fon'), 'imported' => count($insertedIds), 'skipped' => $skipped, 'source_preserved' => \true]);
}
public function clean_up(WP_REST_Request $request): WP_REST_Response
{
if (!defined('BSF_CUSTOM_FONTS_POST_TYPE')) {
return new WP_REST_Response(['message' => __('Custom Fonts by Brainstorm Force is not activated.', 'jooosi-fon')], 404);
}
$fontIds = get_posts(['post_type' => \BSF_CUSTOM_FONTS_POST_TYPE, 'post_status' => 'publish', 'posts_per_page' => -1, 'fields' => 'ids', 'no_found_rows' => \true]);
$trashedIds = [];
foreach ($fontIds as $fontId) {
$fontId = absint($fontId);
if ($fontId < 1 || !wp_trash_post($fontId)) {
foreach ($trashedIds as $trashedId) {
wp_untrash_post($trashedId);
}
return new WP_REST_Response(['message' => __('Brainstorm Force source cleanup failed and previously trashed records were restored.', 'jooosi-fon')], 500);
}
$trashedIds[] = $fontId;
}
FontEvents::dispatch('clean_up', ['source' => 'brainstorm-force-custom-fonts', 'ids' => $trashedIds], \true);
return new WP_REST_Response(['message' => __('Brainstorm Force Custom Fonts source records moved to the trash.', 'jooosi-fon'), 'cleaned' => count($trashedIds)]);
}
}
@@ -0,0 +1,123 @@
<?php
/*
* This file is part of the Jooosi Fon package.
*
* (c) Joshua Gugun Siagian <suabahasa@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare (strict_types=1);
namespace JooosiFon\Api\Migrations;
use JooosiFon\Api\AbstractApi;
use JooosiFon\Api\ApiInterface;
use JooosiFon\Api\Support\FontCodec;
use JooosiFon\Api\Support\FontEvents;
use JooosiFon\Api\Support\FontRepository;
use JooosiFon\Api\Support\MediaImportService;
use JooosiFon\Api\Support\RequestValidator;
use JooosiFon\Utils\Common;
use JooosiFon\Utils\Upload;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;
class BricksCustomFonts extends AbstractApi implements ApiInterface
{
public function __construct()
{
}
public function get_prefix(): string
{
return 'migrations/bricks-custom-fonts';
}
public function register_custom_endpoints(): void
{
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/import-fonts', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->import_fonts($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest)]);
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/clean-up', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->clean_up($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest), 'args' => ['confirm' => ['required' => \true, 'sanitize_callback' => 'rest_sanitize_boolean', 'validate_callback' => [RequestValidator::class, 'confirmed']]]]);
}
/**
* @see Bricks\Custom_Fonts::get_custom_fonts()
* @see JooosiFon\Api\Font::import()
*/
public function import_fonts(WP_REST_Request $wprestRequest): WP_REST_Response
{
if (!defined('BRICKS_DB_CUSTOM_FONTS') || !defined('BRICKS_DB_CUSTOM_FONT_FACES')) {
return new WP_REST_Response(['message' => 'Bricks theme not activated'], 404);
}
$font_ids = get_posts(['post_type' => \BRICKS_DB_CUSTOM_FONTS, 'posts_per_page' => -1, 'fields' => 'ids', 'no_found_rows' => \true]);
add_filter('wp_check_filetype_and_ext', static fn($data, $file, $filename, $mimes) => Upload::disable_real_mime_check($data, $file, $filename, $mimes), 10, 4);
add_filter('upload_mimes', static fn($mime_types) => Upload::upload_mimes($mime_types, \true), 1000001);
$repository = new FontRepository();
$media = new MediaImportService();
$insertedIds = [];
$records = [];
try {
foreach ($font_ids as $font_id) {
$migrationSlug = 'migration-bricks-' . absint($font_id);
if ($repository->findBySlug($migrationSlug)) {
continue;
}
$bricks_font_faces = get_post_meta($font_id, \BRICKS_DB_CUSTOM_FONT_FACES, \true);
if ($bricks_font_faces === \false || empty($bricks_font_faces)) {
continue;
}
$post = get_post($font_id);
if (!$post) {
throw new \RuntimeException('A Bricks font record could not be loaded.');
}
$font_faces = [];
// $key: font-weight + variant (e.g.: 700italic)
foreach ($bricks_font_faces as $key => $bricks_font_face) {
$font_weight = filter_var($key, \FILTER_SANITIZE_NUMBER_INT);
$font_style = str_replace($font_weight, '', $key);
$font_face = ['id' => Common::random_slug(10), 'weight' => $font_weight, 'width' => '', 'style' => empty($font_style) ? 'normal' : $font_style, 'display' => '', 'selector' => '', 'comment' => '', 'unicodeRange' => '', 'preload' => \false, 'files' => []];
foreach ($bricks_font_face as $key_format => $bricks_font_face_file) {
$file_name = sanitize_title_with_dashes(sprintf('%s-%s-%s-%s-%s', $post->post_title, $font_weight, empty($font_style) ? 'normal' : $font_style, Common::random_slug(5), time())) . '.' . $key_format;
$old_attachment_url = wp_get_attachment_url($bricks_font_face_file);
if ($old_attachment_url === \false) {
continue;
}
$font_face['files'][] = $media->remote($old_attachment_url, $file_name, $key_format);
}
$font_faces[] = $font_face;
}
$metadata = ['preload' => \false, 'selector' => '', 'display' => 'auto'];
$records[] = ['type' => 'custom', 'title' => $post->post_title, 'slug' => $migrationSlug, 'family' => $post->post_title, 'status' => \true, 'metadata' => FontCodec::encode($metadata), 'font_faces' => FontCodec::encode($font_faces)];
}
$insertedIds = $repository->transaction(static function (FontRepository $repository) use ($records): array {
$ids = [];
foreach ($records as $record) {
$ids[] = $repository->insert($record, ['%s', '%s', '%s', '%s', '%d', '%s', '%s']);
}
return $ids;
});
} catch (\Throwable $throwable) {
$media->rollback();
return new WP_REST_Response(['message' => __('The Bricks migration failed; newly created Jooosi Fon records were rolled back.', 'jooosi-fon')], 500);
}
$media->commit();
FontEvents::dispatch('migration', ['source' => 'bricks-custom-fonts', 'ids' => $insertedIds], \true);
return new WP_REST_Response(['message' => __('Bricks fonts imported. Source records were preserved.', 'jooosi-fon'), 'imported' => count($insertedIds), 'source_preserved' => \true]);
}
public function clean_up(WP_REST_Request $wprestRequest): WP_REST_Response
{
if (!defined('BRICKS_DB_CUSTOM_FONTS')) {
return new WP_REST_Response(['message' => 'Bricks theme not activated'], 404);
}
$font_ids = get_posts(['post_type' => \BRICKS_DB_CUSTOM_FONTS, 'posts_per_page' => -1, 'fields' => 'ids', 'no_found_rows' => \true]);
$trashedIds = [];
foreach ($font_ids as $font_id) {
if (!wp_trash_post($font_id)) {
foreach ($trashedIds as $trashedId) {
wp_untrash_post($trashedId);
}
return new WP_REST_Response(['message' => __('Bricks source cleanup failed and previously trashed records were restored.', 'jooosi-fon')], 500);
}
$trashedIds[] = $font_id;
}
FontEvents::dispatch('clean_up', ['source' => 'bricks-custom-fonts', 'ids' => $trashedIds], \true);
return new WP_REST_Response(['message' => __('Bricks source records moved to the trash.', 'jooosi-fon'), 'cleaned' => count($trashedIds)]);
}
}
@@ -0,0 +1,110 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Api\Migrations;
use JooosiFonDeps\JOOOSI_FON;
use JooosiFon\Api\AbstractApi;
use JooosiFon\Api\ApiInterface;
use JooosiFon\Api\Migrations\Support\SourceFontNormalizer;
use JooosiFon\Api\Support\FontCodec;
use JooosiFon\Api\Support\FontEvents;
use JooosiFon\Api\Support\FontRepository;
use JooosiFon\Api\Support\RequestValidator;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;
final class CustomAdobeFonts extends AbstractApi implements ApiInterface
{
private const SOURCE_OPTION = 'custom-typekit-fonts';
public function get_prefix(): string
{
return 'migrations/custom-adobe-fonts';
}
public function register_custom_endpoints(): void
{
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/import-fonts', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(WP_REST_Request $request): WP_REST_Response => $this->import_fonts($request), 'permission_callback' => fn(WP_REST_Request $request): bool => $this->permission_callback($request)]);
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/clean-up', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(WP_REST_Request $request): WP_REST_Response => $this->clean_up($request), 'permission_callback' => fn(WP_REST_Request $request): bool => $this->permission_callback($request), 'args' => ['confirm' => ['required' => \true, 'sanitize_callback' => 'rest_sanitize_boolean', 'validate_callback' => [RequestValidator::class, 'confirmed']]]]);
}
public function import_fonts(WP_REST_Request $request): WP_REST_Response
{
if (!defined('CUSTOM_TYPEKIT_FONTS_VER')) {
return new WP_REST_Response(['message' => __('Custom Adobe Fonts is not activated.', 'jooosi-fon')], 404);
}
$source = get_option(self::SOURCE_OPTION, null);
if (!is_array($source)) {
return new WP_REST_Response(['message' => __('Custom Adobe Fonts records could not be read.', 'jooosi-fon')], 500);
}
$kit = SourceFontNormalizer::customAdobeKit($source);
if (!RequestValidator::projectId($kit['id']) || !RequestValidator::adobeKit($kit) || $kit['families'] === []) {
return new WP_REST_Response(['message' => __('The Custom Adobe Fonts project has no usable published families.', 'jooosi-fon')], 422);
}
$options = $this->jooosi_options();
if ($options === null) {
return new WP_REST_Response(['message' => __('Jooosi Fon settings are invalid, so the Adobe project was not changed.', 'jooosi-fon')], 500);
}
$adobeOptions = isset($options['adobe_fonts']) && is_array($options['adobe_fonts']) ? $options['adobe_fonts'] : [];
$currentProjectId = trim((string) ($adobeOptions['project_id'] ?? ''));
if ($currentProjectId !== '' && $currentProjectId !== $kit['id']) {
return new WP_REST_Response(['message' => __('Jooosi Fon is already connected to a different Adobe Fonts project. Disconnect it before migrating this source.', 'jooosi-fon')], 409);
}
$options['adobe_fonts'] = ['project_id' => $kit['id'], 'kit' => $kit];
$repository = new FontRepository();
$insertedIds = [];
try {
$insertedIds = $repository->transaction(function (FontRepository $repository) use ($kit, $options): array {
$repository->deleteByType('adobe-fonts');
$ids = [];
foreach ($kit['families'] as $family) {
$ids[] = $repository->insert(['status' => 1, 'type' => 'adobe-fonts', 'title' => sanitize_text_field($family['name']), 'slug' => sanitize_key($family['id']), 'family' => sanitize_text_field($family['slug']), 'metadata' => FontCodec::encode($family), 'font_faces' => FontCodec::encode([])], ['%d', '%s', '%s', '%s', '%s', '%s', '%s']);
}
$this->store_jooosi_options($options);
return $ids;
});
} catch (\Throwable $throwable) {
wp_cache_delete(JOOOSI_FON::WP_OPTION . '_options', 'options');
return new WP_REST_Response(['message' => __('The Custom Adobe Fonts migration failed; the previous Adobe project and families were preserved.', 'jooosi-fon')], 500);
}
FontEvents::dispatch('migration', ['source' => 'custom-adobe-fonts', 'ids' => $insertedIds], \true);
return new WP_REST_Response(['message' => __('Custom Adobe Fonts project and families imported. Source settings were preserved.', 'jooosi-fon'), 'imported' => count($insertedIds), 'source_preserved' => \true]);
}
public function clean_up(WP_REST_Request $request): WP_REST_Response
{
if (!defined('CUSTOM_TYPEKIT_FONTS_VER')) {
return new WP_REST_Response(['message' => __('Custom Adobe Fonts is not activated.', 'jooosi-fon')], 404);
}
$source = get_option(self::SOURCE_OPTION, null);
if ($source !== null && !delete_option(self::SOURCE_OPTION)) {
return new WP_REST_Response(['message' => __('Custom Adobe Fonts cleanup failed and its source settings were preserved.', 'jooosi-fon')], 500);
}
FontEvents::dispatch('clean_up', ['source' => 'custom-adobe-fonts'], \true);
return new WP_REST_Response(['message' => __('Custom Adobe Fonts source settings were removed. The migrated Jooosi Fon Adobe project remains connected.', 'jooosi-fon'), 'cleaned' => is_array($source) ? 1 : 0]);
}
/**
* @return array<string, mixed>|null
*/
private function jooosi_options(): ?array
{
$stored = get_option(JOOOSI_FON::WP_OPTION . '_options', '{}');
if (!is_string($stored)) {
return null;
}
try {
$options = json_decode($stored, \true, 512, \JSON_THROW_ON_ERROR);
} catch (\JsonException $exception) {
return null;
}
return is_array($options) ? $options : null;
}
/**
* @param array<string, mixed> $options
*/
private function store_jooosi_options(array $options): void
{
$encoded = json_encode($options, \JSON_THROW_ON_ERROR);
$option = JOOOSI_FON::WP_OPTION . '_options';
if (!update_option($option, $encoded) && get_option($option) !== $encoded) {
throw new \RuntimeException('The Jooosi Fon Adobe settings could not be stored.');
}
}
}
@@ -0,0 +1,138 @@
<?php
/*
* This file is part of the Jooosi Fon package.
*
* (c) Joshua Gugun Siagian <suabahasa@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare (strict_types=1);
namespace JooosiFon\Api\Migrations;
use JooosiFon\Api\AbstractApi;
use JooosiFon\Api\ApiInterface;
use JooosiFon\Api\Support\FontCodec;
use JooosiFon\Api\Support\FontEvents;
use JooosiFon\Api\Support\FontRepository;
use JooosiFon\Api\Support\MediaImportService;
use JooosiFon\Api\Support\RequestValidator;
use JooosiFon\Utils\Common;
use JooosiFon\Utils\Upload;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;
use wpdb;
class DpluginsFontHero extends AbstractApi implements ApiInterface
{
public function __construct()
{
}
public function get_prefix(): string
{
return 'migrations/font-hero-dplugins';
}
public function register_custom_endpoints(): void
{
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/import-fonts', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->import_fonts($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest)]);
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/clean-up', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->clean_up($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest), 'args' => ['confirm' => ['required' => \true, 'sanitize_callback' => 'rest_sanitize_boolean', 'validate_callback' => [RequestValidator::class, 'confirmed']]]]);
}
/**
* @see JooosiFon\Api\Font::import()
*/
public function import_fonts(WP_REST_Request $wprestRequest): WP_REST_Response
{
if (!defined('DP_FH_BASE')) {
return new WP_REST_Response(['message' => 'Font Hero plugin is not activated'], 404);
}
/** @var wpdb $wpdb */
global $wpdb;
add_filter('wp_check_filetype_and_ext', static fn($data, $file, $filename, $mimes) => Upload::disable_real_mime_check($data, $file, $filename, $mimes), 10, 4);
add_filter('upload_mimes', static fn($mime_types) => Upload::upload_mimes($mime_types, \true), 1000001);
$dpfh_fonts = $wpdb->get_results(sprintf('SELECT * FROM %sdp_fh_fonts', $wpdb->prefix));
if ($wpdb->last_error) {
return new WP_REST_Response(['message' => __('Font Hero records could not be read.', 'jooosi-fon')], 500);
}
$repository = new FontRepository();
$media = new MediaImportService();
$insertedIds = [];
$records = [];
try {
foreach ($dpfh_fonts as $dpfh_font) {
$migrationSlug = 'migration-font-hero-' . absint($dpfh_font->id);
if ($repository->findBySlug($migrationSlug)) {
continue;
}
$font_faces = [];
$dpfh_font_faces = $wpdb->get_results($wpdb->prepare(sprintf('SELECT * FROM %sdp_fh_font_faces WHERE font_id = %%d', $wpdb->prefix), $dpfh_font->id));
if ($wpdb->last_error) {
throw new \RuntimeException('Font Hero font faces could not be read.');
}
foreach ($dpfh_font_faces as $dpfh_font_face) {
$f_weight = filter_var($dpfh_font_face->font_weight, \FILTER_SANITIZE_NUMBER_INT) ?: 100;
$f_style = empty($dpfh_font_face->font_style) ? 'normal' : sanitize_text_field($dpfh_font_face->font_style);
$font_face = array_filter($font_faces, static fn($ff) => $ff['weight'] === $f_weight && $ff['style'] === $f_style);
if ($font_face !== []) {
$font_face = array_shift($font_face);
$font_faces = array_filter($font_faces, static fn($ff) => $ff['id'] !== $font_face['id']);
} else {
$font_face = ['id' => Common::random_slug(10), 'weight' => $f_weight, 'width' => '', 'style' => $f_style, 'display' => empty($dpfh_font_face->font_display) ? '' : sanitize_text_field($dpfh_font_face->font_display), 'selector' => '', 'comment' => '', 'unicodeRange' => '', 'preload' => $dpfh_font_face->font_preload === 'yes', 'files' => []];
}
if (!empty($dpfh_font_face->font_file)) {
$f_ext = pathinfo((string) wp_parse_url($dpfh_font_face->font_file, \PHP_URL_PATH), \PATHINFO_EXTENSION);
$file_name = sanitize_title_with_dashes(sprintf('%s-%s-%s-%s-%s', sanitize_text_field($dpfh_font->font_name), $f_weight, $f_style, Common::random_slug(5), time())) . '.' . $f_ext;
$font_face['files'][] = $media->remote($dpfh_font_face->font_file, $file_name, $f_ext);
}
if (!empty($dpfh_font_face->font_file_2)) {
$f_ext = pathinfo((string) wp_parse_url($dpfh_font_face->font_file_2, \PHP_URL_PATH), \PATHINFO_EXTENSION);
$file_name = sanitize_title_with_dashes(sprintf('%s-%s-%s-%s-%s', sanitize_text_field($dpfh_font->font_name), $f_weight, $f_style, Common::random_slug(5), time())) . '.' . $f_ext;
$font_face['files'][] = $media->remote($dpfh_font_face->font_file_2, $file_name, $f_ext);
}
if (!empty($dpfh_font_face->font_file_3)) {
$f_ext = pathinfo((string) wp_parse_url($dpfh_font_face->font_file_3, \PHP_URL_PATH), \PATHINFO_EXTENSION);
$file_name = sanitize_title_with_dashes(sprintf('%s-%s-%s-%s-%s', sanitize_text_field($dpfh_font->font_name), $f_weight, $f_style, Common::random_slug(5), time())) . '.' . $f_ext;
$font_face['files'][] = $media->remote($dpfh_font_face->font_file_3, $file_name, $f_ext);
}
$font_faces[] = $font_face;
}
$metadata = ['preload' => \false, 'selector' => '', 'display' => 'auto'];
$records[] = ['type' => 'custom', 'title' => sanitize_text_field($dpfh_font->font_name), 'slug' => $migrationSlug, 'family' => sanitize_text_field($dpfh_font->font_name), 'status' => \true, 'metadata' => FontCodec::encode($metadata), 'font_faces' => FontCodec::encode($font_faces)];
}
$insertedIds = $repository->transaction(static function (FontRepository $repository) use ($records): array {
$ids = [];
foreach ($records as $record) {
$ids[] = $repository->insert($record, ['%s', '%s', '%s', '%s', '%d', '%s', '%s']);
}
return $ids;
});
} catch (\Throwable $throwable) {
$media->rollback();
return new WP_REST_Response(['message' => __('The Font Hero migration failed; newly created Jooosi Fon records were rolled back.', 'jooosi-fon')], 500);
}
$media->commit();
FontEvents::dispatch('migration', ['source' => 'font-hero-dplugins', 'ids' => $insertedIds], \true);
return new WP_REST_Response(['message' => __('Font Hero fonts imported. Source records were preserved.', 'jooosi-fon'), 'imported' => count($insertedIds), 'source_preserved' => \true]);
}
public function clean_up(WP_REST_Request $wprestRequest): WP_REST_Response
{
if (!defined('DP_FH_BASE')) {
return new WP_REST_Response(['message' => 'Font Hero plugin is not activated'], 404);
}
/** @var wpdb $wpdb */
global $wpdb;
if ($wpdb->query('START TRANSACTION') === \false) {
return new WP_REST_Response(['message' => __('Font Hero cleanup could not start a database transaction.', 'jooosi-fon')], 500);
}
try {
if ($wpdb->query(sprintf('DELETE FROM %sdp_fh_font_faces', $wpdb->prefix)) === \false || $wpdb->query(sprintf('DELETE FROM %sdp_fh_fonts', $wpdb->prefix)) === \false || $wpdb->query('COMMIT') === \false) {
throw new \RuntimeException($wpdb->last_error ?: 'Font Hero cleanup failed.');
}
} catch (\Throwable $throwable) {
$wpdb->query('ROLLBACK');
return new WP_REST_Response(['message' => __('Font Hero cleanup failed; the source transaction was rolled back.', 'jooosi-fon')], 500);
}
FontEvents::dispatch('clean_up', ['source' => 'font-hero-dplugins'], \true);
return new WP_REST_Response(['message' => __('Font Hero source records deleted.', 'jooosi-fon')]);
}
}
@@ -0,0 +1,204 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Api\Migrations;
use JooosiFon\Api\AbstractApi;
use JooosiFon\Api\ApiInterface;
use JooosiFon\Api\Migrations\Support\SourceFontNormalizer;
use JooosiFon\Api\Support\FontCodec;
use JooosiFon\Api\Support\FontEvents;
use JooosiFon\Api\Support\FontRepository;
use JooosiFon\Api\Support\MediaImportService;
use JooosiFon\Api\Support\RequestValidator;
use JooosiFon\Utils\Common;
use JooosiFon\Utils\Upload;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;
final class ElementorProCustomFonts extends AbstractApi implements ApiInterface
{
private const LEGACY_POST_TYPE = 'elementor_font';
private const FONT_FACE_POST_TYPE = 'elementor_font_face';
private const LEGACY_META_KEY = 'elementor_font_files';
public function get_prefix(): string
{
return 'migrations/elementor-pro-custom-fonts';
}
public function register_custom_endpoints(): void
{
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/import-fonts', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(WP_REST_Request $request): WP_REST_Response => $this->import_fonts($request), 'permission_callback' => fn(WP_REST_Request $request): bool => $this->permission_callback($request)]);
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/clean-up', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(WP_REST_Request $request): WP_REST_Response => $this->clean_up($request), 'permission_callback' => fn(WP_REST_Request $request): bool => $this->permission_callback($request), 'args' => ['confirm' => ['required' => \true, 'sanitize_callback' => 'rest_sanitize_boolean', 'validate_callback' => [RequestValidator::class, 'confirmed']]]]);
}
public function import_fonts(WP_REST_Request $request): WP_REST_Response
{
if (!$this->is_active()) {
return new WP_REST_Response(['message' => __('Elementor Pro Custom Fonts is not activated.', 'jooosi-fon')], 404);
}
$sourceRecords = $this->source_records();
add_filter('wp_check_filetype_and_ext', static fn($data, $file, $filename, $mimes) => Upload::disable_real_mime_check($data, $file, $filename, $mimes), 10, 4);
add_filter('upload_mimes', static fn($mimeTypes) => Upload::upload_mimes($mimeTypes, \true), 1000001);
$repository = new FontRepository();
$media = new MediaImportService();
$records = [];
$insertedIds = [];
$skipped = 0;
try {
foreach ($sourceRecords as $sourceRecord) {
$family = sanitize_text_field((string) $sourceRecord['title']);
$fontId = (int) $sourceRecord['id'];
$postType = (string) $sourceRecord['post_type'];
if ($family === '' || $fontId < 1) {
++$skipped;
continue;
}
$display = (string) apply_filters('elementor_pro/custom_fonts/font_display', 'auto', $family, $sourceRecord['variants']);
$normalized = SourceFontNormalizer::elementor($sourceRecord['variants'], $display);
$skipped += $normalized['skipped'];
if ($normalized['faces'] === []) {
if ($normalized['skipped'] === 0) {
++$skipped;
}
continue;
}
$migrationSlug = sprintf('migration-elementor-pro-%s-%d', $postType === self::FONT_FACE_POST_TYPE ? 'font-face' : 'font', $fontId);
if ($repository->findBySlug($migrationSlug)) {
continue;
}
$fontFaces = [];
foreach ($normalized['faces'] as $sourceFace) {
$files = [];
foreach ($sourceFace['files'] as $sourceFile) {
$fileName = sanitize_title_with_dashes(sprintf('%s-%s-%s-%s-%s', $family, $sourceFace['weight'], $sourceFace['style'], Common::random_slug(5), time())) . '.' . $sourceFile['extension'];
$files[] = $this->import_file($media, $sourceFile, $fileName);
}
if ($files === []) {
++$skipped;
continue;
}
$fontFaces[] = ['id' => Common::random_slug(10), 'weight' => $sourceFace['weight'], 'width' => $sourceFace['width'], 'style' => $sourceFace['style'], 'display' => '', 'selector' => '', 'comment' => '', 'unicodeRange' => '', 'preload' => (bool) $sourceFace['preload'], 'files' => $files];
}
$records[] = ['type' => 'custom', 'title' => $family, 'slug' => $migrationSlug, 'family' => $family, 'status' => \true, 'metadata' => FontCodec::encode(['preload' => \false, 'selector' => '', 'display' => $normalized['display']]), 'font_faces' => FontCodec::encode($fontFaces)];
}
if ($skipped > 0) {
$media->rollback();
return new WP_REST_Response(['message' => __('Some Elementor Pro font variants had no supported files. Nothing was imported so the source records remain safe.', 'jooosi-fon'), 'skipped' => $skipped], 422);
}
$insertedIds = $repository->transaction(static function (FontRepository $repository) use ($records): array {
$ids = [];
foreach ($records as $record) {
$ids[] = $repository->insert($record, ['%s', '%s', '%s', '%s', '%d', '%s', '%s']);
}
return $ids;
});
} catch (\Throwable $throwable) {
$media->rollback();
return new WP_REST_Response(['message' => __('The Elementor Pro Custom Fonts migration failed; newly created Jooosi Fon records were rolled back.', 'jooosi-fon')], 500);
}
$media->commit();
FontEvents::dispatch('migration', ['source' => 'elementor-pro-custom-fonts', 'ids' => $insertedIds], \true);
return new WP_REST_Response(['message' => __('Elementor Pro custom font families imported. Source records were preserved.', 'jooosi-fon'), 'imported' => count($insertedIds), 'skipped' => $skipped, 'source_preserved' => \true]);
}
public function clean_up(WP_REST_Request $request): WP_REST_Response
{
if (!$this->is_active()) {
return new WP_REST_Response(['message' => __('Elementor Pro Custom Fonts is not activated.', 'jooosi-fon')], 404);
}
$fontIds = array_values(array_unique(array_map(static fn(array $sourceRecord): int => (int) $sourceRecord['id'], $this->source_records())));
$trashedIds = [];
foreach ($fontIds as $fontId) {
if ($fontId < 1 || !wp_trash_post($fontId)) {
foreach ($trashedIds as $trashedId) {
wp_untrash_post($trashedId);
}
return new WP_REST_Response(['message' => __('Elementor Pro source cleanup failed and previously trashed records were restored.', 'jooosi-fon')], 500);
}
$trashedIds[] = $fontId;
}
FontEvents::dispatch('clean_up', ['source' => 'elementor-pro-custom-fonts', 'ids' => $trashedIds], \true);
return new WP_REST_Response(['message' => __('Elementor Pro custom-font records moved to the trash. Original media files were left in place.', 'jooosi-fon'), 'cleaned' => count($trashedIds)]);
}
private function is_active(): bool
{
return defined('ELEMENTOR_PRO_VERSION') && (post_type_exists(self::LEGACY_POST_TYPE) || post_type_exists(self::FONT_FACE_POST_TYPE));
}
/**
* @return array<int, array{id: int, post_type: string, title: string, variants: array<int, mixed>}>
*/
private function source_records(): array
{
$records = [];
foreach ([self::LEGACY_POST_TYPE, self::FONT_FACE_POST_TYPE] as $postType) {
if (!post_type_exists($postType)) {
continue;
}
$fontIds = get_posts(['post_type' => $postType, 'post_status' => 'publish', 'posts_per_page' => -1, 'fields' => 'ids', 'no_found_rows' => \true]);
foreach ($fontIds as $fontId) {
$fontId = absint($fontId);
$post = get_post($fontId);
if ($fontId < 1 || !$post) {
continue;
}
$variants = $postType === self::LEGACY_POST_TYPE ? get_post_meta($fontId, self::LEGACY_META_KEY, \true) : get_post_meta($fontId, 'font_face', \true);
if (!is_array($variants) || $variants === []) {
$variant = $this->font_face_variant($fontId);
$variants = $variant === [] ? [] : [$variant];
} elseif (isset($variants['font_weight']) || isset($variants['weight']) || array_intersect(['woff2', 'woff', 'ttf', 'otf', 'eot'], array_keys($variants)) !== []) {
$variants = [$variants];
}
$records[] = ['id' => $fontId, 'post_type' => $postType, 'title' => (string) $post->post_title, 'variants' => array_values($variants)];
}
}
return $records;
}
/**
* @return array<string, mixed>
*/
private function font_face_variant(int $fontId): array
{
$variant = ['font_weight' => $this->first_meta($fontId, ['font_face_weight', 'font_weight', 'weight'], '400'), 'font_style' => $this->first_meta($fontId, ['font_face_style', 'font_style', 'style'], 'normal'), 'font_stretch' => $this->first_meta($fontId, ['font_face_stretch', 'font_stretch', 'stretch'], 'normal')];
$hasFile = \false;
foreach (['woff2', 'woff', 'ttf', 'otf', 'eot'] as $extension) {
$source = $this->first_meta($fontId, ['font_face_file_' . $extension, 'font_file_' . $extension, $extension], null);
if (is_numeric($source) && (int) $source > 0) {
$source = ['id' => (int) $source, 'url' => wp_get_attachment_url((int) $source) ?: ''];
} elseif (is_array($source) && empty($source['url']) && !empty($source['id'])) {
$source['url'] = wp_get_attachment_url((int) $source['id']) ?: '';
}
if (is_string($source) && $source !== '' || is_array($source) && !empty($source['url'])) {
$variant[$extension] = $source;
$hasFile = \true;
}
}
return $hasFile ? $variant : [];
}
/**
* @param string[] $keys
* @return mixed
*/
private function first_meta(int $fontId, array $keys, $default)
{
foreach ($keys as $key) {
$value = get_post_meta($fontId, $key, \true);
if ($value !== '' && $value !== null && $value !== \false) {
return $value;
}
}
return $default;
}
/**
* @param array<string, mixed> $sourceFile
* @return array<string, mixed>
*/
private function import_file(MediaImportService $media, array $sourceFile, string $fileName): array
{
$location = (string) ($sourceFile['location'] ?? '');
$extension = (string) ($sourceFile['extension'] ?? '');
$attachmentId = (int) ($sourceFile['attachment_id'] ?? attachment_url_to_postid($location));
$path = $attachmentId > 0 ? get_attached_file($attachmentId) : \false;
if (is_string($path) && is_readable($path)) {
return $media->local($path, $fileName, $extension);
}
return $media->remote($location, $fileName, $extension);
}
}
@@ -0,0 +1,221 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Api\Migrations;
use JooosiFon\Api\AbstractApi;
use JooosiFon\Api\ApiInterface;
use JooosiFon\Api\Migrations\Support\SourceFontNormalizer;
use JooosiFon\Api\Support\FontCodec;
use JooosiFon\Api\Support\FontEvents;
use JooosiFon\Api\Support\FontRepository;
use JooosiFon\Api\Support\MediaImportService;
use JooosiFon\Api\Support\RequestValidator;
use JooosiFon\Utils\Common;
use JooosiFon\Utils\Upload;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;
final class FontsPlugin extends AbstractApi implements ApiInterface
{
private const TAXONOMY = 'ogf_custom_fonts';
public function get_prefix(): string
{
return 'migrations/fonts-plugin';
}
public function register_custom_endpoints(): void
{
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/import-fonts', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(WP_REST_Request $request): WP_REST_Response => $this->import_fonts($request), 'permission_callback' => fn(WP_REST_Request $request): bool => $this->permission_callback($request)]);
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/clean-up', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(WP_REST_Request $request): WP_REST_Response => $this->clean_up($request), 'permission_callback' => fn(WP_REST_Request $request): bool => $this->permission_callback($request), 'args' => ['confirm' => ['required' => \true, 'sanitize_callback' => 'rest_sanitize_boolean', 'validate_callback' => [RequestValidator::class, 'confirmed']]]]);
}
public function import_fonts(WP_REST_Request $request): WP_REST_Response
{
if (!$this->is_active()) {
return new WP_REST_Response(['message' => __('Fonts Plugin is not activated.', 'jooosi-fon')], 404);
}
$terms = $this->source_terms();
if (is_wp_error($terms)) {
return new WP_REST_Response(['message' => __('Fonts Plugin records could not be read.', 'jooosi-fon')], 500);
}
$rows = [];
foreach ($terms as $term) {
$data = get_option($this->term_option_name((int) $term->term_id), []);
if (!is_array($data)) {
continue;
}
$rows[] = array_merge($data, ['source_key' => (string) $term->slug, 'name' => (string) $term->name]);
}
$families = SourceFontNormalizer::fontsPlugin($rows, $this->selector_assignments(), (string) get_theme_mod('ogf_font_display', 'swap'));
$normalizedFaceCount = array_sum(array_map(static fn(array $family): int => count($family['faces']), $families));
$skipped = max(0, count($terms) - $normalizedFaceCount);
add_filter('wp_check_filetype_and_ext', static fn($data, $file, $filename, $mimes) => Upload::disable_real_mime_check($data, $file, $filename, $mimes), 10, 4);
add_filter('upload_mimes', static fn($mimeTypes) => Upload::upload_mimes($mimeTypes, \true), 1000001);
$repository = new FontRepository();
$media = new MediaImportService();
$records = [];
$insertedIds = [];
try {
foreach ($families as $sourceFamily) {
$family = sanitize_text_field((string) $sourceFamily['family']);
$familySlug = sanitize_title_with_dashes($family);
if ($family === '' || $familySlug === '') {
++$skipped;
continue;
}
$migrationSlug = 'migration-fonts-plugin-' . $familySlug;
if ($repository->findBySlug($migrationSlug)) {
continue;
}
$fontFaces = [];
foreach ($sourceFamily['faces'] as $sourceFace) {
$files = [];
foreach ($sourceFace['files'] as $sourceFile) {
$fileName = sanitize_title_with_dashes(sprintf('%s-%s-%s-%s-%s', $family, $sourceFace['weight'], $sourceFace['style'], Common::random_slug(5), time())) . '.' . $sourceFile['extension'];
$files[] = $this->import_file($media, $sourceFile, $fileName);
}
if ($files === []) {
++$skipped;
continue;
}
$fontFaces[] = ['id' => Common::random_slug(10), 'weight' => $sourceFace['weight'], 'width' => $sourceFace['width'], 'style' => $sourceFace['style'], 'display' => '', 'selector' => '', 'comment' => '', 'unicodeRange' => '', 'preload' => (bool) $sourceFace['preload'], 'files' => $files];
}
if ($fontFaces === []) {
++$skipped;
continue;
}
$records[] = ['type' => 'custom', 'title' => $family, 'slug' => $migrationSlug, 'family' => $family, 'status' => \true, 'metadata' => FontCodec::encode(['preload' => (bool) $sourceFamily['preload'], 'selector' => $sourceFamily['selector'], 'display' => $sourceFamily['display']]), 'font_faces' => FontCodec::encode($fontFaces)];
}
if ($skipped > 0) {
$media->rollback();
return new WP_REST_Response(['message' => __('Some Fonts Plugin variants had no supported font files. Nothing was imported so the source records remain safe.', 'jooosi-fon'), 'skipped' => $skipped], 422);
}
$insertedIds = $repository->transaction(static function (FontRepository $repository) use ($records): array {
$ids = [];
foreach ($records as $record) {
$ids[] = $repository->insert($record, ['%s', '%s', '%s', '%s', '%d', '%s', '%s']);
}
return $ids;
});
} catch (\Throwable $throwable) {
$media->rollback();
return new WP_REST_Response(['message' => __('The Fonts Plugin migration failed; newly created Jooosi Fon records were rolled back.', 'jooosi-fon')], 500);
}
$media->commit();
FontEvents::dispatch('migration', ['source' => 'fonts-plugin', 'ids' => $insertedIds], \true);
return new WP_REST_Response(['message' => __('Fonts Plugin uploaded families imported. Source records were preserved.', 'jooosi-fon'), 'imported' => count($insertedIds), 'skipped' => $skipped, 'source_preserved' => \true]);
}
public function clean_up(WP_REST_Request $request): WP_REST_Response
{
if (!$this->is_active()) {
return new WP_REST_Response(['message' => __('Fonts Plugin is not activated.', 'jooosi-fon')], 404);
}
$terms = $this->source_terms();
if (is_wp_error($terms)) {
return new WP_REST_Response(['message' => __('Fonts Plugin records could not be read.', 'jooosi-fon')], 500);
}
global $wpdb;
if ($wpdb->query('START TRANSACTION') === \false) {
return new WP_REST_Response(['message' => __('Fonts Plugin cleanup could not start a database transaction.', 'jooosi-fon')], 500);
}
$termIds = array_map(static fn($term): int => (int) $term->term_id, $terms);
$termOptionNames = array_map(fn(int $termId): string => $this->term_option_name($termId), $termIds);
$assignedThemeMods = $this->assigned_theme_mods();
try {
foreach ($terms as $term) {
delete_option($this->term_option_name((int) $term->term_id));
$deleted = wp_delete_term((int) $term->term_id, self::TAXONOMY);
if ($deleted === \false || is_wp_error($deleted)) {
throw new \RuntimeException('A Fonts Plugin term could not be deleted.');
}
}
foreach (array_keys($assignedThemeMods) as $themeMod) {
remove_theme_mod($themeMod);
}
if ($wpdb->query('COMMIT') === \false) {
throw new \RuntimeException($wpdb->last_error ?: 'Fonts Plugin cleanup could not be committed.');
}
} catch (\Throwable $throwable) {
$wpdb->query('ROLLBACK');
clean_term_cache($termIds, self::TAXONOMY);
foreach ($termOptionNames as $termOptionName) {
wp_cache_delete($termOptionName, 'options');
}
foreach ($assignedThemeMods as $themeMod => $value) {
set_theme_mod($themeMod, $value);
}
return new WP_REST_Response(['message' => __('Fonts Plugin cleanup failed and the source transaction was rolled back.', 'jooosi-fon')], 500);
}
FontEvents::dispatch('clean_up', ['source' => 'fonts-plugin', 'ids' => $termIds], \true);
return new WP_REST_Response(['message' => __('Fonts Plugin uploaded-font records and their selector assignments were removed. Original media files were left in place.', 'jooosi-fon'), 'cleaned' => count($termIds)]);
}
private function is_active(): bool
{
return defined('OGF_VERSION') && taxonomy_exists(self::TAXONOMY) && function_exists('ogf_get_elements') && function_exists('ogf_get_custom_elements');
}
/**
* @return array<int, object>|\WP_Error
*/
private function source_terms()
{
return get_terms(['taxonomy' => self::TAXONOMY, 'hide_empty' => \false]);
}
/**
* @return array<int, array{source_key: string, selector: string}>
*/
private function selector_assignments(): array
{
$assignments = [];
foreach ($this->source_elements() as $elementId => $element) {
$fontId = get_theme_mod((string) $elementId . '_font', '');
if (!is_string($fontId) || strpos($fontId, 'cf-') !== 0) {
continue;
}
$selector = is_array($element) ? $element['selectors'] ?? '' : '';
$assignments[] = ['source_key' => substr($fontId, 3), 'selector' => is_string($selector) ? $selector : ''];
}
return $assignments;
}
/**
* @return array<string, mixed>
*/
private function assigned_theme_mods(): array
{
$themeMods = [];
foreach ($this->source_elements() as $elementId => $element) {
$themeMod = (string) $elementId . '_font';
$value = get_theme_mod($themeMod, null);
if (is_string($value) && strpos($value, 'cf-') === 0) {
$themeMods[$themeMod] = $value;
}
}
return $themeMods;
}
/**
* @return array<string, mixed>
*/
private function source_elements(): array
{
$standard = ogf_get_elements();
$custom = ogf_get_custom_elements();
return array_merge(is_array($standard) ? $standard : [], is_array($custom) ? $custom : []);
}
private function term_option_name(int $termId): string
{
return 'taxonomy_' . self::TAXONOMY . '_' . $termId;
}
/**
* @param array<string, mixed> $sourceFile
* @return array<string, mixed>
*/
private function import_file(MediaImportService $media, array $sourceFile, string $fileName): array
{
$location = (string) ($sourceFile['location'] ?? '');
$extension = (string) ($sourceFile['extension'] ?? '');
$attachmentId = (int) ($sourceFile['attachment_id'] ?? attachment_url_to_postid($location));
$path = $attachmentId > 0 ? get_attached_file($attachmentId) : \false;
if (is_string($path) && is_readable($path)) {
return $media->local($path, $fileName, $extension);
}
return $media->remote($location, $fileName, $extension);
}
}
@@ -0,0 +1,310 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Api\Migrations\Support;
/**
* Converts third-party plugin records into a small, source-agnostic shape.
* Keeping this work free of WordPress side effects makes the source schemas
* straightforward to test without booting a complete WordPress installation.
*/
final class SourceFontNormalizer
{
private const SUPPORTED_EXTENSIONS = ['woff2', 'woff', 'ttf', 'otf', 'eot'];
/**
* @param array<string, mixed> $fontData
* @return array{
* display: string,
* fallback: string,
* skipped: int,
* faces: array<int, array{
* weight: string,
* width: string,
* style: string,
* files: array<int, array{location: string, extension: string}>
* }>
* }
*/
public static function brainstormForce(array $fontData): array
{
$faces = [];
$skipped = 0;
$variations = isset($fontData['variations']) && is_array($fontData['variations']) ? $fontData['variations'] : [];
foreach ($variations as $variation) {
if (!is_array($variation)) {
++$skipped;
continue;
}
$weightSource = (string) ($variation['font_weight'] ?? '400');
$files = self::remoteFiles($variation['font_url'] ?? []);
if ($files === []) {
++$skipped;
continue;
}
$faces[] = ['weight' => self::weight($weightSource), 'width' => '100%', 'style' => self::style((string) ($variation['font_style'] ?? ''), $weightSource), 'files' => $files];
}
$display = $fontData['font_display'] ?? 'auto';
$fallback = $fontData['font_fallback'] ?? '';
return ['display' => self::display(is_string($display) ? $display : 'auto'), 'fallback' => is_string($fallback) ? trim($fallback) : '', 'skipped' => $skipped, 'faces' => $faces];
}
/**
* @param array<string|int, mixed> $fontRows
* @param array<string|int, mixed> $assignments
* @return array<string, array{
* family: string,
* display: string,
* selector: string,
* faces: array<int, array{
* source_key: string,
* weight: string,
* width: string,
* style: string,
* files: array<int, array{location: string, extension: string}>
* }>
* }>
*/
public static function useAnyFont(array $fontRows, array $assignments, string $baseDirectory, string $display): array
{
$families = [];
$rowFamilies = [];
$baseDirectory = rtrim($baseDirectory, '/\\') . \DIRECTORY_SEPARATOR;
foreach ($fontRows as $sourceKey => $fontRow) {
if (!is_array($fontRow)) {
continue;
}
$family = trim((string) ($fontRow['font_name'] ?? ''));
$fontPath = basename(str_replace('\\', '/', trim((string) ($fontRow['font_path'] ?? ''))));
if ($family === '' || $fontPath === '') {
continue;
}
if (!isset($families[$family])) {
$families[$family] = ['family' => $family, 'display' => self::display($display), 'selector' => '', 'faces' => []];
}
$key = (string) $sourceKey;
$rowFamilies[$key] = $family;
$files = [];
foreach (['woff2', 'woff', 'eot'] as $extension) {
$files[] = ['location' => $baseDirectory . $fontPath . '.' . $extension, 'extension' => $extension];
}
$families[$family]['faces'][] = ['source_key' => $key, 'weight' => self::weight((string) ($fontRow['font_weight'] ?? '400')), 'width' => self::width((string) ($fontRow['font_stretch'] ?? 'normal')), 'style' => self::style((string) ($fontRow['font_style'] ?? '')), 'files' => $files];
}
$selectors = [];
foreach ($assignments as $assignment) {
if (!is_array($assignment)) {
continue;
}
$family = trim((string) ($assignment['font_name'] ?? ''));
$sourceKey = (string) ($assignment['font_key'] ?? '');
if ($family === '' && isset($rowFamilies[$sourceKey])) {
$family = $rowFamilies[$sourceKey];
}
$selector = self::selector((string) ($assignment['font_elements'] ?? ''));
if ($family === '' || $selector === '' || !isset($families[$family])) {
continue;
}
$selectors[$family][] = $selector;
}
foreach ($selectors as $family => $familySelectors) {
$families[$family]['selector'] = self::selector(implode(', ', array_unique($familySelectors)));
}
return $families;
}
/**
* @param array<int, array<string, mixed>> $fontRows
* @param array<int, array<string, mixed>> $assignments
* @return array<string, array<string, mixed>>
*/
public static function fontsPlugin(array $fontRows, array $assignments, string $display): array
{
$families = [];
$rowFamilies = [];
foreach ($fontRows as $fontRow) {
if (!is_array($fontRow)) {
continue;
}
$family = trim(self::stringValue($fontRow['family'] ?? ''));
if ($family === '') {
$family = trim(self::stringValue($fontRow['name'] ?? ''));
}
$sourceKey = trim(self::stringValue($fontRow['source_key'] ?? $fontRow['slug'] ?? ''));
$files = self::remoteFiles([$fontRow['woff2'] ?? '', $fontRow['woff'] ?? '', $fontRow['ttf'] ?? '', $fontRow['otf'] ?? '', $fontRow['eot'] ?? '']);
if ($family === '' || $files === []) {
continue;
}
if (!isset($families[$family])) {
$families[$family] = ['family' => $family, 'display' => self::display($display), 'selector' => '', 'preload' => \false, 'faces' => []];
}
if ($sourceKey !== '') {
$rowFamilies[$sourceKey] = $family;
}
$preload = filter_var($fontRow['preload'] ?? \false, \FILTER_VALIDATE_BOOLEAN);
$families[$family]['preload'] = $families[$family]['preload'] || $preload;
$families[$family]['faces'][] = ['source_key' => $sourceKey, 'weight' => self::weight(self::stringValue($fontRow['weight'] ?? '400', '400')), 'width' => self::width(self::stringValue($fontRow['stretch'] ?? 'normal', 'normal')), 'style' => self::style(self::stringValue($fontRow['style'] ?? 'normal', 'normal')), 'preload' => $preload, 'files' => $files];
}
$selectors = [];
foreach ($assignments as $assignment) {
if (!is_array($assignment)) {
continue;
}
$sourceKey = trim(self::stringValue($assignment['source_key'] ?? ''));
$family = trim(self::stringValue($assignment['family'] ?? ''));
if ($family === '' && isset($rowFamilies[$sourceKey])) {
$family = $rowFamilies[$sourceKey];
}
$selector = self::selector(self::stringValue($assignment['selector'] ?? ''));
if ($family !== '' && $selector !== '' && isset($families[$family])) {
$selectors[$family][] = $selector;
}
}
foreach ($selectors as $family => $familySelectors) {
$families[$family]['selector'] = self::selector(implode(', ', array_unique($familySelectors)));
}
return $families;
}
/**
* @param array<int, mixed> $variants
* @return array{display: string, skipped: int, faces: array<int, array<string, mixed>>}
*/
public static function elementor(array $variants, string $display = 'auto'): array
{
$faces = [];
$skipped = 0;
foreach ($variants as $variant) {
if (!is_array($variant)) {
++$skipped;
continue;
}
$fontWeight = (string) ($variant['font_weight'] ?? $variant['weight'] ?? '400');
$files = [];
foreach (self::SUPPORTED_EXTENSIONS as $extension) {
$source = $variant[$extension] ?? $variant['font_face_file_' . $extension] ?? null;
if (is_array($source)) {
$source = ['url' => $source['url'] ?? $source['location'] ?? '', 'id' => $source['id'] ?? $source['attachment_id'] ?? 0];
}
$files[] = $source;
}
$files = self::remoteFiles($files);
if ($files === []) {
++$skipped;
continue;
}
$faces[] = ['weight' => self::weight($fontWeight), 'width' => self::width((string) ($variant['font_stretch'] ?? $variant['stretch'] ?? 'normal')), 'style' => self::style((string) ($variant['font_style'] ?? $variant['style'] ?? 'normal'), $fontWeight), 'preload' => filter_var($variant['preload'] ?? \false, \FILTER_VALIDATE_BOOLEAN), 'files' => $files];
}
return ['display' => self::display($display), 'skipped' => $skipped, 'faces' => $faces];
}
/**
* @param array<string, mixed> $source
* @return array{id: string, families: array<int, array<string, mixed>>}
*/
public static function customAdobeKit(array $source): array
{
$projectId = trim(self::stringValue($source['custom-typekit-font-id'] ?? ''));
$details = isset($source['custom-typekit-font-details']) && is_array($source['custom-typekit-font-details']) ? $source['custom-typekit-font-details'] : [];
$families = [];
foreach ($details as $sourceName => $detail) {
if (!is_array($detail)) {
continue;
}
$cssNames = array_values(array_filter(array_map('strval', (array) ($detail['css_names'] ?? [])), static fn(string $name): bool => trim($name) !== ''));
$slug = trim((string) ($detail['slug'] ?? $cssNames[0] ?? ''));
$family = trim((string) ($detail['family'] ?? $sourceName));
if ($slug === '' || $family === '') {
continue;
}
$name = ucwords(str_replace(['-', '_'], ' ', $family));
$weights = array_values(array_unique(array_map(static fn($weight): string => self::weight((string) $weight), (array) ($detail['weights'] ?? []))));
$families[] = ['id' => $slug, 'name' => $name, 'slug' => $cssNames[0] ?? $slug, 'css_names' => $cssNames, 'css_stack' => trim((string) ($detail['fallback'] ?? '')), 'weights' => $weights];
}
return ['id' => $projectId, 'families' => $families];
}
/**
* @param mixed $urls
* @return array<int, array{location: string, extension: string, attachment_id?: int}>
*/
private static function remoteFiles($urls): array
{
if (is_string($urls)) {
$urls = [$urls];
}
if (!is_array($urls)) {
return [];
}
$files = [];
$seenExtensions = [];
foreach ($urls as $url) {
$attachmentId = 0;
if (is_array($url)) {
$attachmentId = max(0, (int) ($url['id'] ?? $url['attachment_id'] ?? 0));
$url = $url['url'] ?? $url['location'] ?? '';
}
if (!is_string($url) || trim($url) === '') {
continue;
}
$path = parse_url(trim($url), \PHP_URL_PATH);
$extension = is_string($path) ? strtolower(pathinfo($path, \PATHINFO_EXTENSION)) : '';
if (!in_array($extension, self::SUPPORTED_EXTENSIONS, \true) || isset($seenExtensions[$extension])) {
continue;
}
$file = ['location' => trim($url), 'extension' => $extension];
if ($attachmentId > 0) {
$file['attachment_id'] = $attachmentId;
}
$seenExtensions[$extension] = \true;
$files[] = $file;
}
return $files;
}
private static function display(string $display): string
{
$display = strtolower(trim($display));
return in_array($display, ['auto', 'block', 'swap', 'fallback', 'optional'], \true) ? $display : 'auto';
}
/**
* @param mixed $value
*/
private static function stringValue($value, string $default = ''): string
{
return is_string($value) || is_int($value) || is_float($value) ? (string) $value : $default;
}
private static function style(string $style, string $weight = ''): string
{
$style = strtolower(trim($style));
if ($style === 'italic' || stripos($weight, 'italic') !== \false) {
return 'italic';
}
return $style === 'oblique' ? 'oblique' : 'normal';
}
private static function weight(string $weight): string
{
$weight = strtolower(trim($weight));
if ($weight === 'normal' || $weight === 'regular') {
return '400';
}
if ($weight === 'bold') {
return '700';
}
if (preg_match('/^([1-9]\d{0,3})(?:\s+([1-9]\d{0,3}))?/', $weight, $matches) !== 1) {
return '400';
}
$minimum = (int) $matches[1];
$maximum = isset($matches[2]) ? (int) $matches[2] : null;
if ($minimum > 1000 || $maximum !== null && ($maximum > 1000 || $minimum > $maximum)) {
return '400';
}
return $maximum === null ? (string) $minimum : $minimum . ' ' . $maximum;
}
private static function width(string $stretch): string
{
$widths = ['ultra-condensed' => '50%', 'extra-condensed' => '62.5%', 'condensed' => '75%', 'semi-condensed' => '87.5%', 'normal' => '100%', 'semi-expanded' => '112.5%', 'expanded' => '125%', 'extra-expanded' => '150%', 'ultra-expanded' => '200%'];
$stretch = strtolower(trim($stretch));
return $widths[$stretch] ?? '100%';
}
private static function selector(string $selector): string
{
$selector = trim($selector);
if ($selector === '' || strlen($selector) > 1000 || preg_match('/[<{};@]|\/\*|\*\/|[\x00-\x08\x0B\x0C\x0E-\x1F]/', $selector) !== 0) {
return '';
}
return $selector;
}
}
@@ -0,0 +1,183 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Api\Migrations;
use JooosiFon\Api\AbstractApi;
use JooosiFon\Api\ApiInterface;
use JooosiFon\Api\Migrations\Support\SourceFontNormalizer;
use JooosiFon\Api\Support\FontCodec;
use JooosiFon\Api\Support\FontEvents;
use JooosiFon\Api\Support\FontRepository;
use JooosiFon\Api\Support\MediaImportService;
use JooosiFon\Api\Support\RequestValidator;
use JooosiFon\Utils\Common;
use JooosiFon\Utils\Upload;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;
final class UseAnyFont extends AbstractApi implements ApiInterface
{
public function get_prefix(): string
{
return 'migrations/use-any-font';
}
public function register_custom_endpoints(): void
{
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/import-fonts', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(WP_REST_Request $request): WP_REST_Response => $this->import_fonts($request), 'permission_callback' => fn(WP_REST_Request $request): bool => $this->permission_callback($request)]);
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/clean-up', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(WP_REST_Request $request): WP_REST_Response => $this->clean_up($request), 'permission_callback' => fn(WP_REST_Request $request): bool => $this->permission_callback($request), 'args' => ['confirm' => ['required' => \true, 'sanitize_callback' => 'rest_sanitize_boolean', 'validate_callback' => [RequestValidator::class, 'confirmed']]]]);
}
public function import_fonts(WP_REST_Request $request): WP_REST_Response
{
if (!$this->is_active()) {
return new WP_REST_Response(['message' => __('Use Any Font is not activated.', 'jooosi-fon')], 404);
}
$fontRows = $this->decode_option('uaf_font_data');
$assignments = $this->decode_option('uaf_font_implement');
if ($fontRows === null || $assignments === null) {
return new WP_REST_Response(['message' => __('Use Any Font records could not be read.', 'jooosi-fon')], 500);
}
/** @var array{dir?: mixed} $paths */
$paths = uaf_path_details();
$directory = isset($paths['dir']) && is_string($paths['dir']) ? $paths['dir'] : '';
if ($directory === '') {
return new WP_REST_Response(['message' => __('Use Any Font storage could not be located.', 'jooosi-fon')], 500);
}
$families = SourceFontNormalizer::useAnyFont($fontRows, $assignments, $directory, (string) get_option('uaf_font_display_property', 'auto'));
add_filter('wp_check_filetype_and_ext', static fn($data, $file, $filename, $mimes) => Upload::disable_real_mime_check($data, $file, $filename, $mimes), 10, 4);
add_filter('upload_mimes', static fn($mimeTypes) => Upload::upload_mimes($mimeTypes, \true), 1000001);
$repository = new FontRepository();
$media = new MediaImportService();
$records = [];
$insertedIds = [];
$normalizedFaceCount = array_sum(array_map(static fn(array $sourceFamily): int => count($sourceFamily['faces']), $families));
$skipped = max(0, count($fontRows) - $normalizedFaceCount);
try {
foreach ($families as $sourceFamily) {
$family = sanitize_text_field($sourceFamily['family']);
$familySlug = sanitize_title_with_dashes($family);
if ($family === '' || $familySlug === '') {
++$skipped;
continue;
}
$migrationSlug = 'migration-use-any-font-' . $familySlug;
if ($repository->findBySlug($migrationSlug)) {
continue;
}
$fontFaces = [];
foreach ($sourceFamily['faces'] as $sourceFace) {
$files = [];
foreach ($sourceFace['files'] as $sourceFile) {
if (!is_file($sourceFile['location']) || !is_readable($sourceFile['location'])) {
continue;
}
$fileName = sanitize_title_with_dashes(sprintf('%s-%s-%s-%s-%s', $family, $sourceFace['weight'], $sourceFace['style'], Common::random_slug(5), time())) . '.' . $sourceFile['extension'];
$files[] = $media->local($sourceFile['location'], $fileName, $sourceFile['extension']);
}
if ($files === []) {
++$skipped;
continue;
}
$fontFaces[] = ['id' => Common::random_slug(10), 'weight' => $sourceFace['weight'], 'width' => $sourceFace['width'], 'style' => $sourceFace['style'], 'display' => '', 'selector' => '', 'comment' => '', 'unicodeRange' => '', 'preload' => \false, 'files' => $files];
}
if ($fontFaces === []) {
++$skipped;
continue;
}
$records[] = ['type' => 'custom', 'title' => $family, 'slug' => $migrationSlug, 'family' => $family, 'status' => \true, 'metadata' => FontCodec::encode(['preload' => \false, 'selector' => $sourceFamily['selector'], 'display' => $sourceFamily['display']]), 'font_faces' => FontCodec::encode($fontFaces)];
}
if ($skipped > 0) {
$media->rollback();
return new WP_REST_Response(['message' => __('Some Use Any Font records had no supported, readable files. Nothing was imported so the source records remain safe.', 'jooosi-fon'), 'skipped' => $skipped], 422);
}
$insertedIds = $repository->transaction(static function (FontRepository $repository) use ($records): array {
$ids = [];
foreach ($records as $record) {
$ids[] = $repository->insert($record, ['%s', '%s', '%s', '%s', '%d', '%s', '%s']);
}
return $ids;
});
} catch (\Throwable $throwable) {
$media->rollback();
return new WP_REST_Response(['message' => __('The Use Any Font migration failed; newly created Jooosi Fon records were rolled back.', 'jooosi-fon')], 500);
}
$media->commit();
FontEvents::dispatch('migration', ['source' => 'use-any-font', 'ids' => $insertedIds], \true);
return new WP_REST_Response(['message' => __('Use Any Font families imported. Source records were preserved.', 'jooosi-fon'), 'imported' => count($insertedIds), 'skipped' => $skipped, 'source_preserved' => \true]);
}
public function clean_up(WP_REST_Request $request): WP_REST_Response
{
if (!$this->is_active()) {
return new WP_REST_Response(['message' => __('Use Any Font is not activated.', 'jooosi-fon')], 404);
}
$fontData = get_option('uaf_font_data', null);
$assignments = get_option('uaf_font_implement', null);
try {
$this->replace_option('uaf_font_data', $fontData, '[]');
$this->replace_option('uaf_font_implement', $assignments, '[]');
if (function_exists('uaf_write_css')) {
uaf_write_css();
}
} catch (\Throwable $throwable) {
$this->restore_option('uaf_font_data', $fontData);
$this->restore_option('uaf_font_implement', $assignments);
return new WP_REST_Response(['message' => __('Use Any Font cleanup failed and the source options were restored.', 'jooosi-fon')], 500);
}
$decodedFontData = $this->decode_value($fontData);
$cleaned = is_array($decodedFontData) ? count($decodedFontData) : 0;
FontEvents::dispatch('clean_up', ['source' => 'use-any-font'], \true);
return new WP_REST_Response(['message' => __('Use Any Font source records and selector assignments were removed. Original font files were left in place.', 'jooosi-fon'), 'cleaned' => $cleaned]);
}
private function is_active(): bool
{
return defined('UAF_FILE_PATH') && function_exists('uaf_path_details');
}
/**
* @return array<string|int, mixed>|null
*/
private function decode_option(string $option): ?array
{
return $this->decode_value(get_option($option, '[]'));
}
/**
* @param mixed $value
* @return array<string|int, mixed>|null
*/
private function decode_value($value): ?array
{
if (is_array($value)) {
return $value;
}
if ($value === \false || $value === null || $value === '') {
return [];
}
if (!is_string($value)) {
return null;
}
$decoded = json_decode($value, \true);
return is_array($decoded) ? $decoded : null;
}
/**
* @param mixed $original
*/
private function replace_option(string $option, $original, string $replacement): void
{
if ($original === $replacement) {
return;
}
if (!update_option($option, $replacement)) {
throw new \RuntimeException('The Use Any Font source option could not be updated.');
}
}
/**
* @param mixed $value
*/
private function restore_option(string $option, $value): void
{
if ($value === null || $value === \false) {
delete_option($option);
return;
}
update_option($option, $value);
}
}
@@ -0,0 +1,126 @@
<?php
/*
* This file is part of the Jooosi Fon package.
*
* (c) Joshua Gugun Siagian <suabahasa@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare (strict_types=1);
namespace JooosiFon\Api;
use JooosiFon\Api\Migrations\BrainstormForceCustomFonts;
use JooosiFon\Api\Migrations\BricksCustomFonts;
use JooosiFon\Api\Migrations\CustomAdobeFonts;
use JooosiFon\Api\Migrations\DpluginsFontHero;
use JooosiFon\Api\Migrations\ElementorProCustomFonts;
use JooosiFon\Api\Migrations\FontsPlugin;
use JooosiFon\Api\Migrations\UseAnyFont;
use JooosiFon\Api\Setting\AdobeFonts;
use JooosiFon\Api\Setting\Cache;
use JooosiFon\Api\Setting\License;
use JooosiFon\Api\Setting\Option;
use ReflectionClass;
use JooosiFonDeps\Symfony\Component\Finder\Finder;
/**
* @todo Remove all legacy Yabe Webfont hook shims completely in Jooosi Fon 3.0.0.
*/
class Router
{
/**
* @var array<string, array{name: string, file_path: string|false, class_name: class-string<ApiInterface>}>
*/
private array $apis = [];
public function __construct()
{
$this->scan_apis();
add_action('rest_api_init', function (): void {
$this->register_apis();
});
}
public function scan_apis(): void
{
/** @param array<string, class-string<ApiInterface>> $classes */
$classes = apply_filters('f!jooosi/fon/api/router:classes', ['fonts' => \JooosiFon\Api\Font::class, 'setting/adobe-fonts' => AdobeFonts::class, 'setting/cache' => Cache::class, 'setting/license' => License::class, 'setting/option' => Option::class, 'migrations/bricks-custom-fonts' => BricksCustomFonts::class, 'migrations/brainstorm-force-custom-fonts' => BrainstormForceCustomFonts::class, 'migrations/custom-adobe-fonts' => CustomAdobeFonts::class, 'migrations/elementor-pro-custom-fonts' => ElementorProCustomFonts::class, 'migrations/font-hero-dplugins' => DpluginsFontHero::class, 'migrations/fonts-plugin' => FontsPlugin::class, 'migrations/use-any-font' => UseAnyFont::class]);
$classes = apply_filters_deprecated('f!yabe/webfont/api/router:classes', [$classes], '2.1.0', 'f!jooosi/fon/api/router:classes');
foreach ((array) $classes as $prefix => $className) {
$this->addApi((string) $prefix, $className);
}
$this->scanLegacyExtensionDirectories();
}
public function register_apis(): void
{
/** @var array<string, array{name: string, file_path: string|false, class_name: class-string<ApiInterface>}> $apis */
$apis = apply_filters('f!jooosi/fon/api/router:register_apis', $this->apis);
$apis = apply_filters_deprecated('f!yabe/webfont/api/router:register_apis', [$apis], '2.1.0', 'f!jooosi/fon/api/router:register_apis');
foreach ((array) $apis as $api) {
$className = $api['class_name'] ?? null;
if (!is_string($className) || !is_a($className, \JooosiFon\Api\ApiInterface::class, \true)) {
do_action('a!jooosi/fon/api/router:invalid_api', $api);
continue;
}
$reflector = new ReflectionClass($className);
if (!$reflector->isInstantiable()) {
do_action('a!jooosi/fon/api/router:invalid_api', $api);
continue;
}
/** @var ApiInterface $instance */
$instance = $reflector->newInstance();
$instance->register_custom_endpoints();
}
}
/**
* @param mixed $className
*/
private function addApi(string $prefix, $className): void
{
if ($prefix === '' || !is_string($className) || !is_a($className, \JooosiFon\Api\ApiInterface::class, \true)) {
do_action('a!jooosi/fon/api/router:invalid_api', $prefix, $className);
return;
}
$reflector = new ReflectionClass($className);
if (!$reflector->isInstantiable()) {
do_action('a!jooosi/fon/api/router:invalid_api', $prefix, $className);
return;
}
$this->apis[$prefix] = ['name' => $prefix, 'file_path' => $reflector->getFileName(), 'class_name' => $className];
}
/**
* Compatibility path for extensions still using the old Finder hook. It is
* only activated when a listener exists and is never cached, preventing a
* class name from surviving without its defining file on the next request.
*
* @todo Remove this legacy extension scan completely in Jooosi Fon 3.0.0.
*/
private function scanLegacyExtensionDirectories(): void
{
$hook = 'a!jooosi/fon/api/router:before_scan';
$legacyHook = 'a!yabe/webfont/api/router:before_scan';
if (!has_action($hook) && !has_action($legacyHook)) {
return;
}
$finder = new Finder();
$finder->files()->in(__DIR__)->name('*.php');
do_action($hook, $finder);
do_action_deprecated($legacyHook, [$finder], '2.1.0', $hook);
foreach ($finder as $file) {
if ($file->isReadable()) {
require_once $file->getPathname();
}
}
foreach (get_declared_classes() as $className) {
if (!is_a($className, \JooosiFon\Api\ApiInterface::class, \true)) {
continue;
}
$reflector = new ReflectionClass($className);
if (!$reflector->isInstantiable()) {
continue;
}
/** @var ApiInterface $instance */
$instance = $reflector->newInstanceWithoutConstructor();
$this->addApi($instance->get_prefix(), $className);
}
}
}
@@ -0,0 +1,88 @@
<?php
/*
* This file is part of the Jooosi Fon package.
*
* (c) Joshua Gugun Siagian <suabahasa@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare (strict_types=1);
namespace JooosiFon\Api\Setting;
use JooosiFon\Api\AbstractApi;
use JooosiFon\Api\ApiInterface;
use JooosiFon\Api\Support\FontCodec;
use JooosiFon\Api\Support\FontEvents;
use JooosiFon\Api\Support\FontRepository;
use JooosiFon\Api\Support\RequestValidator;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;
class AdobeFonts extends AbstractApi implements ApiInterface
{
public function __construct()
{
}
public function get_prefix(): string
{
return 'setting/adobe-fonts';
}
public function register_custom_endpoints(): void
{
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/get-kits', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->get_kits($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest), 'args' => ['project_id' => ['required' => \true, 'sanitize_callback' => 'sanitize_text_field', 'validate_callback' => [RequestValidator::class, 'projectId']]]]);
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/sync', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->sync($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest), 'args' => ['kit' => ['required' => \true, 'validate_callback' => [RequestValidator::class, 'adobeKit']]]]);
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/destroy', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->destroy($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest)]);
}
public function get_kits(WP_REST_Request $wprestRequest): WP_REST_Response
{
$project_id = (string) $wprestRequest->get_param('project_id');
$response = wp_safe_remote_get(sprintf('https://typekit.com/api/v1/json/kits/%s/published', rawurlencode($project_id)), ['timeout' => 15, 'redirection' => 2, 'limit_response_size' => 2 * \MB_IN_BYTES]);
if (is_wp_error($response)) {
return new WP_REST_Response(['message' => 'Failed to get kits'], 500);
}
$status_code = wp_remote_retrieve_response_code($response);
if ($status_code !== 200) {
return new WP_REST_Response(['message' => 'Kits not found'], $status_code);
}
$body = wp_remote_retrieve_body($response);
try {
$kits = json_decode($body, \true, 512, \JSON_THROW_ON_ERROR);
} catch (\JsonException $exception) {
return new WP_REST_Response(['message' => __('Adobe Fonts returned an invalid response.', 'jooosi-fon')], 502);
}
return new WP_REST_Response(['data' => $kits]);
}
public function sync(WP_REST_Request $wprestRequest): WP_REST_Response
{
$kit = (array) $wprestRequest->get_param('kit');
$repository = new FontRepository();
try {
$repository->transaction(static function (FontRepository $repository) use ($kit): void {
$repository->deleteByType('adobe-fonts');
foreach ($kit['families'] as $family) {
$repository->insert(['status' => 1, 'type' => 'adobe-fonts', 'title' => sanitize_text_field($family['name']), 'slug' => sanitize_key($family['id']), 'family' => sanitize_text_field($family['slug']), 'metadata' => FontCodec::encode($family), 'font_faces' => FontCodec::encode([])], ['%d', '%s', '%s', '%s', '%s', '%s', '%s']);
}
});
} catch (\Throwable $throwable) {
return new WP_REST_Response(['message' => __('Adobe Fonts could not be synchronized. The previous data was preserved.', 'jooosi-fon')], 500);
}
FontEvents::invalidate('a!jooosi/fon/api/setting/adobe-fonts:sync');
return new WP_REST_Response([]);
}
public function destroy(WP_REST_Request $wprestRequest): WP_REST_Response
{
try {
$this->delete_fonts();
} catch (\Throwable $throwable) {
return new WP_REST_Response(['message' => __('Adobe Fonts could not be disconnected.', 'jooosi-fon')], 500);
}
FontEvents::invalidate('a!jooosi/fon/api/setting/adobe-fonts:destroy');
return new WP_REST_Response([]);
}
private function delete_fonts(): void
{
(new FontRepository())->deleteByType('adobe-fonts');
}
}
@@ -0,0 +1,60 @@
<?php
/*
* This file is part of the Jooosi Fon package.
*
* (c) Joshua Gugun Siagian <suabahasa@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare (strict_types=1);
namespace JooosiFon\Api\Setting;
use JooosiFon\Api\AbstractApi;
use JooosiFon\Api\ApiInterface;
use JooosiFon\Api\Support\FontEvents;
use JooosiFon\Core\Cache as CoreCache;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;
class Cache extends AbstractApi implements ApiInterface
{
public function __construct()
{
}
public function get_prefix(): string
{
return 'setting/cache';
}
public function register_custom_endpoints(): void
{
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/index', ['methods' => WP_REST_Server::READABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->index($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest)]);
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/generate', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->generate($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest)]);
}
public function index(WP_REST_Request $wprestRequest): WP_REST_Response
{
$cache_path = CoreCache::get_cache_path(CoreCache::CSS_CACHE_FILE);
$cache = ['last_generated' => '', 'pending_task' => \false, 'file_url' => '', 'state' => 'idle', 'error' => '', 'warnings' => []];
$buildStatus = CoreCache::getBuildStatus();
$cache['state'] = (string) ($buildStatus['state'] ?? 'idle');
$cache['error'] = (string) ($buildStatus['error'] ?? '');
$cache['warnings'] = is_array($buildStatus['warnings'] ?? null) ? array_values($buildStatus['warnings']) : [];
$cache['hash'] = (string) ($buildStatus['hash'] ?? '');
$cache['changed'] = (bool) ($buildStatus['changed'] ?? \false);
if (file_exists($cache_path) && is_readable($cache_path)) {
$cache['file_url'] = CoreCache::get_versioned_cache_url(CoreCache::CSS_CACHE_FILE);
$cache['last_generated'] = filemtime($cache_path);
}
if (wp_next_scheduled('a!jooosi/fon/core/cache:build_cache') || $cache['state'] === 'running') {
$cache['pending_task'] = \true;
}
return new WP_REST_Response(['cache' => $cache]);
}
public function generate(WP_REST_Request $wprestRequest): WP_REST_Response
{
wp_clear_scheduled_hook('a!jooosi/fon/core/cache:build_cache');
FontEvents::invalidate('a!jooosi/fon/api/setting/cache:generate', null, \false);
return $this->index($wprestRequest);
}
}
@@ -0,0 +1,88 @@
<?php
/*
* This file is part of the Jooosi Fon package.
*
* (c) Joshua Gugun Siagian <suabahasa@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare (strict_types=1);
namespace JooosiFon\Api\Setting;
use JooosiFonDeps\JOOOSI_FON;
use JooosiFon\Api\AbstractApi;
use JooosiFon\Api\ApiInterface;
use JooosiFon\Plugin;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;
class License extends AbstractApi implements ApiInterface
{
public function __construct()
{
}
public function get_prefix(): string
{
return 'setting/license';
}
public function register_custom_endpoints(): void
{
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/index', ['methods' => WP_REST_Server::READABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->index($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest)]);
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/store', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->store($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest), 'args' => ['license' => ['required' => \true, 'sanitize_callback' => 'sanitize_text_field', 'validate_callback' => static fn($value): bool => is_string($value) && strlen($value) <= 255]]]);
}
public function index(WP_REST_Request $wprestRequest): WP_REST_Response
{
return new WP_REST_Response(['license' => $this->get_license()]);
}
private function store(WP_REST_Request $wprestRequest): WP_REST_Response
{
$new_license_key = trim((string) $wprestRequest->get_param('license'));
$old_license = $this->get_license();
$plugin_updater = Plugin::get_instance()->plugin_updater;
$notice = [];
if ($new_license_key !== $old_license['key']) {
if (!$plugin_updater) {
return new WP_REST_Response(['message' => __('License management is unavailable in this edition.', 'jooosi-fon'), 'license' => $this->get_license()], 404);
}
if ($new_license_key === '') {
$response = $plugin_updater->deactivate();
if (is_wp_error($response)) {
$message = $response->get_error_message();
$status = $response->get_error_code() === 'license_server_unavailable' ? 502 : 422;
return new WP_REST_Response(['message' => $message, 'license' => $this->get_license(), 'notice' => ['error' => $message]], $status);
}
$notice['success'] = __('Plugin license key deactivated successfully.', 'jooosi-fon');
} else {
$response = $plugin_updater->activate($new_license_key);
if (is_wp_error($response)) {
$message = $response->get_error_message();
$status = $response->get_error_code() === 'license_server_unavailable' ? 502 : 422;
return new WP_REST_Response(['message' => $message, 'license' => $this->get_license(), 'notice' => ['error' => $message]], $status);
}
$notice['success'] = __('Plugin license key activated successfully.', 'jooosi-fon');
}
$newOption = ['key' => $new_license_key, 'opt_in_pre_release' => (bool) $old_license['opt_in_pre_release']];
if (!update_option(JOOOSI_FON::WP_OPTION . '_license', $newOption) && get_option(JOOOSI_FON::WP_OPTION . '_license') !== $newOption) {
return new WP_REST_Response(['message' => __('The license was accepted but could not be saved locally.', 'jooosi-fon'), 'license' => $this->get_license()], 500);
}
}
return new WP_REST_Response(['license' => $this->get_license(), 'notice' => $notice]);
}
private function get_license(): array
{
$license = get_option(JOOOSI_FON::WP_OPTION . '_license', ['key' => '', 'opt_in_pre_release' => \false]);
$license = wp_parse_args(is_array($license) ? $license : [], ['key' => '', 'opt_in_pre_release' => \false]);
$plugin_updater = Plugin::get_instance()->plugin_updater;
if ($plugin_updater) {
$license['key'] = $plugin_updater->get_license_key();
}
try {
$license['is_activated'] = $plugin_updater && $plugin_updater->is_activated();
} catch (\Throwable $throwable) {
$license['is_activated'] = \false;
}
return $license;
}
}
@@ -0,0 +1,104 @@
<?php
/*
* This file is part of the Jooosi Fon package.
*
* (c) Joshua Gugun Siagian <suabahasa@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare (strict_types=1);
namespace JooosiFon\Api\Setting;
use JooosiFonDeps\JOOOSI_FON;
use JooosiFon\Api\AbstractApi;
use JooosiFon\Api\ApiInterface;
use JooosiFon\Api\Support\RequestValidator;
use JooosiFon\Database\FontTable;
use JooosiFon\Upgrade\LegacyRebrandUpgrade;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;
/**
* @todo Remove all legacy Yabe Webfont filter shims completely in Jooosi Fon 3.0.0.
*/
class Option extends AbstractApi implements ApiInterface
{
public function __construct()
{
}
public function get_prefix(): string
{
return 'setting/option';
}
public function register_custom_endpoints(): void
{
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/index', ['methods' => WP_REST_Server::READABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->index($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest)]);
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/store', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->store($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest), 'args' => ['options' => ['required' => \true, 'validate_callback' => [RequestValidator::class, 'arrayValue']]]]);
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/migrate-legacy', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->migrate_legacy($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest)]);
}
public function index(WP_REST_Request $wprestRequest): WP_REST_Response
{
try {
$stored = get_option(JOOOSI_FON::WP_OPTION . '_options', '{}');
$options = json_decode(is_string($stored) ? $stored : '{}', null, 512, \JSON_THROW_ON_ERROR);
} catch (\JsonException $exception) {
$options = new \stdClass();
}
$options = apply_filters('f!jooosi/fon/api/setting/option:index_options', $options);
$options = apply_filters_deprecated('f!yabe/webfont/api/setting/option:index_options', [$options], '2.1.0', 'f!jooosi/fon/api/setting/option:index_options');
return new WP_REST_Response(['options' => $options, 'legacy_migration' => (new LegacyRebrandUpgrade())->status()]);
}
public function migrate_legacy(WP_REST_Request $wprestRequest): WP_REST_Response
{
try {
FontTable::migrateLegacy();
$upgrade = new LegacyRebrandUpgrade();
$upgrade->run();
$status = $upgrade->status();
if (!$status['complete']) {
return new WP_REST_Response(['message' => __('The Yabe Webfont migration is incomplete. The original data was preserved; try again after resolving the reported file issue.', 'jooosi-fon'), 'legacy_migration' => $status], 500);
}
return new WP_REST_Response(['legacy_migration' => $status]);
} catch (\Throwable $throwable) {
return new WP_REST_Response(['message' => $throwable->getMessage(), 'legacy_migration' => (new LegacyRebrandUpgrade())->status()], 500);
}
}
public function store(WP_REST_Request $wprestRequest): WP_REST_Response
{
$options = (array) $wprestRequest->get_param('options');
if (empty($options)) {
$options = (object) $options;
}
$options = apply_filters('f!jooosi/fon/api/setting/option:store_options', $options);
$options = apply_filters_deprecated('f!yabe/webfont/api/setting/option:store_options', [$options], '2.1.0', 'f!jooosi/fon/api/setting/option:store_options');
try {
$encoded = json_encode($options, \JSON_THROW_ON_ERROR);
} catch (\JsonException $exception) {
return new WP_REST_Response(['message' => __('The settings payload could not be encoded.', 'jooosi-fon')], 400);
}
if (!update_option(JOOOSI_FON::WP_OPTION . '_options', $encoded) && get_option(JOOOSI_FON::WP_OPTION . '_options') !== $encoded) {
return new WP_REST_Response(['message' => __('The settings could not be saved.', 'jooosi-fon')], 500);
}
if ($this->shouldDeleteLegacyData($options) && !(new LegacyRebrandUpgrade())->deleteLegacyData()) {
return new WP_REST_Response(['message' => __('The legacy Yabe Webfont data cleanup was incomplete. Any remaining data was preserved.', 'jooosi-fon')], 500);
}
do_action('f!jooosi/fon/api/setting/option:after_store', $options);
do_action_deprecated('f!yabe/webfont/api/setting/option:after_store', [$options], '2.1.0', 'f!jooosi/fon/api/setting/option:after_store');
return $this->index($wprestRequest);
}
/**
* @param mixed $options
*/
private function shouldDeleteLegacyData($options): bool
{
if (is_object($options)) {
$options = get_object_vars($options);
}
if (!is_array($options) || !is_array($options['misc'] ?? null)) {
return \false;
}
return !empty($options['misc']['delete_legacy_data']);
}
}
@@ -0,0 +1,57 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Api\Support;
/**
* Encodes font payloads and reads both the current compressed representation
* and the legacy plain JSON representation.
*/
final class FontCodec
{
/**
* @return array|object
*/
public static function decode(string $payload, bool $associative = \false)
{
try {
return self::decodeJson($payload, $associative);
} catch (\JsonException $exception) {
$compressed = base64_decode($payload, \true);
if ($compressed === \false) {
throw new \UnexpectedValueException('The stored font payload is neither JSON nor valid base64.', 0, $exception);
}
$json = @gzuncompress($compressed);
if (!is_string($json)) {
throw new \UnexpectedValueException('The stored font payload could not be decompressed.', 0, $exception);
}
return self::decodeJson($json, $associative);
}
}
/**
* @param array|object $payload
*/
public static function encode($payload, bool $compressed = \true): string
{
$json = json_encode($payload, \JSON_THROW_ON_ERROR);
if (!$compressed) {
return $json;
}
$encoded = gzcompress($json, 9);
if ($encoded === \false) {
throw new \RuntimeException('The font payload could not be compressed.');
}
return base64_encode($encoded);
}
/**
* @return array|object
*/
private static function decodeJson(string $payload, bool $associative)
{
$decoded = json_decode($payload, $associative, 512, \JSON_THROW_ON_ERROR);
if (!is_array($decoded) && !is_object($decoded)) {
throw new \UnexpectedValueException('The font payload must decode to an object or array.');
}
return $decoded;
}
}
@@ -0,0 +1,45 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Api\Support;
use JooosiFon\Utils\Font;
/**
* Emits the public font lifecycle hooks and exactly one cache invalidation
* event for each successful mutation.
*
* @todo Remove all legacy Yabe Webfont hook shims completely in Jooosi Fon 3.0.0.
*/
final class FontEvents
{
/**
* @param mixed $payload
*/
public static function dispatch(string $event, $payload = null, bool $async = \true): void
{
$hook = 'a!jooosi/fon/api/font:' . $event;
$legacyHook = 'a!yabe/webfont/api/font:' . $event;
Font::clear_cache();
do_action($hook, $payload);
do_action_deprecated($legacyHook, [$payload], '2.1.0', $hook);
self::emitInvalidation($hook, $payload, $async);
}
/**
* @param mixed $payload
*/
public static function invalidate(string $source, $payload = null, bool $async = \true): void
{
Font::clear_cache();
self::emitInvalidation($source, $payload, $async);
}
/**
* @param mixed $payload
*/
private static function emitInvalidation(string $source, $payload, bool $async): void
{
$hook = $async ? 'a!jooosi/fon/api/font:fonts_event_async' : 'a!jooosi/fon/api/font:fonts_event';
$legacyHook = $async ? 'a!yabe/webfont/api/font:fonts_event_async' : 'a!yabe/webfont/api/font:fonts_event';
do_action($hook, $source, $payload);
do_action_deprecated($legacyHook, [str_replace('!jooosi/fon/', '!yabe/webfont/', $source), $payload], '2.1.0', $hook);
}
}
@@ -0,0 +1,89 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Api\Support;
/**
* Owns database writes for font records and turns silent wpdb failures into
* exceptions that REST controllers can handle consistently.
*/
final class FontRepository
{
public function table(): string
{
global $wpdb;
return $wpdb->prefix . 'jooosi_fon_fonts';
}
public function find(int $id)
{
global $wpdb;
return $wpdb->get_row($wpdb->prepare("SELECT * FROM {$this->table()} WHERE id = %d", $id));
}
public function findOfType(int $id, string $type)
{
global $wpdb;
return $wpdb->get_row($wpdb->prepare("SELECT * FROM {$this->table()} WHERE id = %d AND type = %s", $id, $type));
}
public function findBySlug(string $slug)
{
global $wpdb;
return $wpdb->get_row($wpdb->prepare("SELECT * FROM {$this->table()} WHERE slug = %s LIMIT 1", $slug));
}
/**
* @param array<string, mixed> $data
* @param string[] $formats
*/
public function insert(array $data, array $formats): int
{
global $wpdb;
if ($wpdb->insert($this->table(), $data, $formats) === \false || $wpdb->insert_id < 1) {
throw new \RuntimeException($wpdb->last_error ?: 'Unable to create the font record.');
}
return (int) $wpdb->insert_id;
}
/**
* @param array<string, mixed> $data
* @param string[] $formats
*/
public function update(int $id, array $data, array $formats): void
{
global $wpdb;
if ($wpdb->update($this->table(), $data, ['id' => $id], $formats, ['%d']) === \false) {
throw new \RuntimeException($wpdb->last_error ?: 'Unable to update the font record.');
}
}
public function delete(int $id): void
{
global $wpdb;
if ($wpdb->delete($this->table(), ['id' => $id], ['%d']) === \false) {
throw new \RuntimeException($wpdb->last_error ?: 'Unable to delete the font record.');
}
}
public function deleteByType(string $type): void
{
global $wpdb;
if ($wpdb->delete($this->table(), ['type' => $type], ['%s']) === \false) {
throw new \RuntimeException($wpdb->last_error ?: 'Unable to delete the font records.');
}
}
/**
* @return mixed
*/
public function transaction(callable $callback)
{
global $wpdb;
if ($wpdb->query('START TRANSACTION') === \false) {
throw new \RuntimeException($wpdb->last_error ?: 'Unable to start the database transaction.');
}
try {
$result = $callback($this);
if ($wpdb->query('COMMIT') === \false) {
throw new \RuntimeException($wpdb->last_error ?: 'Unable to commit the database transaction.');
}
return $result;
} catch (\Throwable $throwable) {
$wpdb->query('ROLLBACK');
throw $throwable;
}
}
}
@@ -0,0 +1,44 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Api\Support;
final class GoogleFontFileSelector
{
/**
* @param array<int, array<string, mixed>> $files
* @param array<string, mixed> $face
* @param string[] $subsets
* @param string[] $formats
* @return array<int, array<string, mixed>>
*/
public static function variableFiles(array $files, array $face, array $subsets, array $formats): array
{
$selected = [];
foreach ($subsets as $subset) {
foreach ($files as $file) {
if (self::matchesFace($file, $face, $formats) && in_array($subset, (array) ($file['subsets'] ?? []), \true)) {
$selected[] = $file;
}
}
}
$usesNamedSubsets = array_reduce($subsets, static fn(bool $carry, string $subset): bool => $carry && preg_match('/\d/', $subset) !== 1, \true);
if ($usesNamedSubsets) {
foreach ($files as $file) {
if (self::matchesFace($file, $face, $formats)) {
$selected[] = $file;
}
}
}
return array_values(array_unique($selected, \SORT_REGULAR));
}
/**
* @param array<string, mixed> $file
* @param array<string, mixed> $face
* @param string[] $formats
*/
private static function matchesFace(array $file, array $face, array $formats): bool
{
return ($file['weight'] ?? null) === ($face['weight'] ?? null) && ($file['style'] ?? null) === ($face['style'] ?? null) && in_array($file['format'] ?? null, $formats, \true);
}
}
@@ -0,0 +1,28 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Api\Support;
final class GoogleFontsClient
{
public function fetchCss(string $url, string $userAgent): string
{
$host = strtolower((string) wp_parse_url($url, \PHP_URL_HOST));
if (wp_parse_url($url, \PHP_URL_SCHEME) !== 'https' || $host !== 'fonts.googleapis.com') {
throw new \InvalidArgumentException('The Google Fonts stylesheet URL is invalid.');
}
$response = wp_safe_remote_get($url, ['headers' => ['User-Agent' => $userAgent], 'redirection' => 2, 'timeout' => 15, 'limit_response_size' => \MB_IN_BYTES]);
if (is_wp_error($response)) {
throw new \RuntimeException($response->get_error_message());
}
$status = wp_remote_retrieve_response_code($response);
if ($status !== 200) {
throw new \RuntimeException(sprintf('Google Fonts returned HTTP %d.', $status));
}
$body = wp_remote_retrieve_body($response);
if (!is_string($body) || trim($body) === '') {
throw new \RuntimeException('Google Fonts returned an empty stylesheet.');
}
return $body;
}
}
@@ -0,0 +1,138 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Api\Support;
use JooosiFon\Utils\Common;
use JooosiFon\Utils\Upload;
/**
* Creates font attachments as a unit and can compensate for a later database
* failure by deleting attachments created during the current operation.
*/
final class MediaImportService
{
/**
* @var int[]
*/
private array $createdAttachmentIds = [];
/**
* @param string[] $allowedHosts
* @return array<string, mixed>
*/
public function remote(string $url, string $fileName, string $extension, array $allowedHosts = []): array
{
$this->assertRemoteUrl($url, $allowedHosts);
$mime = self::mimeForExtension($extension);
$attachmentId = Upload::remote_upload_media($url, $fileName, $mime);
return $this->attachmentData($attachmentId, $fileName, $extension, $mime);
}
/**
* @return array<string, mixed>
*/
public function binary(string $binary, string $fileName, string $extension): array
{
$mime = self::mimeForExtension($extension);
$attachmentId = Upload::binary_upload_media($binary, $fileName, $mime);
return $this->attachmentData($attachmentId, $fileName, $extension, $mime);
}
/**
* @return array<string, mixed>
*/
public function local(string $path, string $fileName, string $extension): array
{
if (!is_file($path) || !is_readable($path)) {
throw new \RuntimeException('The source font file is not readable.');
}
$binary = file_get_contents($path);
if (!is_string($binary) || $binary === '') {
throw new \RuntimeException('The source font file is empty.');
}
return $this->binary($binary, $fileName, $extension);
}
public function commit(): void
{
$this->createdAttachmentIds = [];
}
public function rollback(): void
{
foreach (array_unique($this->createdAttachmentIds) as $attachmentId) {
wp_delete_attachment($attachmentId, \true);
}
$this->createdAttachmentIds = [];
}
/**
* @param array|object $fontFaces
* @return int[]
*/
public static function attachmentIds($fontFaces): array
{
$ids = [];
foreach ((array) $fontFaces as $fontFace) {
$files = is_array($fontFace) ? $fontFace['files'] ?? [] : $fontFace->files ?? [];
foreach ((array) $files as $file) {
$attachmentId = is_array($file) ? $file['attachment_id'] ?? 0 : $file->attachment_id ?? 0;
if (is_numeric($attachmentId) && (int) $attachmentId > 0) {
$ids[] = (int) $attachmentId;
}
}
}
return array_values(array_unique($ids));
}
/**
* @param int[] $attachmentIds
*/
public static function deleteAttachments(array $attachmentIds): void
{
foreach (array_unique(array_map('intval', $attachmentIds)) as $attachmentId) {
if ($attachmentId > 0) {
wp_delete_attachment($attachmentId, \true);
}
}
}
public static function mimeForExtension(string $extension): string
{
$mimes = ['woff2' => 'font/woff2', 'woff' => 'font/woff', 'ttf' => 'font/ttf', 'otf' => 'font/otf', 'eot' => 'font/eot'];
$extension = strtolower($extension);
if (!isset($mimes[$extension])) {
throw new \InvalidArgumentException('Unsupported font file extension.');
}
return $mimes[$extension];
}
/**
* @param mixed $attachmentId
* @return array<string, mixed>
*/
private function attachmentData($attachmentId, string $fileName, string $extension, string $mime): array
{
if (is_wp_error($attachmentId)) {
throw new \RuntimeException($attachmentId->get_error_message());
}
if (!is_int($attachmentId) || $attachmentId < 1) {
throw new \RuntimeException('The font attachment could not be created.');
}
$path = get_attached_file($attachmentId);
if (!is_string($path) || !is_readable($path)) {
wp_delete_attachment($attachmentId, \true);
throw new \RuntimeException('The uploaded font attachment is not readable.');
}
$this->createdAttachmentIds[] = $attachmentId;
return ['uid' => Common::random_slug(10), 'attachment_id' => $attachmentId, 'attachment_url' => wp_get_attachment_url($attachmentId), 'extension' => strtolower($extension), 'mime' => $mime, 'file_size' => (int) filesize($path), 'name' => pathinfo($fileName, \PATHINFO_FILENAME)];
}
/**
* @param string[] $allowedHosts
*/
private function assertRemoteUrl(string $url, array $allowedHosts): void
{
if (!wp_http_validate_url($url)) {
throw new \InvalidArgumentException('The remote font URL is not safe.');
}
if ($allowedHosts === []) {
return;
}
$host = strtolower((string) wp_parse_url($url, \PHP_URL_HOST));
$allowedHosts = array_map('strtolower', $allowedHosts);
if (!in_array($host, $allowedHosts, \true)) {
throw new \InvalidArgumentException('The remote font URL uses an unapproved host.');
}
}
}
@@ -0,0 +1,206 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Api\Support;
final class RequestValidator
{
private const FONT_EXTENSION_ALIASES = ['font/woff2' => 'woff2', 'font/woff' => 'woff', 'font/ttf' => 'ttf', 'font/otf' => 'otf', 'font/eot' => 'eot', 'application/font-woff2' => 'woff2', 'application/font-woff' => 'woff', 'application/x-font-woff2' => 'woff2', 'application/x-font-woff' => 'woff', 'application/x-font-ttf' => 'ttf', 'application/x-font-truetype' => 'ttf', 'application/x-font-opentype' => 'otf', 'application/vnd.ms-opentype' => 'otf', 'application/vnd.ms-fontobject' => 'eot', 'x-font-woff2' => 'woff2', 'x-font-woff' => 'woff', 'x-font-ttf' => 'ttf', 'x-font-opentype' => 'otf', 'vnd.ms-opentype' => 'otf', 'vnd.ms-fontobject' => 'eot', 'truetype' => 'ttf', 'opentype' => 'otf', 'embedded-opentype' => 'eot'];
public static function positiveInteger($value): bool
{
return filter_var($value, \FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]) !== \false;
}
public static function pageSize($value): bool
{
return filter_var($value, \FILTER_VALIDATE_INT, ['options' => ['min_range' => 1, 'max_range' => 100]]) !== \false;
}
public static function boolean($value): bool
{
return is_bool($value) || in_array($value, [0, 1, '0', '1', 'false', 'true'], \true);
}
public static function nonEmptyString($value): bool
{
return is_string($value) && trim($value) !== '';
}
public static function arrayValue($value): bool
{
if (!is_array($value)) {
return \false;
}
$encoded = json_encode($value);
return is_string($encoded) && strlen($encoded) <= 2 * 1024 * 1024;
}
public static function positiveIntegerList($value): bool
{
if (!is_array($value) || $value === [] || count($value) > 50) {
return \false;
}
foreach ($value as $item) {
if (!self::positiveInteger($item)) {
return \false;
}
}
return \true;
}
public static function fontType($value): bool
{
return is_string($value) && in_array($value, ['custom', 'google-fonts', 'adobe-fonts'], \true);
}
public static function projectId($value): bool
{
return is_string($value) && preg_match('/^[a-zA-Z0-9_-]{1,100}$/', $value) === 1;
}
public static function subsets($value): bool
{
return is_string($value) && ($value === '' || preg_match('/^[a-zA-Z0-9_-]+(?:,[a-zA-Z0-9_-]+)*$/', $value) === 1);
}
public static function importItem($value): bool
{
return is_array($value) && isset($value['type'], $value['title'], $value['family'], $value['font_faces'], $value['metadata']) && self::fontType($value['type']) && self::nonEmptyString($value['title']) && self::nonEmptyString($value['family']) && is_string($value['font_faces']) && is_string($value['metadata']) && strlen($value['font_faces']) <= 30 * 1024 * 1024 && strlen($value['metadata']) <= 5 * 1024 * 1024;
}
public static function googleMetadata($value): bool
{
if (!is_array($value) || !isset($value['google_fonts']) || !is_array($value['google_fonts'])) {
return \false;
}
$google = $value['google_fonts'];
if (!isset($google['font_data'], $google['font_faces'], $google['font_files'], $google['formats'], $google['subsets']) || !is_array($google['font_data']) || !is_array($google['font_faces']) || !is_array($google['font_files']) || !is_array($google['formats']) || !is_array($google['subsets']) || !isset($google['font_data']['family'], $google['font_data']['slug']) || !self::nonEmptyString($google['font_data']['family']) || !self::nonEmptyString($google['font_data']['slug']) || strlen($google['font_data']['family']) > 255 || strlen($google['font_data']['slug']) > 255 || count($google['font_faces']) > 100 || count($google['font_files']) > 500 || count($google['formats']) > 3 || count($google['subsets']) > 50 || $google['formats'] === [] || $google['subsets'] === [] || $google['font_files'] === [] || $google['font_faces'] === []) {
return \false;
}
foreach ($google['formats'] as $format) {
if (!in_array($format, ['woff2', 'woff', 'ttf'], \true)) {
return \false;
}
}
foreach ($google['subsets'] as $subset) {
if (!is_string($subset) || preg_match('/^[a-zA-Z0-9_-]+$/', $subset) !== 1) {
return \false;
}
}
foreach ($google['font_files'] as $file) {
if (!is_array($file) || !isset($file['uid'], $file['format'], $file['weight'], $file['style'], $file['subsets'], $file['url']) || !self::nonEmptyString($file['uid']) || strlen($file['uid']) > 255 || !in_array($file['format'], ['woff2', 'woff', 'ttf'], \true) || !is_numeric($file['weight']) || !is_string($file['style']) || !is_array($file['subsets']) || count($file['subsets']) > 50 || !filter_var($file['url'], \FILTER_VALIDATE_URL) || strtolower((string) parse_url($file['url'], \PHP_URL_SCHEME)) !== 'https' || strtolower((string) parse_url($file['url'], \PHP_URL_HOST)) !== 'fonts.gstatic.com') {
return \false;
}
foreach ($file['subsets'] as $subset) {
if (!is_string($subset) || preg_match('/^[a-zA-Z0-9_-]+$/', $subset) !== 1) {
return \false;
}
}
if (array_key_exists('file', $file) && !self::attachmentFile($file['file'])) {
return \false;
}
}
$hasEnabledFace = \false;
foreach ($google['font_faces'] as $face) {
if (!is_array($face) || !array_key_exists('weight', $face) || !array_key_exists('width', $face) || !array_key_exists('style', $face) || !array_key_exists('isEnabled', $face) || !array_key_exists('display', $face) || !array_key_exists('selector', $face) || !array_key_exists('comment', $face) || !array_key_exists('preload', $face) || !is_numeric($face['weight']) || !is_string($face['style']) || !self::boolean($face['isEnabled'])) {
return \false;
}
$hasEnabledFace = $hasEnabledFace || filter_var($face['isEnabled'], \FILTER_VALIDATE_BOOLEAN) === \true;
}
if (!empty($google['variable']) && (!isset($google['font_data']['axes']) || !is_array($google['font_data']['axes']))) {
return \false;
}
if (!empty($google['variable'])) {
if ($google['font_data']['axes'] === [] || count($google['font_data']['axes']) > 20) {
return \false;
}
foreach ($google['font_data']['axes'] as $axis) {
if (!is_array($axis) || !isset($axis['tag'], $axis['min'], $axis['max']) || !is_string($axis['tag']) || preg_match('/^[a-zA-Z0-9]{1,10}$/', $axis['tag']) !== 1 || !is_numeric($axis['min']) || !is_numeric($axis['max']) || (float) $axis['min'] > (float) $axis['max']) {
return \false;
}
}
}
return $hasEnabledFace;
}
public static function fontFaces($value): bool
{
if (!is_array($value) || $value === [] || count($value) > 100) {
return \false;
}
foreach ($value as $face) {
if (!is_array($face) || !isset($face['id'], $face['weight'], $face['style'], $face['files']) || !self::nonEmptyString($face['id']) || !self::fontWeight($face['weight']) || !is_string($face['style']) || array_key_exists('isEnabled', $face) && !self::boolean($face['isEnabled']) || !is_array($face['files']) || count($face['files']) > 10) {
return \false;
}
foreach ($face['files'] as $file) {
if (!self::attachmentFile($file)) {
return \false;
}
}
}
return \true;
}
/**
* Normalize font file extensions from WordPress MIME subtypes and legacy
* payloads before they are persisted.
*/
public static function sanitizeFontFaces($value): array
{
if (!is_array($value)) {
return (array) $value;
}
foreach ($value as &$face) {
if (!is_array($face) || !isset($face['files']) || !is_array($face['files'])) {
continue;
}
foreach ($face['files'] as &$file) {
if (!is_array($file) || !isset($file['extension'])) {
continue;
}
$extension = self::fontExtension($file['extension']);
if ($extension !== null) {
$file['extension'] = $extension;
}
}
unset($file);
}
unset($face);
return $value;
}
public static function attachmentFile($value): bool
{
return is_array($value) && isset($value['attachment_id'], $value['extension']) && self::positiveInteger($value['attachment_id']) && self::fontExtension($value['extension']) !== null;
}
private static function fontExtension($value): ?string
{
$extension = strtolower(trim((string) $value));
if (in_array($extension, ['woff2', 'woff', 'ttf', 'otf', 'eot'], \true)) {
return $extension;
}
return self::FONT_EXTENSION_ALIASES[$extension] ?? null;
}
public static function fontWeight($value): bool
{
if (is_int($value) || is_float($value)) {
return $value >= 1 && $value <= 1000;
}
if (!is_string($value) || preg_match('/^(?:normal|bold|[1-9]\d{0,3})(?:\s+[1-9]\d{0,3})?$/', trim($value)) !== 1) {
return \false;
}
$weights = preg_split('/\s+/', trim($value));
if ($weights === \false) {
return \false;
}
foreach ($weights as $weight) {
if (is_numeric($weight) && ((int) $weight < 1 || (int) $weight > 1000)) {
return \false;
}
}
return \true;
}
public static function adobeKit($value): bool
{
if (!is_array($value) || !isset($value['families']) || !is_array($value['families'])) {
return \false;
}
foreach ($value['families'] as $family) {
if (!is_array($family) || !isset($family['id'], $family['name'], $family['slug']) || !self::nonEmptyString($family['id']) || !self::nonEmptyString($family['name']) || !self::nonEmptyString($family['slug'])) {
return \false;
}
}
return \true;
}
public static function confirmed($value): bool
{
return filter_var($value, \FILTER_VALIDATE_BOOLEAN) === \true;
}
}
@@ -0,0 +1,20 @@
<?php
/*
* This file is part of the Jooosi Fon package.
*
* (c) Joshua Gugun Siagian <suabahasa@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare (strict_types=1);
namespace JooosiFon\Builder;
interface BuilderInterface
{
/**
* Get the Builder integration name.
*/
public function get_name(): string;
}
@@ -0,0 +1,67 @@
<?php
/*
* This file is part of the Jooosi Fon package.
*
* (c) Joshua Gugun Siagian <suabahasa@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare (strict_types=1);
namespace JooosiFon\Builder\Builderius;
use JooosiFon\Admin\AdminPage;
use JooosiFon\Builder\BuilderInterface;
use JooosiFon\Utils\Font;
/**
* @author Joshua Gugun Siagian <suabahasa@gmail.com>
*
* @todo Built-in Google Fonts are not disabled.
*/
class Main implements BuilderInterface
{
public function __construct()
{
add_action('admin_menu', static fn() => AdminPage::add_redirect_submenu_page('builderius'), 1000001);
add_action('wp_enqueue_scripts', fn() => $this->enqueue_scripts(), 1000001);
}
public function get_name(): string
{
return 'builderius';
}
public function enqueue_scripts()
{
if (!wp_script_is('builderius-builder', 'registered')) {
return;
}
$fonts = Font::get_fonts();
$inline_script_content = <<<JS
const moduleTypography = builderiusBackend.settingsList?.module?.advanced?.typography?.find((item) => item.name === 'font');
if (moduleTypography) {
moduleTypography.options.fontType.values.push('Jooosi Fon');
moduleTypography.options.genericFamily.values['Jooosi Fon'] = ['Jooosi Fon'];
moduleTypography.options.fontFamily.values['Jooosi Fon.Jooosi Fon'] = jooosiFonBuilderiusFonts;
}
const GlobalTypography = builderiusBackend.settingsList?.global?.advanced?.typography?.find((item) => item.name === 'font');
if (GlobalTypography) {
GlobalTypography.options.fontType.values.push('Jooosi Fon');
GlobalTypography.options.genericFamily.values['Jooosi Fon'] = ['Jooosi Fon'];
GlobalTypography.options.fontFamily.values['Jooosi Fon.Jooosi Fon'] = jooosiFonBuilderiusFonts;
}
const templateTypography = builderiusBackend.settingsList?.template?.advanced?.typography?.find((item) => item.name === 'font');
if (templateTypography) {
templateTypography.options.fontType.values.push('Jooosi Fon');
templateTypography.options.genericFamily.values['Jooosi Fon'] = ['Jooosi Fon'];
templateTypography.options.fontFamily.values['Jooosi Fon.Jooosi Fon'] = jooosiFonBuilderiusFonts;
}
JS;
wp_add_inline_script('builderius-builder', 'const jooosiFonBuilderiusFonts = ' . json_encode(array_column($fonts, 'family'), \JSON_THROW_ON_ERROR), 'before');
wp_add_inline_script('builderius-builder', $inline_script_content, 'before');
}
}
@@ -0,0 +1,58 @@
<?php
/*
* This file is part of the Jooosi Fon package.
*
* (c) Joshua Gugun Siagian <suabahasa@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare (strict_types=1);
namespace JooosiFon\Builder\ClassicEditor;
use JooosiFon\Builder\BuilderInterface;
use JooosiFon\Core\Cache;
use JooosiFon\Utils\Font;
/**
* Classic Editor integration.
*
* @author Joshua Gugun Siagian <suabahasa@gmail.com>
*/
class Main implements BuilderInterface
{
public function __construct()
{
add_filter('mce_buttons_2', fn($buttons) => $this->filter_mce_buttons($buttons), 1000001);
add_filter('tiny_mce_before_init', fn($mceInit, $editor_id) => $this->filter_tiny_mce($mceInit, $editor_id), 1000001, 2);
add_filter('mce_css', fn($stylesheets) => $this->filter_mce_css($stylesheets), 1000001);
}
public function get_name(): string
{
return 'classic-editor';
}
public function filter_tiny_mce($mceInit, $editor_id)
{
$theme_advanced_fonts = '';
$fonts = Font::get_fonts();
foreach ($fonts as $font) {
$theme_advanced_fonts .= sprintf('[Jooosi Fon] %s=%s;', $font['title'], $font['family']);
}
$mceInit['font_formats'] = $theme_advanced_fonts . 'Andale Mono=andale mono,times; Arial=arial,helvetica,sans-serif; Arial Black=arial black,avant garde; Book Antiqua=book antiqua,palatino; Comic Sans MS=comic sans ms,sans-serif; Courier New=courier new,courier; Georgia=georgia,palatino; Helvetica=helvetica; Impact=impact,chicago; Symbol=symbol; Tahoma=tahoma,arial,helvetica,sans-serif; Terminal=terminal,monaco; Times New Roman=times new roman,times; Trebuchet MS=trebuchet ms,geneva; Verdana=verdana,geneva; Webdings=webdings; Wingdings=wingdings,zapf dingbats';
return $mceInit;
}
public function filter_mce_buttons($buttons)
{
return array_merge($buttons, ['fontsizeselect', 'fontselect']);
}
public function filter_mce_css($stylesheets)
{
$css_url = Cache::get_versioned_cache_url(Cache::CSS_CACHE_FILE);
if (is_array($stylesheets)) {
$stylesheets[] = $css_url;
} else {
$stylesheets .= ',' . $css_url;
}
return $stylesheets;
}
}
@@ -0,0 +1,62 @@
<?php
/*
* This file is part of the Jooosi Fon package.
*
* (c) Joshua Gugun Siagian <suabahasa@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare (strict_types=1);
namespace JooosiFon\Builder\Elementor;
use JooosiFon\Admin\AdminPage;
use JooosiFon\Builder\BuilderInterface;
use JooosiFon\Utils\Config;
use JooosiFon\Utils\Font;
/**
* Elementor integration.
*
* @author Joshua Gugun Siagian <suabahasa@gmail.com>
*/
class Main implements BuilderInterface
{
public function __construct()
{
/**
* Disable Elementor's built-in Google Fonts.
*/
if (Config::get('builder_integrations.disable_google_fonts.elementor', \true)) {
add_filter('pre_option_elementor_google_font', static fn($pre_option, $option, $default) => '0', 1000001, 3);
add_filter('pre_update_option_elementor_google_font', static fn($value, $old_value, $option) => '0', 1000001, 3);
}
/**
* Register fonts with 'custom' category for Atomic Widgets compatibility.
* Atomic Widgets (Elementor v4) only supports: system, custom, googlefonts
*/
add_filter('elementor/fonts/additional_fonts', fn($fonts) => $this->filter_elementor_fonts($fonts), 1000001);
add_action('admin_menu', static fn() => AdminPage::add_redirect_submenu_page('elementor'), 1000001);
}
public function get_name(): string
{
return 'elementor';
}
/**
* Register fonts with Elementor.
* Uses 'custom' category for compatibility with both Classic Editor and Atomic Widgets.
*
* @param array $elementor_fonts Existing Elementor fonts.
* @return array Modified fonts array.
*/
public function filter_elementor_fonts($elementor_fonts)
{
$fonts = Font::get_fonts();
foreach ($fonts as $font) {
// Use 'custom' category for Atomic Widgets v4 compatibility
// Atomic Widgets only recognizes: system, custom, googlefonts
$elementor_fonts[$font['family']] = 'custom';
}
return $elementor_fonts;
}
}
@@ -0,0 +1,110 @@
<?php
/*
* This file is part of the Jooosi Fon package.
*
* (c) Joshua Gugun Siagian <suabahasa@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare (strict_types=1);
namespace JooosiFon\Builder\GeneratePress;
use JooosiFon\Builder\BuilderInterface;
use JooosiFon\Utils\Font;
/**
* GeneratePress and GenerateBlocks integration.
*
* @author Joshua Gugun Siagian <suabahasa@gmail.com>
*/
class Main implements BuilderInterface
{
public function __construct()
{
/**
* Disable GeneratePress's built-in Google Fonts.
*/
add_filter('generate_font_manager_show_google_fonts', static fn() => \false, 1000001, 0);
/**
* Disable GenerateBlocks's built-in Google Fonts.
*/
add_filter('generateblocks_option_defaults', fn($value) => $this->filter_generateblocks_option_defaults($value), 1000001, 1);
add_filter('option_generateblocks', fn($value, $option) => $this->filter_option_generateblocks($value), 1000001, 2);
/**
* Add custom font to GeneratePress.
* Append the data on the pre_option, and rewrite the data on the option and pre_update_option.
*/
add_filter('generate_option_defaults', fn($opt) => $this->filter_generate_option_defaults($opt), 1000001);
/**
* @deprecated version 2.0.11
* @see https://github.com/tomusborne/generatepress/blob/e7fbf5693bfe4325a41cae988e3eda16550d4025/inc/defaults.php#L412
*/
// add_filter('generate_typography_default_fonts', static fn ($fonts) => array_merge($fonts, array_column(Font::get_fonts(), 'family')), 1_000_001);
/**
* @deprecated version 2.0.46
*/
// add_filter('pre_option_generate_settings', fn ($value, $option) => $this->generate_settings($value), 1_000_001, 2);
// add_filter('option_generate_settings', fn ($value, $option) => $this->generate_settings($value), 1_000_001, 2);
// add_filter('pre_update_option_generate_settings', fn ($value, $old_value, $option) => $this->generate_settings($value), 1_000_001, 3);
/**
* Add custom font to GenerateBlocks.
*
* @see https://github.com/tomusborne/generateblocks/issues/937
*/
add_filter('generateblocks_typography_font_family_list', fn($fonts) => $this->generateblocks_typography_font_family_list($fonts), 1000001);
}
public function get_name(): string
{
return 'generate-press';
}
public function generate_settings($opt)
{
$fonts = Font::get_fonts();
if (!is_array($opt)) {
$opt = [];
}
if (!array_key_exists('font_manager', $opt) || !is_array($opt['font_manager'])) {
$opt['font_manager'] = [];
}
foreach ($fonts as $font) {
if (!in_array($font['family'], array_column($opt['font_manager'], 'fontFamily'), \true)) {
$opt['font_manager'][] = ['fontFamily' => $font['family'], 'googleFont' => \false, 'googleFontApi' => 0];
}
}
return $opt;
}
public function filter_generateblocks_option_defaults($opt)
{
if (is_array($opt)) {
$opt['disable_google_fonts'] = \true;
}
return $opt;
}
public function filter_option_generateblocks($opt)
{
if (is_array($opt)) {
$opt['disable_google_fonts'] = \true;
}
return $opt;
}
public function generateblocks_typography_font_family_list($gb_fonts)
{
$fonts = Font::get_fonts();
$jooosi_fonts = array_map(static fn($f) => ['label' => $f['title'], 'value' => $f['family']], $fonts);
return array_merge([['label' => 'Jooosi Fon', 'options' => $jooosi_fonts]], is_array($gb_fonts) ? $gb_fonts : iterator_to_array($gb_fonts));
}
public function filter_generate_option_defaults($opt)
{
$fonts = Font::get_fonts();
if (!array_key_exists('font_manager', $opt) || !is_array($opt['font_manager'])) {
$opt['font_manager'] = [];
}
foreach ($fonts as $font) {
if (!in_array($font['family'], array_column($opt['font_manager'], 'fontFamily'), \true)) {
$opt['font_manager'][] = ['fontFamily' => $font['family'], 'googleFont' => \false, 'googleFontApi' => 0];
}
}
return $opt;
}
}
@@ -0,0 +1,141 @@
<?php
/*
* This file is part of the Jooosi Fon package.
*
* (c) Joshua Gugun Siagian <suabahasa@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare (strict_types=1);
namespace JooosiFon\Builder\Gutenberg;
use JooosiFonDeps\JOOOSI_FON;
use JooosiFon\Builder\BuilderInterface;
use JooosiFon\Core\Cache;
use JooosiFon\Core\Frontpage;
use JooosiFon\Utils\Config;
use JooosiFon\Utils\Font;
use WP_Theme_JSON;
use WP_Theme_JSON_Data;
/**
* Gutenberg integration.
*
* @see https://developer.wordpress.org/block-editor/how-to-guides/themes/theme-json/
* @see https://developer.wordpress.org/block-editor/reference-guides/theme-json-reference/theme-json-living/
* @see https://developer.wordpress.org/themes/advanced-topics/theme-json/
* @see https://make.wordpress.org/core/2022/10/10/filters-for-theme-json-data/
* @see https://make.wordpress.org/core/2021/09/28/implementing-a-webfonts-api-in-wordpress-core/
*
* @author Joshua Gugun Siagian <suabahasa@gmail.com>
*/
class Main implements BuilderInterface
{
public function __construct()
{
add_filter('wp_theme_json_data_theme', fn($theme_json) => $this->filter_theme_json_data_theme($theme_json), 1000001);
add_filter('f!jooosi/fon/core/cache:build_css.append_content', fn($css, $rows) => $this->filter_append_build_css_content($css, $rows), 1000001, 2);
add_filter('f!jooosi/fon/core/cache:build_css.append_content', fn($css, $rows) => $this->filter_ensure_block_editor($css, $rows), 1000001, 2);
// add_action('enqueue_block_editor_assets', fn () => $this->enqueue_block_editor_assets(), 1_000_001);
// add_action('after_setup_theme', fn () => $this->after_setup_theme(), 1_000_001);
add_action('enqueue_block_assets', fn() => $this->enqueue_block_assets(), 1000001);
}
public function get_name(): string
{
return 'gutenberg';
}
/**
* @see https://make.wordpress.org/core/2022/10/10/filters-for-theme-json-data/
* @param WP_Theme_JSON_Data $theme_json
* @return WP_Theme_JSON_Data
*/
public function filter_theme_json_data_theme($theme_json)
{
$theme_json_data = $theme_json->get_data();
$theme_json_font_families = $theme_json_data['settings']['typography']['fontFamilies']['theme'] ?? [];
$font_family_presets = [];
foreach (Font::get_fonts() as $font) {
/**
* @see https://www.w3.org/TR/CSS22/syndata.html#value-def-identifier
*/
$font_family_presets[] = ['name' => $font['title'], 'slug' => Font::slugify($font['family']), 'fontFamily' => Font::css_variable($font['family'])];
}
$new_data = ['version' => WP_Theme_JSON::LATEST_SCHEMA, 'settings' => ['typography' => ['fontFamilies' => self::merge_font_family_presets($theme_json_font_families, $font_family_presets)]]];
return $theme_json->update_with($new_data);
}
public function enqueue_block_editor_assets()
{
$screen = get_current_screen();
if (is_admin() && $screen->is_block_editor()) {
add_action('admin_head', static function () {
add_filter('f!jooosi/fon/api/setting/option:index_options', static function ($options) {
Config::propertyAccessor()->setValue($options, 'cache.inline_print', \false);
return $options;
}, 1000001);
Frontpage::enqueue_css_cache();
}, 1000001);
}
}
public function after_setup_theme()
{
// Add support for editor styles.
add_theme_support('editor-styles');
add_editor_style(Cache::get_versioned_cache_url(Cache::CSS_CACHE_FILE));
}
public function enqueue_block_assets()
{
if (is_admin() && file_exists(Cache::get_cache_path(Cache::CSS_CACHE_FILE))) {
$handle = JOOOSI_FON::WP_OPTION . '-cache';
$version = Cache::get_cache_version(Cache::CSS_CACHE_FILE) ?? JOOOSI_FON::VERSION;
wp_enqueue_style($handle, Cache::get_cache_url(Cache::CSS_CACHE_FILE), [], $version);
}
}
/**
* ensure the css file is loaded to the block editor, template editor, or site editor
*/
public function filter_ensure_block_editor($css, $rows): string
{
return $css . ".wp-block, .editor-styles-wrapper { } \n\n";
}
/**
* Support for a non block-based theme.
*/
public function filter_append_build_css_content($css, $rows)
{
if (function_exists('wp_is_block_theme') && wp_is_block_theme()) {
return $css;
}
return $css . self::non_block_based_theme_support_classes();
}
public static function non_block_based_theme_support_classes(): string
{
$inline_css = '';
$fonts = Font::get_fonts();
foreach ($fonts as $font) {
$inline_css .= sprintf(".has-%s-font-family {\n", Font::slugify($font['family']));
$inline_css .= sprintf("\tfont-family: %s !important;\n", Font::css_variable($font['family']));
$inline_css .= "}\n\n";
}
return $inline_css;
}
private static function merge_font_family_presets(array $existing, array $incoming): array
{
$merged = [];
$positions = [];
foreach (array_merge($existing, $incoming) as $preset) {
$slug = is_array($preset) && isset($preset['slug']) && is_string($preset['slug']) ? $preset['slug'] : '';
if ($slug === '') {
$merged[] = $preset;
continue;
}
if (isset($positions[$slug])) {
$merged[$positions[$slug]] = $preset;
continue;
}
$positions[$slug] = count($merged);
$merged[] = $preset;
}
return array_values($merged);
}
}
@@ -0,0 +1,104 @@
<?php
/*
* This file is part of the Jooosi Fon package.
*
* (c) Joshua Gugun Siagian <suabahasa@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare (strict_types=1);
namespace JooosiFon\Builder;
use JooosiFonDeps\JOOOSI_FON;
use ReflectionClass;
use JooosiFonDeps\Symfony\Component\Finder\Finder;
/**
* @todo Remove all legacy Yabe Webfont hook shims completely in Jooosi Fon 3.0.0.
*/
class Integration
{
private static int $registered_count = 0;
/**
* List of Builders services.
*
* @var BuilderInterface[]
*/
private array $builders = [];
public function __construct()
{
$this->scan_builders();
$this->register_builders();
}
public function scan_builders()
{
// Get cached Builders
$transient_name = 'jooosi_fon_scanned_builders_' . JOOOSI_FON::VERSION;
/** @var BuilderInterface[]|false $cached */
$cached = get_transient($transient_name);
if ($cached !== \false) {
$this->builders = $cached;
return;
}
$finder = new Finder();
$finder->files()->in(__DIR__)->name('*.php');
/**
* Add additional places to scan for Builders integration.
*
* @param Finder $finder The Finder instance.
*/
do_action('a!jooosi/fon/builder/integration:before_scan', $finder);
do_action_deprecated('a!yabe/webfont/builder/integration:before_scan', [$finder], '2.1.0', 'a!jooosi/fon/builder/integration:before_scan');
foreach ($finder as $file) {
$builder_file = $file->getPathname();
if (!is_readable($builder_file)) {
continue;
}
require_once $builder_file;
}
// Find any Builders integration that extends BuilderInterface class
$declared_classes = get_declared_classes();
foreach ($declared_classes as $declared_class) {
if (!class_exists($declared_class)) {
continue;
}
$reflector = new ReflectionClass($declared_class);
if (!$reflector->isSubclassOf(\JooosiFon\Builder\BuilderInterface::class)) {
continue;
}
// Get Builders integration detail and push to Integration::$builders to be register later
/** @var BuilderInterface $builder */
$builder = $reflector->newInstanceWithoutConstructor();
$this->builders[$builder->get_name()] = ['name' => $builder->get_name(), 'file_path' => $reflector->getFileName(), 'class_name' => $reflector->getName()];
}
// Cache the Builders
set_transient($transient_name, $this->builders, \DAY_IN_SECONDS);
}
/**
* Register Builders.
*/
public function register_builders(): void
{
/**
* Filter the Builders before register.
*
* @param BuilderInterface[] $builders
* @return BuilderInterface[]
*/
/** @var BuilderInterface[] $builders */
$builders = apply_filters('f!jooosi/fon/builder/integration:register_builders', $this->builders);
$builders = apply_filters_deprecated('f!yabe/webfont/builder/integration:register_builders', [$builders], '2.1.0', 'f!jooosi/fon/builder/integration:register_builders');
self::$registered_count = count($builders);
foreach ($builders as $builder) {
// Create new instance of Builder class
/** @var BuilderInterface $builderInstance */
$builderInstance = new $builder['class_name']();
$this->builders[$builder['name']]['instance'] = $builderInstance;
}
}
public static function get_registered_count(): int
{
return self::$registered_count;
}
}
@@ -0,0 +1,79 @@
<?php
/*
* This file is part of the Jooosi Fon package.
*
* (c) Joshua Gugun Siagian <suabahasa@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare (strict_types=1);
namespace JooosiFon\Builder\Kadence;
use JooosiFonDeps\JOOOSI_FON;
use JooosiFon\Builder\BuilderInterface;
use JooosiFon\Utils\Font;
/**
* Kadence integration.
*
* @author Joshua Gugun Siagian <suabahasa@gmail.com>
*/
class Main implements BuilderInterface
{
public function __construct()
{
add_filter('kadence_theme_custom_fonts', fn($fonts) => $this->theme_custom_fonts($fonts), 1000001);
add_action('enqueue_block_editor_assets', fn() => $this->register_block_editor_assets(), 1000001);
/**
* Disable Kadence's built-in Google Fonts.
*/
add_action('customize_controls_enqueue_scripts', fn() => $this->action_theme_customizer_google_fonts(), 1000001);
add_action('customize_preview_init', fn() => $this->action_theme_customizer_preview(), 1000001);
add_action('enqueue_block_editor_assets', fn() => $this->block_editor_remove_google_fonts(), 1000001);
}
public function get_name(): string
{
return 'kadence';
}
public function action_theme_customizer_google_fonts()
{
if (wp_script_is('kadence-customizer-controls', 'registered')) {
wp_add_inline_script('kadence-customizer-controls', 'kadenceCustomizerControlsData.gfontvars = [];', 'before');
}
}
public function action_theme_customizer_preview()
{
if (wp_script_is('kadence-webfont-js', 'registered')) {
wp_dequeue_script('kadence-webfont-js');
}
}
public function block_editor_remove_google_fonts()
{
if (wp_script_is('kadence-blocks-js', 'registered')) {
wp_add_inline_script('kadence-blocks-js', 'kadence_blocks_params.g_fonts = [];', 'before');
wp_add_inline_script('kadence-blocks-js', 'kadence_blocks_params.g_font_names = [];', 'before');
}
}
public function register_block_editor_assets()
{
if (wp_script_is('kadence-blocks-js', 'registered')) {
$jooosi_fonts = [];
$fonts = Font::get_fonts();
foreach ($fonts as $font) {
$jooosi_fonts[] = ['label' => $font['title'], 'value' => $font['family'], 'google' => \false, 'weights' => [['value' => '100', 'label' => 'Thin 100'], ['value' => '200', 'label' => 'Extra-Light 200'], ['value' => '300', 'label' => 'Light 300'], ['value' => '400', 'label' => 'Regular'], ['value' => '500', 'label' => 'Medium 500'], ['value' => '600', 'label' => 'Semi-Bold 600'], ['value' => '700', 'label' => 'Bold 700'], ['value' => '800', 'label' => 'Extra-Bold 800'], ['value' => '900', 'label' => 'Ultra-Bold 900']], 'styles' => [['value' => 'normal', 'label' => 'Normal'], ['value' => 'italic', 'label' => 'Italic']]];
}
wp_enqueue_script('jooosi-fon-for-kadence-blocks', plugin_dir_url(__FILE__) . 'assets/script/kadence-blocks.js', ['kadence-blocks-js'], JOOOSI_FON::VERSION, \true);
wp_localize_script('jooosi-fon-for-kadence-blocks', 'jooosiFonKadenceBlocks', ['fonts' => $jooosi_fonts]);
}
}
public function theme_custom_fonts($kadence_fonts)
{
$fonts = Font::get_fonts();
$v = ['100', '100italic', '200', '200italic', '300', '300italic', 'regular', 'italic', '500', '500italic', '600', '600italic', '700', '700italic', '800', '800italic', '900', '900italic'];
foreach ($fonts as $font) {
$kadence_fonts[$font['family']] = ['v' => $v];
}
return $kadence_fonts;
}
}
@@ -0,0 +1,15 @@
function jooosi_fon_add_fonts(options) {
const { __ } = wp.i18n;
const jooosi_fonts = [
{
type: 'group',
label: __('Jooosi Fon', 'jooosi-fon'),
options: jooosiFonKadenceBlocks.fonts,
},
];
options = jooosi_fonts.concat(options);
return options;
}
wp.hooks.addFilter('kadence.typography_options', 'jooosi/fon/add_fonts', jooosi_fon_add_fonts);
@@ -0,0 +1,44 @@
<?php
/*
* This file is part of the Jooosi Fon package.
*
* (c) Joshua Gugun Siagian <suabahasa@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare (strict_types=1);
namespace JooosiFon\Builder\Pinegrow;
use JooosiFonDeps\JOOOSI_FON;
use JooosiFon\Admin\AdminPage;
use JooosiFon\Builder\BuilderInterface;
use JooosiFon\Core\Cache;
use JooosiFon\Utils\Font;
/**
* Pinegrow integration.
*
* @author Joshua Gugun Siagian <suabahasa@gmail.com>
*/
class Main implements BuilderInterface
{
public function __construct()
{
add_action('admin_menu', static fn() => AdminPage::add_redirect_submenu_page('pinegrow-projects'), 1000001);
add_action('load-toplevel_page_pinegrow-projects', fn() => $this->init_hooks());
}
public function get_name(): string
{
return 'pinegrow';
}
public function init_hooks(): void
{
add_action('admin_enqueue_scripts', fn() => $this->enqueue_scripts(), 1000001);
}
public function enqueue_scripts()
{
wp_enqueue_script('jooosi-fon-for-pinegrow', plugin_dir_url(__FILE__) . 'assets/script/pinegrow.js', [], JOOOSI_FON::VERSION, \true);
wp_localize_script('jooosi-fon-for-pinegrow', 'jooosiFonPinegrow', ['stylesheet_url' => Cache::get_versioned_cache_url(Cache::CSS_CACHE_FILE), 'font_families' => array_map(static fn($f) => ['name' => $f['title'], 'key' => $f['css']['variable'], 'family' => $f['family']], Font::get_fonts())]);
}
}
@@ -0,0 +1,81 @@
document.addEventListener('DOMContentLoaded', async function () {
await new Promise(resolve => {
let waitingForEditor = setInterval(() => {
if (
window.frames[0].pinegrow?.getSelectedPage() !== null
&& window.frames[0].pinegrow?.getSelectedPage() !== undefined
) {
clearInterval(waitingForEditor);
resolve();
}
}, 3000);
});
// add stylesheet
window.frames[0].pinegrow.getSelectedPage().addStylesheet(window.jooosiFonPinegrow.stylesheet_url);
// style tab
await new Promise(resolve => {
let waitingForFontFamily = setInterval(() => {
try {
if (
window.frames[0].$.fn.crsa.defaults.rulesDefinition.sections.text.fields['font-family'] !== null
&& window.frames[0].$.fn.crsa.defaults.rulesDefinition.sections.text.fields['font-family'] !== undefined
) {
clearInterval(waitingForFontFamily);
resolve();
}
} catch (err) { }
}, 100);
});
window.frames[0].$.fn.crsa.defaults.rulesDefinition.sections.text.fields['font-family'].options = function () {
return window.jooosiFonPinegrow.font_families || [];
};
// design tab
await new Promise(resolve => {
let waitingForFontLibrary = setInterval(() => {
try {
if (
window.frames[0].pinegrow.fontLibrary !== null
&& window.frames[0].pinegrow.fontLibrary !== undefined
) {
clearInterval(waitingForFontLibrary);
resolve();
}
} catch (err) { }
}, 100);
});
const preservedSystemFonts = [];
window.frames[0].pinegrow.fontLibrary.forEachFont(font => {
if (font.type === 'system') {
preservedSystemFonts.push(font);
}
});
const fontSystemClass = window.frames[0].pinegrow.fontLibrary.getFontClassForType('system');
window.frames[0].pinegrow.fontLibrary.removeAll();
window.jooosiFonPinegrow.font_families.forEach(font => {
const pfs = new fontSystemClass({
type: 'system',
family: font.family,
usage: 'all',
category: 'sans-serif',
w: '100, 200, 300, 400, 500, 600, 700, 800, 900'.split(/,\s?/)
});
window.frames[0].pinegrow.fontLibrary.addFont(pfs);
});
preservedSystemFonts.forEach(font => {
window.frames[0].pinegrow.fontLibrary.addFont(font);
});
window.frames[0].pinegrow.fontLibrary.save();
});
@@ -0,0 +1,419 @@
<?php
/*
* This file is part of the Jooosi Fon package.
*
* (c) Joshua Gugun Siagian <suabahasa@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare (strict_types=1);
namespace JooosiFon\Core;
use JooosiFonDeps\JOOOSI_FON;
use JooosiFon\Core\Cache\FontCacheSnapshotBuilder;
use JooosiFon\Core\Cache\FontCssRenderer;
use JooosiFon\Core\Cache\FontPreloadRenderer;
use JooosiFon\Upgrade\LegacyRebrandUpgrade;
use JooosiFon\Utils\Common;
use JooosiFon\Utils\Config;
use JooosiFon\Utils\Notice;
/**
* Manage the cache of fonts for the frontpage.
*
* @author Joshua Gugun Siagian <suabahasa@gmail.com>
* @todo Remove all legacy Yabe Webfont hook shims completely in Jooosi Fon 3.0.0.
*/
class Cache
{
/**
* @var string
*/
public const CSS_CACHE_FILE = 'fonts.css';
/**
* @var string
*/
public const PRELOAD_HTML_FILE = 'preload.html';
/**
* @var string
*/
public const CACHE_DIR = '/jooosi-fon/cache/';
/**
* @var string
*/
public static $typekit_embed = 'css';
public function __construct()
{
$this->migrate_legacy_scheduled_cache();
add_action('a!jooosi/fon/core/cache:build_cache', fn() => $this->build_cache());
// listen to fonts event for cache build (async/scheduled)
add_action('a!jooosi/fon/api/font:fonts_event_async', fn() => $this->schedule_cache(), 10, 1);
// listen to fonts event for cache build (sync)
add_action('a!jooosi/fon/api/font:fonts_event', fn() => $this->build_cache(), 10, 1);
// listen to theme switch for cache build (async/scheduled)
add_action('switch_theme', fn() => $this->schedule_cache(), 1000001);
// listen to Config change for cache build (async/scheduled)
add_action('f!jooosi/fon/api/setting/option:after_store', fn() => $this->schedule_cache(), 10, 1);
// listen to plugin upgrade for cache build (async/scheduled)
add_action('a!jooosi/fon/plugins:upgrade_plugin_end', fn() => $this->schedule_cache(), 10, 1);
$this->maybeRebuildAfterLegacyUpgrade();
}
public function schedule_cache(): void
{
self::updateBuildStatus(['state' => 'pending', 'requested_at' => time(), 'changed' => \false, 'warnings' => [], 'error' => '']);
if (!wp_next_scheduled('a!jooosi/fon/core/cache:build_cache')) {
$scheduled = wp_schedule_single_event(time() + 10, 'a!jooosi/fon/core/cache:build_cache');
if ($scheduled === \false) {
self::updateBuildStatus(['state' => 'failed', 'error' => 'The cache build could not be scheduled.', 'completed_at' => time()]);
}
}
}
public static function get_cache_path(string $file_path = ''): string
{
return wp_upload_dir()['basedir'] . self::CACHE_DIR . $file_path;
}
public static function get_cache_url(string $file_path = ''): string
{
return wp_upload_dir()['baseurl'] . self::CACHE_DIR . $file_path;
}
public static function get_versioned_cache_url(string $filePath): string
{
$url = self::get_cache_url($filePath);
$version = self::get_cache_version($filePath);
return $version !== null ? add_query_arg('ver', $version, $url) : $url;
}
public static function get_cache_version(string $filePath): ?string
{
$path = self::get_cache_path($filePath);
if (!is_readable($path)) {
return null;
}
$hash = hash_file('sha256', $path);
return is_string($hash) ? substr($hash, 0, 16) : null;
}
public function build_cache(): void
{
try {
$lock = $this->acquireBuildLock();
} catch (\Throwable $throwable) {
$message = sprintf('Failed to start the font cache build: %s', $throwable->getMessage());
self::updateBuildStatus(['state' => 'failed', 'completed_at' => time(), 'changed' => \false, 'warnings' => [], 'error' => $message]);
Notice::error($message, 'jooosi-fon-cache-build', \true);
return;
}
if ($lock === \false) {
return;
}
self::updateBuildStatus(['state' => 'running', 'started_at' => time(), 'changed' => \false, 'warnings' => [], 'error' => '']);
try {
$artifacts = self::buildArtifacts();
$payload = sprintf("/*\n! %s v%s | %s\n*/\n\n%s", Common::plugin_data('Name'), JOOOSI_FON::VERSION, date('Y-m-d H:i:s', time()), $artifacts['css']);
$cssPath = self::get_cache_path(self::CSS_CACHE_FILE);
$preloadPath = self::get_cache_path(self::PRELOAD_HTML_FILE);
self::publishArtifacts($payload, $artifacts['preload'], $cssPath, $preloadPath);
$this->purge_cache_plugin();
self::updateBuildStatus(['state' => 'succeeded', 'completed_at' => time(), 'hash' => hash('sha256', $payload . "\x00" . $artifacts['preload']), 'changed' => \true, 'warnings' => $artifacts['warnings'], 'error' => '']);
do_action('a!jooosi/fon/core/cache:build_succeeded', \true, $artifacts['warnings']);
} catch (\Throwable $throwable) {
$message = sprintf('Failed to build the font cache: %s', $throwable->getMessage());
self::updateBuildStatus(['state' => 'failed', 'completed_at' => time(), 'changed' => \false, 'warnings' => [], 'error' => $message]);
Notice::error($message, 'jooosi-fon-cache-build', \true);
do_action('a!jooosi/fon/core/cache:build_failed', $throwable);
} finally {
flock($lock, \LOCK_UN);
fclose($lock);
}
}
public static function build_css(): string
{
return self::buildArtifacts()['css'];
}
public static function build_preload(): string
{
return self::buildArtifacts()['preload'];
}
public static function get_kit_css($kit_id, ?array &$warnings = null): string
{
$kitId = trim((string) $kit_id);
if (preg_match('/^[a-zA-Z0-9_-]{1,100}$/', $kitId) !== 1) {
self::adobeWarning($warnings, 'Adobe Fonts CSS was skipped because the project ID is invalid.');
return '';
}
$cachePath = self::get_cache_path('adobe/' . hash('sha256', $kitId) . '.css');
$cachedCss = is_readable($cachePath) ? file_get_contents($cachePath) : \false;
$cachedCss = is_string($cachedCss) ? $cachedCss : '';
if (!self::isSafeStylesheet($cachedCss)) {
$cachedCss = '';
}
$ttl = max(300, (int) apply_filters('f!jooosi/fon/core/cache:adobe_css_ttl', 12 * \HOUR_IN_SECONDS));
if ($cachedCss !== '' && filemtime($cachePath) > time() - $ttl) {
return $cachedCss;
}
$response = wp_safe_remote_get(sprintf('https://use.typekit.net/%s.css', rawurlencode($kitId)), ['timeout' => 15, 'redirection' => 2, 'limit_response_size' => 2 * \MB_IN_BYTES]);
if (is_wp_error($response)) {
return self::adobeFallback($cachedCss, $warnings, 'Adobe Fonts could not be refreshed.');
}
$status = wp_remote_retrieve_response_code($response);
if ($status === 412) {
self::$typekit_embed = 'js';
return '';
}
if ($status !== 200) {
return self::adobeFallback($cachedCss, $warnings, sprintf('Adobe Fonts returned HTTP %d.', $status));
}
$body = wp_remote_retrieve_body($response);
if (!is_string($body) || !self::isSafeStylesheet($body)) {
return self::adobeFallback($cachedCss, $warnings, 'Adobe Fonts returned an invalid stylesheet.');
}
try {
self::publishArtifact($body, $cachePath);
} catch (\Throwable $throwable) {
self::adobeWarning($warnings, 'Adobe Fonts CSS was refreshed but could not be cached separately.');
}
return $body;
}
public static function get_kit_js($kit_id): string
{
$kitId = trim((string) $kit_id);
if (preg_match('/^[a-zA-Z0-9_-]{1,100}$/', $kitId) !== 1) {
return '';
}
$response = wp_safe_remote_get(sprintf('https://use.typekit.net/%s.js', rawurlencode($kitId)), ['timeout' => 15, 'redirection' => 2, 'limit_response_size' => 2 * \MB_IN_BYTES]);
if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
return '';
}
$body = wp_remote_retrieve_body($response);
if (!is_string($body) || trim($body) === '') {
return '';
}
$js = '<script type="text/javascript">';
$js .= $body;
$js .= "\n\n";
$js .= sprintf('try{Typekit.load({kitId:%s,scriptTimeout:3E3,async:true});}catch(e){}', wp_json_encode($kitId));
$js .= '</script>';
return "\n\n" . $js . "\n\n";
}
/**
* @return array<string, mixed>
*/
public static function getBuildStatus(): array
{
$status = get_option(JOOOSI_FON::WP_OPTION . '_cache_build_status', []);
return is_array($status) ? $status : [];
}
/**
* @return array{css: string, preload: string, warnings: string[]}
*/
private static function buildArtifacts(): array
{
self::$typekit_embed = 'css';
$snapshot = (new FontCacheSnapshotBuilder())->build();
$warnings = $snapshot['warnings'];
$adobeCss = '';
$projectId = trim((string) Config::get('adobe_fonts.project_id', ''));
$hasAdobeFonts = in_array('adobe-fonts', array_column($snapshot['fonts'], 'type'), \true);
if ($projectId !== '' && $hasAdobeFonts) {
$adobeCss = self::get_kit_css($projectId, $warnings);
}
$css = (new FontCssRenderer())->render($snapshot['fonts'], $adobeCss);
/**
* @param string $css The CSS content
* @param array $rows The active database rows
* @return string The CSS content
*/
$css = apply_filters('f!jooosi/fon/core/cache:build_css.append_content', $css, $snapshot['rows']);
$css = apply_filters_deprecated('f!yabe/webfont/core/cache:build_css.append_content', [$css, $snapshot['rows']], '2.1.0', 'f!jooosi/fon/core/cache:build_css.append_content');
if (!is_string($css)) {
throw new \UnexpectedValueException('The font CSS filter must return a string.');
}
$preloadLimit = (int) apply_filters('f!jooosi/fon/core/cache:preload_limit', 6);
$preload = (new FontPreloadRenderer())->render($snapshot['fonts'], $preloadLimit);
if (self::$typekit_embed === 'js' && $projectId !== '' && $hasAdobeFonts) {
$preload .= self::get_kit_js($projectId);
}
foreach ($warnings as $warning) {
do_action('a!jooosi/fon/core/cache:build_warning', $warning);
}
return ['css' => $css, 'preload' => $preload, 'warnings' => array_values(array_unique($warnings))];
}
/**
* @return resource|false
*/
private function acquireBuildLock()
{
$directory = self::get_cache_path();
if (!is_dir($directory) && !wp_mkdir_p($directory)) {
throw new \RuntimeException('The font cache directory could not be created.');
}
$lock = fopen($directory . '.build.lock', 'c');
if ($lock === \false) {
throw new \RuntimeException('The font cache build lock could not be opened.');
}
if (!flock($lock, \LOCK_EX | \LOCK_NB)) {
fclose($lock);
return \false;
}
return $lock;
}
private static function publishArtifacts(string $css, string $preload, string $cssPath, string $preloadPath): void
{
$cssTemp = self::stageArtifact($css, $cssPath);
$preloadTemp = null;
try {
$preloadTemp = self::stageArtifact($preload, $preloadPath);
if (!rename($preloadTemp, $preloadPath)) {
throw new \RuntimeException('The font preload cache could not be published.');
}
$preloadTemp = null;
if (!rename($cssTemp, $cssPath)) {
throw new \RuntimeException('The font CSS cache could not be published.');
}
$cssTemp = null;
} finally {
if (is_string($cssTemp) && file_exists($cssTemp)) {
unlink($cssTemp);
}
if (is_string($preloadTemp) && file_exists($preloadTemp)) {
unlink($preloadTemp);
}
}
}
private static function publishArtifact(string $contents, string $path): void
{
$temporaryPath = self::stageArtifact($contents, $path);
try {
if (!rename($temporaryPath, $path)) {
throw new \RuntimeException('The cache artifact could not be published.');
}
$temporaryPath = null;
} finally {
if (is_string($temporaryPath) && file_exists($temporaryPath)) {
unlink($temporaryPath);
}
}
}
private static function stageArtifact(string $contents, string $path): string
{
$directory = dirname($path);
if (!is_dir($directory) && !wp_mkdir_p($directory)) {
throw new \RuntimeException('The cache artifact directory could not be created.');
}
$temporaryPath = tempnam($directory, '.jooosi-fon-');
if (!is_string($temporaryPath)) {
throw new \RuntimeException('A temporary cache artifact could not be created.');
}
$written = file_put_contents($temporaryPath, $contents, \LOCK_EX);
if ($written === \false || $written !== strlen($contents)) {
unlink($temporaryPath);
throw new \RuntimeException('A cache artifact could not be written completely.');
}
$permissions = defined('FS_CHMOD_FILE') ? \FS_CHMOD_FILE : 0644;
chmod($temporaryPath, $permissions);
return $temporaryPath;
}
/**
* @param array<string, mixed> $status
*/
private static function updateBuildStatus(array $status): void
{
update_option(JOOOSI_FON::WP_OPTION . '_cache_build_status', array_merge(self::getBuildStatus(), $status), \false);
}
private static function adobeWarning(?array &$warnings, string $message): void
{
if ($warnings !== null && count($warnings) < 100) {
$warnings[] = $message;
}
}
private static function adobeFallback(string $cachedCss, ?array &$warnings, string $message): string
{
if ($cachedCss === '') {
throw new \RuntimeException($message . ' No cached stylesheet is available.');
}
self::adobeWarning($warnings, $message . ' The last-known-good stylesheet was retained.');
return $cachedCss;
}
private static function isSafeStylesheet(string $css): bool
{
return trim($css) !== '' && stripos($css, '</style') === \false;
}
/**
* @todo Remove this legacy cron migration completely in Jooosi Fon 3.0.0.
*/
private function migrate_legacy_scheduled_cache(): void
{
$legacyHook = 'a!yabe/webfont/core/cache:build_cache';
$hook = 'a!jooosi/fon/core/cache:build_cache';
$legacyTimestamp = wp_next_scheduled($legacyHook);
if ($legacyTimestamp === \false) {
return;
}
if (!wp_next_scheduled($hook)) {
wp_schedule_single_event(max(time() + 1, $legacyTimestamp), $hook);
}
wp_clear_scheduled_hook($legacyHook);
}
/**
* Rebuild generated files immediately after upload paths have moved so a
* frontend request never prints cache content containing legacy URLs.
*
* @todo Remove this legacy cache rebuild completely in Jooosi Fon 3.0.0.
*/
private function maybeRebuildAfterLegacyUpgrade(): void
{
if (get_option(LegacyRebrandUpgrade::CACHE_REBUILD_OPTION, \false) === \false) {
return;
}
self::updateBuildStatus(['state' => 'pending', 'requested_at' => time(), 'changed' => \false, 'warnings' => [], 'error' => '']);
$this->build_cache();
if ((self::getBuildStatus()['state'] ?? null) === 'succeeded') {
delete_option(LegacyRebrandUpgrade::CACHE_REBUILD_OPTION);
}
}
/**
* Clear the cache from various cache plugins.
*/
private function purge_cache_plugin()
{
/**
* Only invalidate this plugin's font catalog. Flushing the complete
* WordPress object cache can create a site-wide performance spike.
* @see https://developer.wordpress.org/reference/classes/wp_object_cache/
*/
\wp_cache_delete('get_fonts', JOOOSI_FON::WP_OPTION);
do_action('a!jooosi/fon/core/cache:before_page_cache_purge');
/**
* WP Rocket
* @see https://docs.wp-rocket.me/article/92-rocketcleandomain
*/
if (function_exists('rocket_clean_domain')) {
\rocket_clean_domain();
}
/**
* WP Super Cache
* @see https://github.com/Automattic/wp-super-cache/blob/a0872032b1b3fc6847f490eadfabf74c12ad0135/wp-cache-phase2.php#L3013
*/
if (function_exists('wp_cache_clear_cache')) {
\wp_cache_clear_cache();
}
/**
* W3 Total Cache
* @see https://github.com/BoldGrid/w3-total-cache/blob/3a094493064ea60d727b3389dee813639860ef49/w3-total-cache-api.php#L259
*/
if (function_exists('w3tc_flush_all')) {
\w3tc_flush_all();
}
/**
* WP Fastest Cache
* @see https://www.wpfastestcache.com/tutorial/delete-the-cache-by-calling-the-function/
*/
if (function_exists('wpfc_clear_all_cache')) {
\wpfc_clear_all_cache(\true);
}
/**
* LiteSpeed Cache
* @see https://docs.litespeedtech.com/lscache/lscwp/api/#purge-all-existing-caches
*/
do_action('litespeed_purge_all');
}
}
@@ -0,0 +1,204 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Core\Cache;
use JooosiFon\Api\Support\FontCodec;
use JooosiFon\Database\FontTable;
use JooosiFon\Utils\Font;
/**
* Reads active font records once and converts them into a safe, predictable
* representation shared by the stylesheet and preload renderers.
*/
final class FontCacheSnapshotBuilder
{
/**
* @return array{fonts: array<int, array<string, mixed>>, rows: array<int, object>, warnings: string[]}
*/
public function build(): array
{
global $wpdb;
// Cache generation may be the first request after a failed update.
// Ensure the table exists even when migration history is stale.
FontTable::ensure();
$rows = $wpdb->get_results("\n SELECT id, type, family, metadata, font_faces\n FROM {$wpdb->prefix}jooosi_fon_fonts\n WHERE status = 1\n AND deleted_at IS NULL\n ORDER BY type ASC, family ASC, id ASC\n ");
if ($wpdb->last_error) {
throw new \RuntimeException($wpdb->last_error);
}
if (!is_array($rows)) {
throw new \RuntimeException('The active font records could not be loaded.');
}
$fonts = [];
$warnings = [];
foreach ($rows as $row) {
try {
$metadata = FontCodec::decode((string) $row->metadata, \true);
$fontFaces = FontCodec::decode((string) $row->font_faces, \true);
} catch (\Throwable $throwable) {
$this->warn($warnings, sprintf('Font #%d was skipped because its stored payload is invalid.', (int) $row->id));
continue;
}
if (!is_array($metadata) || !is_array($fontFaces)) {
$this->warn($warnings, sprintf('Font #%d was skipped because its stored payload has an invalid shape.', (int) $row->id));
continue;
}
$family = trim((string) $row->family);
if ($family === '' || preg_match('//u', $family) !== 1) {
$this->warn($warnings, sprintf('Font #%d was skipped because its family name is missing or invalid.', (int) $row->id));
continue;
}
[$selector, $fallback] = $this->fontSelector((string) ($metadata['selector'] ?? ''));
$faces = [];
foreach ($fontFaces as $faceIndex => $fontFace) {
if (!is_array($fontFace)) {
$this->warn($warnings, sprintf('Font #%d face #%d was skipped because it is invalid.', (int) $row->id, (int) $faceIndex + 1));
continue;
}
if (array_key_exists('isEnabled', $fontFace) && filter_var($fontFace['isEnabled'], \FILTER_VALIDATE_BOOLEAN) !== \true) {
continue;
}
$normalizedFace = $this->normalizeFace($fontFace, (int) $row->id, (int) $faceIndex, $warnings);
if ($normalizedFace !== null) {
$faces[] = $normalizedFace;
}
}
if ($faces === [] && $row->type !== 'adobe-fonts') {
$this->warn($warnings, sprintf('Font #%d was skipped because it has no usable font files.', (int) $row->id));
continue;
}
$fonts[] = ['id' => (int) $row->id, 'type' => (string) $row->type, 'family' => $family, 'custom_property' => Font::css_custom_property($family), 'legacy_custom_property' => Font::legacy_css_custom_property($family), 'display' => $this->display((string) ($metadata['display'] ?? 'auto'), 'auto'), 'preload' => filter_var($metadata['preload'] ?? \false, \FILTER_VALIDATE_BOOLEAN), 'selector' => $selector, 'fallback' => $fallback, 'faces' => $faces];
}
return ['fonts' => $fonts, 'rows' => $rows, 'warnings' => $warnings];
}
/**
* @param array<string, mixed> $face
* @param string[] $warnings
* @return array<string, mixed>|null
*/
private function normalizeFace(array $face, int $fontId, int $faceIndex, array &$warnings): ?array
{
$files = [];
$seenExtensions = [];
foreach ((array) ($face['files'] ?? []) as $file) {
if (!is_array($file)) {
continue;
}
$extension = strtolower((string) ($file['extension'] ?? ''));
$attachmentId = (int) ($file['attachment_id'] ?? 0);
$mime = $this->mime($extension);
if ($attachmentId < 1 || $mime === null || isset($seenExtensions[$extension])) {
continue;
}
$url = wp_get_attachment_url($attachmentId);
if (!is_string($url) || $url === '') {
$this->warn($warnings, sprintf('Font #%d face #%d references a missing attachment.', $fontId, $faceIndex + 1));
continue;
}
$seenExtensions[$extension] = \true;
$files[] = ['attachment_id' => $attachmentId, 'url' => $url, 'extension' => $extension, 'mime' => $mime, 'format' => $this->format($extension)];
}
if ($files === []) {
$this->warn($warnings, sprintf('Font #%d face #%d was skipped because it has no usable files.', $fontId, $faceIndex + 1));
return null;
}
usort($files, static function (array $left, array $right): int {
$precedence = ['woff2' => 1, 'woff' => 2, 'ttf' => 3, 'otf' => 4, 'eot' => 5];
return $precedence[$left['extension']] <=> $precedence[$right['extension']];
});
return ['weight' => $this->weight($face['weight'] ?? 400), 'width' => $this->width($face['width'] ?? '100%'), 'style' => $this->style((string) ($face['style'] ?? 'normal')), 'display' => $this->display((string) ($face['display'] ?? ''), ''), 'selector' => $this->selector((string) ($face['selector'] ?? '')), 'comment' => $this->comment((string) ($face['comment'] ?? '')), 'unicode_range' => $this->unicodeRange((string) ($face['unicodeRange'] ?? '')), 'preload' => filter_var($face['preload'] ?? \false, \FILTER_VALIDATE_BOOLEAN), 'files' => $files];
}
/**
* @return array{0: string, 1: string}
*/
private function fontSelector(string $value): array
{
$parts = array_map('trim', explode('|', $value, 2));
$selector = $this->selector($parts[0] ?? '');
$fallback = trim($parts[1] ?? '');
if ($fallback !== '' && (strlen($fallback) > 500 || preg_match('/[^a-zA-Z0-9\s,_\'"-]/', $fallback) !== 0 || substr_count($fallback, "'") % 2 !== 0 || substr_count($fallback, '"') % 2 !== 0)) {
$fallback = '';
}
return [$selector, $fallback];
}
private function selector(string $value): string
{
$value = trim($value);
if ($value === '' || strlen($value) > 1000 || preg_match('/[<{};@]|\/\*|\*\/|[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) !== 0) {
return '';
}
return $value;
}
private function comment(string $value): string
{
$value = trim(str_replace(['/*', '*/', '<'], ['', '* /', '\3C '], $value));
return strlen($value) <= 500 ? $value : substr($value, 0, 500);
}
private function style(string $value): string
{
$value = trim(strtolower($value));
return preg_match('/^(?:normal|italic|oblique(?:\s+-?\d+(?:\.\d+)?deg(?:\s+-?\d+(?:\.\d+)?deg)?)?)$/', $value) ? $value : 'normal';
}
/**
* @param mixed $value
*/
private function weight($value): string
{
$value = trim((string) $value);
if (in_array($value, ['normal', 'bold'], \true)) {
return $value;
}
if (preg_match('/^[1-9]\d{0,3}(?:\s+[1-9]\d{0,3})?$/', $value) !== 1) {
return '400';
}
foreach (preg_split('/\s+/', $value) ?: [] as $weight) {
if ((int) $weight < 1 || (int) $weight > 1000) {
return '400';
}
}
return $value;
}
/**
* @param mixed $value
*/
private function width($value): string
{
$value = trim((string) $value);
$keywords = ['normal', 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'];
if (in_array($value, $keywords, \true) || preg_match('/^\d+(?:\.\d+)?%(?:\s+\d+(?:\.\d+)?%)?$/', $value) === 1) {
return $value;
}
return '100%';
}
private function display(string $value, string $fallback): string
{
$value = strtolower(trim($value));
return in_array($value, ['auto', 'block', 'swap', 'fallback', 'optional'], \true) ? $value : $fallback;
}
private function unicodeRange(string $value): string
{
$value = trim($value);
if ($value === '') {
return '';
}
return preg_match('/^U\+[0-9A-F?]{1,6}(?:-[0-9A-F]{1,6})?(?:\s*,\s*U\+[0-9A-F?]{1,6}(?:-[0-9A-F]{1,6})?)*$/i', $value) ? $value : '';
}
private function mime(string $extension): ?string
{
$mimes = ['woff2' => 'font/woff2', 'woff' => 'font/woff', 'ttf' => 'font/ttf', 'otf' => 'font/otf', 'eot' => 'font/eot'];
return $mimes[$extension] ?? null;
}
private function format(string $extension): string
{
$formats = ['ttf' => 'truetype', 'otf' => 'opentype', 'eot' => 'embedded-opentype'];
return $formats[$extension] ?? $extension;
}
/**
* @param string[] $warnings
*/
private function warn(array &$warnings, string $message): void
{
if (count($warnings) < 100) {
$warnings[] = $message;
}
}
}
@@ -0,0 +1,82 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Core\Cache;
/**
* Pure renderer for an already validated font-cache snapshot.
*
* @phpstan-type CacheFile array{attachment_id: int, url: string, extension: string, mime: string, format: string}
* @phpstan-type CacheFace array{weight: string, width: string, style: string, display: string, selector: string, comment: string, unicode_range: string, preload: bool, files: array<int, CacheFile>}
* @phpstan-type CacheFont array{id: int, type: string, family: string, custom_property: string, legacy_custom_property: string, display: string, preload: bool, selector: string, fallback: string, faces: array<int, CacheFace>}
*/
final class FontCssRenderer
{
/**
* @param array<int, CacheFont> $fonts
*/
public function render(array $fonts, string $adobeCss = ''): string
{
$css = trim($adobeCss);
$css = $css !== '' ? $css . "\n\n" : '';
foreach ($fonts as $font) {
foreach ($font['faces'] as $face) {
if ($face['files'] === []) {
continue;
}
if ($face['comment'] !== '') {
$css .= sprintf("/* %s */\n", $face['comment']);
}
$sources = array_map(function (array $file): string {
return sprintf("url('%s') format('%s')", $this->escapeString($file['url']), $this->escapeString($file['format']));
}, $face['files']);
$display = $face['display'] !== '' ? $face['display'] : $font['display'];
$css .= "@font-face {\n";
$css .= sprintf("\tfont-family: '%s';\n", $this->escapeString($font['family']));
$css .= sprintf("\tfont-style: %s;\n", $face['style']);
$css .= sprintf("\tfont-weight: %s;\n", $face['weight']);
$css .= sprintf("\tfont-stretch: %s;\n", $face['width']);
$css .= sprintf("\tfont-display: %s;\n", $display);
$css .= sprintf("\tsrc: %s;\n", implode(",\n\t\t", $sources));
if ($face['unicode_range'] !== '') {
$css .= sprintf("\tunicode-range: %s;\n", $face['unicode_range']);
}
$css .= "}\n\n";
}
}
$variables = [];
foreach ($fonts as $font) {
$fallback = $font['fallback'] !== '' ? ', ' . $font['fallback'] : '';
$variables[$font['custom_property']] = ['legacy_property' => $font['legacy_custom_property'], 'value' => sprintf("'%s'%s", $this->escapeString($font['family']), $fallback)];
}
if ($variables !== []) {
$css .= ":root {\n";
foreach ($variables as $property => $variable) {
$css .= sprintf("\t%s: %s;\n", $property, $variable['value']);
// TODO: Remove this legacy CSS property alias completely in Jooosi Fon 3.0.0.
$css .= sprintf("\t%s: var(%s);\n", $variable['legacy_property'], $property);
}
$css .= "}\n\n";
}
foreach ($fonts as $font) {
if ($font['selector'] !== '') {
$css .= sprintf("%s {\n\tfont-family: var(%s);\n}\n\n", $font['selector'], $font['custom_property']);
}
foreach ($font['faces'] as $face) {
if ($face['selector'] === '') {
continue;
}
$css .= sprintf("%s {\n", $face['selector']);
$css .= sprintf("\tfont-family: var(%s);\n", $font['custom_property']);
$css .= sprintf("\tfont-style: %s;\n", $face['style']);
$css .= sprintf("\tfont-weight: %s;\n", $face['weight']);
$css .= "}\n\n";
}
}
return $css;
}
private function escapeString(string $value): string
{
return str_replace(['\\', "'", '<', "\r", "\n", "\f"], ['\\\\', "\\'", '\3C ', '\D ', '\A ', '\C '], $value);
}
}
@@ -0,0 +1,47 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Core\Cache;
/**
* Pure renderer for the bounded set of critical WOFF2 preload resources.
*
* @phpstan-type CacheFile array{attachment_id: int, url: string, extension: string, mime: string, format: string}
* @phpstan-type CacheFace array{weight: string, width: string, style: string, display: string, selector: string, comment: string, unicode_range: string, preload: bool, files: array<int, CacheFile>}
* @phpstan-type CacheFont array{id: int, type: string, family: string, custom_property: string, legacy_custom_property: string, display: string, preload: bool, selector: string, fallback: string, faces: array<int, CacheFace>}
*/
final class FontPreloadRenderer
{
/**
* @param array<int, CacheFont> $fonts
*/
public function render(array $fonts, int $limit = 6): string
{
$limit = max(0, min(50, $limit));
if ($limit === 0) {
return '';
}
$resources = [];
foreach ($fonts as $font) {
foreach ($font['faces'] as $face) {
if (!$font['preload'] && !$face['preload']) {
continue;
}
foreach ($face['files'] as $file) {
if ($file['mime'] !== 'font/woff2') {
continue;
}
$resources[$file['url']] = $file['mime'];
if (count($resources) >= $limit) {
break 3;
}
}
}
}
$html = '';
foreach ($resources as $url => $mime) {
$html .= sprintf('<link rel="preload" href="%s" as="font" type="%s" crossorigin>' . \PHP_EOL, htmlspecialchars($url, \ENT_QUOTES | \ENT_SUBSTITUTE, 'UTF-8'), htmlspecialchars($mime, \ENT_QUOTES | \ENT_SUBSTITUTE, 'UTF-8'));
}
return $html;
}
}
@@ -0,0 +1,161 @@
<?php
/*
* This file is part of the Jooosi Fon package.
*
* (c) Joshua Gugun Siagian <suabahasa@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare (strict_types=1);
namespace JooosiFon\Core;
use JooosiFonDeps\JOOOSI_FON;
use JooosiFon\Utils\Config;
use JooosiFon\Utils\Debug;
/**
* Serve the font on the frontpage.
*
* @author Joshua Gugun Siagian <suabahasa@gmail.com>
* @todo Remove the legacy Yabe Webfont hook shim completely in Jooosi Fon 3.0.0.
*/
final class Frontpage
{
/**
* @var string[]
*/
private array $preload_script_handles = [];
/**
* @var array<int, array<string, string>>
*/
private array $preload_resources = [];
private bool $print_preload_resources = \false;
public function __construct()
{
/**
* @see wp-includes\default-filters.php for the priority.
*/
add_action('wp_head', fn() => $this->append_header(), 1000001);
add_filter('wp_preload_resources', fn($resources) => $this->preload($resources));
add_action('wp_enqueue_scripts', fn() => $this->disable_user_google_fonts(), 1000001);
}
public static function enqueue_css_cache()
{
if (defined('JooosiFonDeps\JOOOSI_FON_CSS_CACHE_WAS_LOADED')) {
return;
}
Debug::stopwatch()->start(sprintf('%s::%s', self::class, __FUNCTION__));
if (file_exists(\JooosiFon\Core\Cache::get_cache_path(\JooosiFon\Core\Cache::CSS_CACHE_FILE))) {
$handle = JOOOSI_FON::WP_OPTION . '-cache';
$version = \JooosiFon\Core\Cache::get_cache_version(\JooosiFon\Core\Cache::CSS_CACHE_FILE) ?? JOOOSI_FON::VERSION;
if (Config::get('cache.inline_print', \false)) {
$css = file_get_contents(\JooosiFon\Core\Cache::get_cache_path(\JooosiFon\Core\Cache::CSS_CACHE_FILE));
if ($css !== \false) {
wp_register_style($handle, \false, [], null);
wp_add_inline_style($handle, $css);
}
} else {
wp_register_style($handle, \JooosiFon\Core\Cache::get_cache_url(\JooosiFon\Core\Cache::CSS_CACHE_FILE), [], $version);
}
do_action('a!jooosi/fon/core/frontpage:before_print_style');
do_action_deprecated('a!yabe/webfont/core/frontpage:before_print_style', [], '2.1.0', 'a!jooosi/fon/core/frontpage:before_print_style');
wp_enqueue_style($handle);
wp_print_styles($handle);
}
define('JooosiFonDeps\JOOOSI_FON_CSS_CACHE_WAS_LOADED', \true);
Debug::stopwatch()->stop(sprintf('%s::%s', self::class, __FUNCTION__));
}
/**
* Append the header to the frontpage.
*/
private function append_header()
{
if (function_exists('wp_preload_resources')) {
$this->print_preload_resources = \true;
wp_preload_resources();
$this->print_preload_resources = \false;
} else {
$this->preload([]);
}
self::enqueue_css_cache();
if ($this->preload_script_handles !== []) {
wp_print_scripts($this->preload_script_handles);
}
}
/**
* Preload the fonts file on the frontpage.
*/
private function preload($resources)
{
if (defined('JooosiFonDeps\JOOOSI_FON_PRELOAD_HTML_WAS_LOADED') && !$this->print_preload_resources) {
return $resources;
}
if (!defined('JooosiFonDeps\JOOOSI_FON_PRELOAD_HTML_WAS_LOADED')) {
Debug::stopwatch()->start(sprintf('%s::%s', self::class, __FUNCTION__));
if (file_exists(\JooosiFon\Core\Cache::get_cache_path(\JooosiFon\Core\Cache::PRELOAD_HTML_FILE))) {
$preload_html = file_get_contents(\JooosiFon\Core\Cache::get_cache_path(\JooosiFon\Core\Cache::PRELOAD_HTML_FILE));
if ($preload_html !== \false) {
preg_match_all('/<link\b[^>]*>/i', $preload_html, $link_tags);
foreach ($link_tags[0] as $link_tag) {
$rel = $this->get_attribute($link_tag, 'rel');
$href = $this->get_attribute($link_tag, 'href');
if (strtolower((string) $rel) !== 'preload' || $href === null) {
continue;
}
$resource = ['href' => $href];
foreach (['as', 'type', 'media', 'fetchpriority'] as $attribute) {
$value = $this->get_attribute($link_tag, $attribute);
if ($value !== null) {
$resource[$attribute] = $value;
}
}
if (stripos($link_tag, ' crossorigin') !== \false) {
$resource['crossorigin'] = '';
}
$this->preload_resources[] = $resource;
}
preg_match_all('/<script\b[^>]*>(.*?)<\/script>/is', $preload_html, $script_tags);
foreach ($script_tags[1] as $script) {
$script = trim($script);
if ($script === '') {
continue;
}
$handle = sprintf('%s-preload-%s', JOOOSI_FON::WP_OPTION, md5($script));
wp_register_script($handle, \false, [], null, \false);
wp_add_inline_script($handle, $script);
$this->preload_script_handles[] = $handle;
}
}
}
define('JooosiFonDeps\JOOOSI_FON_PRELOAD_HTML_WAS_LOADED', \true);
Debug::stopwatch()->stop(sprintf('%s::%s', self::class, __FUNCTION__));
}
return $this->print_preload_resources ? $this->preload_resources : $resources;
}
private function get_attribute(string $tag, string $attribute): ?string
{
$pattern = sprintf('/\b%s\s*=\s*([\'\"])(.*?)\1/is', preg_quote($attribute, '/'));
if (preg_match($pattern, $tag, $matches)) {
return html_entity_decode($matches[2], \ENT_QUOTES, 'UTF-8');
}
return null;
}
/**
* Scan and disable Google Fonts API that loaded manually by the theme or plugin through `wp_enqueue_style` function.
*/
private function disable_user_google_fonts()
{
$is_disable = Config::get('misc.disable_user_google_fonts', \false);
if (!$is_disable) {
return;
}
global $wp_styles;
foreach ($wp_styles->queue as $q) {
if ($wp_styles->registered[$q]->src && strpos($wp_styles->registered[$q]->src, 'fonts.googleapis.com') !== \false) {
wp_dequeue_style($q);
wp_deregister_style($q);
}
}
}
}
@@ -0,0 +1,23 @@
<?php
/*
* This file is part of the Jooosi Fon package.
*
* (c) Joshua Gugun Siagian <suabahasa@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare (strict_types=1);
namespace JooosiFon\Core;
/**
* @author Joshua Gugun Siagian <suabahasa@gmail.com>
*/
class Runtime
{
public function __construct()
{
new \JooosiFon\Core\Frontpage();
}
}
@@ -0,0 +1,100 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Database;
use RuntimeException;
/**
* Keeps the font library table available while the plugin is being rebranded.
*
* The migration history can survive an incomplete update, so table presence
* must not be inferred from a recorded migration version alone.
*/
final class FontTable
{
public static function migrateLegacy(): void
{
global $wpdb;
$legacyTable = self::legacyTable();
$table = self::table();
if (!self::exists($table)) {
if (self::exists($legacyTable)) {
self::rename($legacyTable, $table);
} else {
self::createTable($table);
}
} elseif (self::exists($legacyTable)) {
$columns = '`id`, `type`, `status`, `title`, `slug`, `family`, `metadata`, `font_faces`, `created_at`, `updated_at`, `deleted_at`';
if ($wpdb->query("INSERT IGNORE INTO `{$table}` ({$columns}) SELECT {$columns} FROM `{$legacyTable}`") === \false) {
throw new RuntimeException($wpdb->last_error ?: 'Unable to merge the legacy Jooosi Fon fonts table.');
}
}
self::assertExists($table);
}
/**
* Ensure the current table exists without merging a legacy table that has
* already been handled by the rebrand migration.
*/
public static function ensure(): void
{
$table = self::table();
if (self::exists($table)) {
return;
}
$legacyTable = self::legacyTable();
if (self::exists($legacyTable)) {
self::rename($legacyTable, $table);
} else {
self::createTable($table);
}
self::assertExists($table);
}
public static function create(): void
{
self::createTable(self::table());
}
public static function exists(?string $table = null): bool
{
global $wpdb;
$table = $table ?? self::table();
$foundTable = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->esc_like($table)));
return is_string($foundTable) && $foundTable === $table;
}
private static function rename(string $legacyTable, string $table): void
{
global $wpdb;
if ($wpdb->query("RENAME TABLE `{$legacyTable}` TO `{$table}`") === \false) {
throw new RuntimeException($wpdb->last_error ?: 'Unable to rename the Jooosi Fon fonts table.');
}
}
private static function createTable(string $table): void
{
global $wpdb;
if (!function_exists('dbDelta') && defined('ABSPATH')) {
require_once \ABSPATH . 'wp-admin/includes/upgrade.php';
}
if (!function_exists('dbDelta')) {
throw new RuntimeException('The WordPress database upgrade API is unavailable.');
}
$collation = $wpdb->has_cap('collation') ? $wpdb->get_charset_collate() : '';
$sql = "CREATE TABLE `{$table}` (\n `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,\n `type` VARCHAR(50) NOT NULL DEFAULT 'custom',\n `status` INT(1) NOT NULL DEFAULT 0,\n `title` VARCHAR(255) NOT NULL,\n `slug` VARCHAR(255) NOT NULL,\n `family` VARCHAR(255),\n `metadata` TEXT,\n `font_faces` TEXT,\n `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,\n `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,\n `deleted_at` DATETIME DEFAULT NULL,\n PRIMARY KEY (`id`)\n ) {$collation};";
dbDelta($sql);
}
private static function assertExists(string $table): void
{
global $wpdb;
if (!self::exists($table)) {
throw new RuntimeException($wpdb->last_error ?: 'Unable to create the Jooosi Fon fonts table.');
}
}
private static function table(): string
{
global $wpdb;
return $wpdb->prefix . 'jooosi_fon_fonts';
}
private static function legacyTable(): string
{
global $wpdb;
return $wpdb->prefix . 'yabe_webfont_fonts';
}
}
@@ -0,0 +1,54 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Database\Migration;
use JooosiFon\Database\Migration\Exception\AbortMigration;
use JooosiFon\Database\Migration\Exception\SkipMigration;
/**
* Base class for Jooosi Fon schema migrations.
*/
abstract class AbstractMigration
{
public function getDescription(): string
{
return '';
}
public function abortIf(bool $condition, string $message = 'Unknown reason'): void
{
if ($condition) {
throw new AbortMigration($message);
}
}
public function skipIf(bool $condition, string $message = 'Unknown reason'): void
{
if ($condition) {
throw new SkipMigration($message);
}
}
public function preUp(): void
{
}
public function postUp(): void
{
}
public function preDown(): void
{
}
public function postDown(): void
{
}
abstract public function up(): void;
public function down(): void
{
$this->abortIf(\true, sprintf('No down() migration implemented for "%s".', static::class));
}
protected function collation(): string
{
global $wpdb;
if (!$wpdb->has_cap('collation')) {
return '';
}
return $wpdb->get_charset_collate();
}
}
@@ -0,0 +1,8 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Database\Migration\Exception;
final class AbortMigration extends \JooosiFon\Database\Migration\Exception\MigrationException
{
}
@@ -0,0 +1,9 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Database\Migration\Exception;
use RuntimeException;
class MigrationException extends RuntimeException
{
}
@@ -0,0 +1,8 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Database\Migration\Exception;
final class SkipMigration extends \JooosiFon\Database\Migration\Exception\MigrationException
{
}
@@ -0,0 +1,63 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Database\Migration;
use WP_CLI_Command;
use function WP_CLI\Utils\format_items;
/**
* WP-CLI commands for Jooosi Fon migrations.
*/
final class MigrationCommand extends WP_CLI_Command
{
private \JooosiFon\Database\Migration\MigrationManager $manager;
public function __construct(\JooosiFon\Database\Migration\MigrationManager $manager)
{
$this->manager = $manager;
}
/**
* Generate a migration stub.
*
* ## OPTIONS
*
* [--table-name=<table-name>]
* : Optionally prefill a create/drop table migration.
*
* @when wp_loaded
*
* @param array<int, string> $args
* @param array<string, mixed> $assocArgs
*/
public function generate(array $args, array $assocArgs): void
{
$tableName = isset($assocArgs['table-name']) ? sanitize_key((string) $assocArgs['table-name']) : null;
$path = $this->manager->generate($tableName);
\WP_CLI::success(sprintf('Generated migration: %s', $path));
}
/**
* List discovered migrations and their execution state.
*
* @param array<int, string> $args
* @param array<string, mixed> $assocArgs
*/
public function list(array $args, array $assocArgs): void
{
format_items('table', $this->manager->list(), ['version', 'executed_at', 'execution_time', 'executed']);
}
/**
* Run all pending migrations.
*
* @param array<int, string> $args
* @param array<string, mixed> $assocArgs
*/
public function run(array $args, array $assocArgs): void
{
$executed = $this->manager->execute();
if ($executed === []) {
\WP_CLI::success('No pending migrations.');
return;
}
format_items('table', $executed, ['version', 'executed_at', 'execution_time']);
\WP_CLI::success(sprintf('%d migration(s) executed.', count($executed)));
}
}

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